Sunday, August 18, 2013

Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

Solution:
1. Brute Force. Takes O(n^3).
2. Look here for the Leetcode explanation which uses DP. Time and space complexity O(n^2).
    There is also a O(n) solution which we shall see in a later post.

Code:
(same as in the link)

class Solution {
public:
    string longestPalindrome(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
       bool flag[1000][1000] = {false};
       int n=s.length();
       int longestBegin = 0;
       int maxlen = 1;
       int i,j;
       for(i=0; i<n; i++)
       {
           flag[i][i] = true;
       }
       for(i=0; i<n-1; i++)
       {
           if (s[i]==s[i+1])
           {
               flag[i][i+1]= true;
               longestBegin = i;
               maxlen = 2;
           }
       }
       for(int len = 3; len <= n; len++)
       for(i=0; i<n-len+1;i++)
       {
           j=i+len-1;
           if(s[i]==s[j] && flag[i+1][j-1]==true)
           {
               flag[i][j]=true;
               longestBegin = i;
               maxlen = len;
           }
       }
       return s.substr(longestBegin,maxlen);
    }
};

Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Solution:

A rather easy question. We'll just have to keep in mind the carry at the end of either or both of the linked lists given.

Code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
      ListNode *p1 =l1;
      ListNode *p2 =l2;
      ListNode *head = NULL;
      ListNode *temp = NULL;
      ListNode *tail = NULL;
      int sum =0;
      int carry =0;
      while(p1 && p2)
      {
         sum = carry+p1->val+p2->val;
         carry = sum/10;
         sum = sum%10;
         temp = new ListNode(sum);
         if(head==NULL) {head = temp; tail = temp;}
         else
         {tail->next = temp; tail = temp;}
         p1=p1->next;
         p2=p2->next;
      }
      while(p1)
      {
          sum = carry+p1->val;
          carry = sum/10;
          sum = sum%10;
          temp = new ListNode(sum);
          tail->next= temp;
          tail = temp;
          p1=p1->next;
      }
      while(p2)
      {
         sum = carry+p2->val;
          carry = sum/10;
          sum = sum%10;
          temp = new ListNode(sum);
          tail->next= temp;
          tail = temp;
          p2=p2->next;
      }
      if(carry)
      {
          temp = new ListNode(carry);
          tail->next= temp;
          tail = temp; 
      }
        return head;
    }
 
};

Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

There are 2 ways to solve this in better than O(n^2)
1. Sort the given array. Take 2 pointers, one at the start, other at the end. 
if their sum exceeds the target, decrement the end pointer. If their sum is less than the target increment the start pointer.Do this until you find a pair.
Takes no extra space. Time Complexity O(nlogn).

2. The other approach is to use map. Map the elements of the array. Take the elements one by one, subtract it from the target and search for the (target-element) part in the map.
Time and Space Complexity O(n).

Code :

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> result;
        map<int, int> mymap;
        int i;
        int toSearch;
        for(  i=0; i<numbers.size();++i)
        mymap[numbers[i]]= i;
        for(i=0; i<numbers.size(); ++i)
        {
            toSearch = target-numbers[i];
            if(mymap.find(toSearch)!=mymap.end())
            {
                result.push_back(i+1);
                result.push_back(mymap[toSearch]+1);
            }
        }
    return result;
    }
};