Array and Strings

| Comments

Array Problems

Sum of 2 numbers

We are given a sorted array A of length n and a value k. We want to find out if there are indices i, j such that A[i] + A[j] == k.

Give a Θ(n) way of solving this problem. Prove its running time and correctness.
Your algorithm should also output one pair of indices i, j such that A[i] + A[j] == k (if at least one pair exists; if multiple exist, you only need to output one of them).

Other variant of the same problem
When array is not sorted
We need to find pair of numbers in an array whose sum is equal to a given value.
Input [6,4,5,7,9,1,2]
Sum = 10
Then the pairs are [6,4] , [9,1]


Solution

There are three solutions

Sorted array
1. When array is sorted, take two index variable. Indx1 point to fisrt index and Indx2 points to the last index
2. If Indx1 + Indx2 < sum then increment the Indx1
3. Else if Indx1 + Indx2 > sum then decrement Indx 2
4. If Indx 1 > Indx 2 then halt -> No pairs found

If pair found then keep doing the same to find next pair.

Sorted array Run Code
 1
 2#include <stdio.h>
 3
 4void printPairs(int arr[], int arr_size, int sum)
 5{
 6    int front = 0;
 7    int back = arr_size - 1;
 8
 9    while (front < back) {
10        if (arr[front] + arr[back] < sum) {
11            front++;
12        } else if (arr[front] + arr[back] > sum) {
13            back--;
14        } else {
15            printf ("Pair with given sum %d is (%d, %d) \n",
16                    sum, arr[front], arr[back]);
17            back--;
18        }
19    }
20}
21
22/* Driver program to test above function */
23int main()
24{
25    int A[] = {4, 5, 6, 10, 12, 12};
26    int sum = 16;
27    int arr_size = 6;
28
29    printPairs(A, arr_size, sum);
30
31    return 0;
32}

Hashing/Binary Map
Another solution works for both sorted and unsorted array. In this approach we not actually using the hash function fundamental idea is to maintain the occurrence of number i.e. Binary Map

The caveat is that we need extra memory.

  1. Get the number from input array
  2. Num2 = Sum - arr[i]
  3. If we have encountered Num2 already in input array then we found a pair i.e.
    if(binMap[Num2] == 1)
  4. Else record input element in Binary map i.e. binMap[arr[i]] = 1;
Binary Map Run Code
 1
 2#include <stdio.h>
 3#define MAX 100000
 4
 5void printPairs(int arr[], int arr_size, int sum)
 6{
 7    int i = 0;
 8    int temp = 0;
 9    int binMap[MAX] = {0}; /*initialize hash map as 0*/
10
11    for(i = 0; i < arr_size; i++)
12    {
13        temp = sum - arr[i];
14        if(temp >= 0 && binMap[temp] == 1)
15        {
16            printf("Pair with given sum %d is (%d, %d) \n",
17                    sum, arr[i], temp);
18        }
19        binMap[arr[i]] = 1;
20    }
21}
22
23/* Driver program to test above function */
24int main()
25{
26    int A[] = {12, 4, 45, 6, 10, 12};
27    int sum = 16;
28    int arr_size = 6;
29
30    printPairs(A, arr_size, sum);
31
32    return 0;
33}

Bit Vector

This approach is similar to Binary map except using array for extra space we use bit vector to save some of extra space.

This program works for max for 31 as bit map is int which is 32 bits. For numbers more than 31 more memory could be allocated.

Bit Vector Run Code
 1
 2#include <stdio.h>
 3
 4void printPairs(int arr[], int arr_size, int sum)
 5{
 6    int i = 0;
 7    int temp = 0;
 8    int bitmap = 0; // all bits are 0
 9    int bitmask = 0;
10
11    for(i = 0; i < arr_size; i++)
12    {
13        temp = sum - arr[i];
14
15        bitmask = 0;
16        bitmask = 1 << temp;
17
18        if(temp >= 0 && (bitmap & bitmask))
19        {
20            printf("Pair with given sum %d is (%d, %d) \n",
21                   sum, arr[i], temp);
22        }
23        bitmap |= 1 << arr[i];
24    }
25}
26
27/* Driver program to test above function */
28int main()
29{
30    int A[] = {12, 4, 13, 6, 10, 3};
31    int sum = 16;
32    int arr_size = 6;
33
34    printPairs(A, arr_size, sum);
35
36    return 0;
37}


Sum of 2 numbers greater or equal to given sum*

We are given a sorted array A of length n and a value k. We want to find out if there are indices i, j such that A[i] + A[j] >= k.

Your algorithm should also output all the pairs of indices i, j such that A[i] + A[j] >= k



Sum of 3 numbers*

We need to find three numbers in an array whose sum is equal to a given value.



Find repeating/duplicate numbers*

Find all the numbers repeating in a array

Input [2,1, 3, 2, 3, 1, 4]

Output [2,1,3]



Find the number when size of array is unknown*

Given an array of integers find the given element is present when size of array is not given

Input array 2,1, 3, 2, 3, 1, 4

Element to find 3. Find solution in less than O(n) time.



Merge two sorted array

Input array1 [1, 3, 6, 7]
Input array2 [1, 2, 4]

Output [1, 1, 2, 3, 4, 6, 7]

Merge Sorted Arrays Run Code
  1
  2#include <stdio.h>
  3
  4int lSize = 4;
  5int rSize = 3;
  6int L[4] = {1, 3, 6, 7};
  7int R[4] = {1, 2, 4};
  8int finalArray[7];
  9
 10void merge()
 11{
 12    int lIndx = 0;
 13    int rIndx = 0;
 14    int i = 0;
 15
 16    for (i = 0; i < (lSize + rSize); i++) {
 17        if (L[lIndx] <= R[rIndx]) {
 18            finalArray[i] = L[lIndx++];
 19            if (lIndx == lSize) {
 20                break;
 21            }
 22        } else {
 23            finalArray[i] = R[rIndx++];
 24            if (rIndx == rSize) {
 25                break;
 26            }
 27        }
 28    }
 29
 30    i++;
 31    if (lIndx != lSize) {
 32        while(1) {
 33            finalArray[i++] = L[lIndx++];
 34
 35            if (lIndx == lSize) {
 36                return;
 37            }
 38        }
 39    }
 40    if (rIndx != rSize) {
 41        while(1) {
 42            finalArray[i++] = R[rIndx++];
 43
 44            if (rIndx == rSize) {
 45                return;
 46            }
 47        }
 48    }
 49}
 50
 51void display()
 52{
 53    int i = 0;
 54
 55    printf("\n\nArray1: ");
 56    for (i = 0; i < lSize; i++) {
 57        printf("%d ", L[i]);
 58    }
 59
 60    printf("\nArray2: ");
 61    for (i = 0; i < rSize; i++) {
 62        printf("%d ", R[i]);
 63    }
 64
 65    printf("\nMerge array: ");
 66    for (i = 0; i < lSize+rSize; i++) {
 67        printf("%d ", finalArray[i]);
 68    }
 69}
 70
 71int main()
 72{
 73    // Test 1
 74    merge();
 75    display();
 76
 77    // Test 2
 78    R[0] = 1;
 79    R[1] = 3;
 80    R[2] = 6;
 81    R[3] = 7;
 82    L[0] = 1;
 83    L[1] = 2;
 84    L[2] = 4;
 85    lSize = 3;
 86    rSize = 4;
 87    merge();
 88    display();
 89
 90    // test 3
 91    L[0] = 1;
 92    R[0] = 1;
 93    lSize = 1;
 94    rSize = 1;
 95    merge();
 96    display();
 97
 98    return 0;
 99}


Merge 2 non sorted array and remove duplicates

Input array1 [6, 3, 6, 1, 7]
Input array2 [5, 1, 2, 4, 6]

Output could be in sorted order or non-sorted order based on algorithm you choose to solve it.

Output [1, 2, 3, 4, 5, 6, 7] OR
Output [6, 3, 1, 7, 5, 2, 4] OR
Output [5, 1, 2, 4, 6, 3, 7] OR
Output [6, 5, 3, 1, 2, 4, 7] etc…

Merge Unsorted Arrays Run Code
 1
 2#include <stdio.h>
 3
 4#define ARR1SIZE 5
 5#define ARR2SIZE 5
 6
 7int main()
 8{
 9    int arr1[] = {6, 3, 6, 1, 7};
10    int arr2[] = {5, 1, 2, 4, 6};
11    int arr3[ARR1SIZE + ARR2SIZE];
12
13    // Using bit map, All bits are 0
14    int bitMap = 0;
15    int bitMask = 0;
16    int i = 0;
17    int k = 0;
18
19    for (i = 0; i < ARR1SIZE; i++) {
20        // Check if value already exist
21        bitMask = 0;
22        bitMask = 1 << arr1[i];
23
24        if (bitMap & bitMask) {
25            continue;
26        }
27        arr3[k++] = arr1[i];
28
29        // Mark bitMap that value exist
30        bitMap |= 1 << arr1[i];
31    }
32
33    for (i = 0; i < ARR2SIZE; i++) {
34        // Check if value already exist
35        bitMask = 0;
36        bitMask = 1 << arr2[i];
37
38        if (bitMap & bitMask) {
39            continue;
40        }
41        arr3[k++] = arr2[i];
42
43        // Mark bitMap that value exist
44        bitMap |= 1 << arr2[i];
45    }
46
47    printf("Merged Array\n");
48    for (i = 0; i < k; i++) {
49        printf("%d ", arr3[i]);
50    }
51
52    return 0;
53}


Sort array based on count

Given number in array [2, 1, 3, 2, 1, 4] sort array based on count of numbers.

Sort them as [1, 1, 2, 2, 3, 4]

Counting Sort Run Code
 1
 2#include <stdio.h>
 3
 4#define ARRAYSIZE 6
 5#define MAX 4
 6
 7int main()
 8{
 9    int arr[] = {2, 1, 3, 2, 1, 4};
10    int final[ARRAYSIZE];
11
12    // Given we know max element in array
13    // This technique is based on counting sort
14    int count[MAX + 1] = {0};
15    int i = 0;
16    int j = 0;
17
18    for (i = 0; i < ARRAYSIZE; i++) {
19        count[arr[i]]++;
20    }
21
22    for (i = 0; i < MAX + 1; i++) {
23        if (count[i] != 0) {
24            while (count[i] != 0) {
25                final[j++] = i;
26                count[i]--;
27            }
28        }
29    }
30
31    printf("Sorted Array\n");
32    for (i = 0; i < ARRAYSIZE; i++) {
33        printf("%d ", final[i]);
34    }
35
36    return 0;
37}


Find odd number of occurrence

Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space.

Odd occurence
 1
 2#include <stdio.h>
 3 
 4int getOddOccurrence(int ar[], int ar_size)
 5{
 6     int i;
 7     int res = 0; 
 8     for (i=0; i < ar_size; i++)     
 9        res = res ^ ar[i];
10      
11     return res;
12}
13 
14/* Diver function to test above function */
15int main()
16{
17     int ar[] = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
18     int n = sizeof(ar)/sizeof(ar[0]);
19     printf("%d", getOddOccurrence(ar, n));
20     return 0;
21}



Find 2 numbers with odd occurence

Given an unsorted array that contains even number of occurrences for all numbers except two numbers. Find the two numbers which have odd occurrences in O(n) time complexity and O(1) extra space.

Input: [12, 23, 34, 12, 12, 23, 12, 45]
Output: 34 and 45

Input: [4, 4, 100, 5000, 4, 4, 4, 4, 100, 100]
Output: 100 and 5000

Input: [10, 20]
Output: 10 and 20

Solution Explanation

2 Odd Num
 1
 2// Program to find the two odd occurring elements
 3#include<stdio.h>
 4 
 5/* Prints two numbers that occur odd number of times. The
 6   function assumes that the array size is at least 2 and
 7   there are exactly two numbers occurring odd number of times. */
 8void printTwoOdd(int arr[], int size)
 9{
10  int xor2 = arr[0]; /* Will hold XOR of two odd occurring elements */
11  int set_bit_no;  /* Will have only single set bit of xor2 */
12  int i;
13  int n = size - 2;
14  int x = 0, y = 0;
15 
16  /* Get the xor of all elements in arr[]. The xor will basically
17     be xor of two odd occurring elements */
18  for(i = 1; i < size; i++)
19    xor2 = xor2 ^ arr[i];
20 
21  /* Get one set bit in the xor2. We get rightmost set bit
22     in the following line as it is easy to get */
23  set_bit_no = xor2 & ~(xor2-1);
24 
25  /* Now divide elements in two sets: 
26    1) The elements having the corresponding bit as 1. 
27    2) The elements having the corresponding bit as 0.  */
28  for(i = 0; i < size; i++)
29  {
30     /* XOR of first set is finally going to hold one odd 
31       occurring number x */
32    if(arr[i] & set_bit_no)
33      x = x ^ arr[i];
34 
35     /* XOR of second set is finally going to hold the other 
36       odd occurring number y */
37    else
38      y = y ^ arr[i]; 
39  }
40 
41  printf("\n The two ODD elements are %d & %d ", x, y);
42}
43
44/* Driver program to test above function */
45int main()
46{
47  int arr[] = {4, 2, 4, 5, 2, 3, 3, 1};
48  int arr_size = sizeof(arr)/sizeof(arr[0]);
49  printTwoOdd(arr, arr_size);
50
51  return 0;
52}


Searching an Element in a Rotated Sorted Array

This article explains the reasoning for searching an element in a rotated sorted array.

It even explains how to find the minimum number i.e. from where rotation started.




Largest Sum Contiguous Subarray

Write an efficient C program to find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum.

Array [-2, -3, 4, -1, -2, 1, 5, -3]
Sum 7

Largest Sum Run Code
 1
 2#include <stdio.h>
 3
 4int main()
 5{
 6    int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3};
 7
 8    int best = -1110;
 9    int sum = 0;
10    int indx = 0;
11    int i = 0;
12    int x = 0; // start of max sub array
13    int y = 0; // end of max sub array
14    int n = 8; // size of array
15
16    for (i = 0; i < n; i++) {
17        if (sum <= 0) {
18            sum = arr[i];
19            indx = i;
20        } else {
21            sum += arr[i];
22        }
23
24        if (best < sum) {
25            best = sum;
26            x = indx;
27            y = i;
28        }
29    }
30
31    printf("Max sum %d, start index %d, end index %d\n", best, x, y);
32
33    return 0;
34}


Permute numbers

Write all the non repeating permutations of given numbers i.e.

Input = [1, 2, 3, 4]
Output
1 2 3 4
1 2 3 4
1 2 4 3 …

This problem is on the same footstep of string permutation

Permute Numbers Run Code
 1
 2#include <stdio.h>
 3#include <string.h>
 4
 5#define TEST 1
 6
 7void permute(int *s, int start, int end);
 8void swap(int *s, int start, int end);
 9void startTesting();
10
11int main(void) {
12#ifdef TEST
13    startTesting();
14#endif
15
16    return 0;
17}
18
19void swap(int *s, int start, int end) {
20    int temp = s[start];
21    s[start] = s[end];
22    s[end] = temp;
23}
24
25void permute(int *s, int start, int end)
26{
27    int i = 0;
28    int j = 0;
29
30    if (start == end) {
31        for (i = 0; i < 4; i++) {
32            printf("%d ", s[i]);
33        }
34        printf("\n");
35    } else {
36        for (j = start; j <= end; j++) {
37            swap(s, start, j);
38            permute(s, start + 1, end);
39            swap(s, start, j);
40        }
41    }
42}
43
44void test1()
45{
46    int s[] = {1, 2, 3, 4};
47    int i = 0;
48
49    printf("permute \n");
50    for (i = 0; i < 4; i++) {
51        printf("%d ", s[i]);
52    }
53    printf("\n");
54
55    permute(s, 0, 3);
56    printf("\n");
57}
58
59void startTesting()
60{
61    test1();
62}


String Problems

Reverse a string without extra space

String could be reversed without using extra space using bitwise operator XOR

String Reverse Run Code
 1
 2#include <stdio.h>
 3#include <string.h>
 4 
 5 
 6int main(void) {
 7    int i = 0;
 8    char str[] = "testString";
 9    int len = strlen(str);
10 
11    for(i = 0; i < len/2; i++){
12        str[len - i - 1] ^= str[i];
13        str[i] ^= str[len - i - 1];
14        str[len - i - 1] ^= str[i];
15    }
16
17    printf("Reverse String %s \n", str);
18 
19    return 0;
20}
21




Duplicates and Count

Print all duplicate characters and their count

Input string
Foo Bar

Output
a1B1F1o2r1

Duplicate & count Run Code
 1
 2#include <stdio.h>
 3
 4void printDup(char *str)
 5{
 6    int count[256] = {0};
 7    int i = 0;
 8
 9    while (*str != '\0') {
10        count[*str++]++;
11    }
12
13    for (i = 0; i < 256; i++) {
14        if (count[i] > 0) {
15            printf("%c %d\n", i, count[i]);
16        }
17    }
18}
19
20int main()
21{
22    char *str = "Foo Bar";
23
24    printDup(str);
25
26    return 0;
27}


Remove all consecutive duplicate elements

Remove all consecutive duplicate elements from the string

Input string
aabbccddd

Output
abcd

Remove dup
 1
 2void removeDup(char *str)
 3{
 4    int read = 0;
 5    int write = 0;
 6
 7    while (str[read] != '\0') {
 8        while (str[read] != '\0' && str[read] != str[read + 1]) {
 9            str[write++] = str[read++];
10        }
11
12        while (str[read] != '\0' && str[read] == str[read++]);
13    }
14}


Rotate a string

Rotate a string for a ‘n’ times

Input string
1234567
len = 7
Rotate 2 times

Output
3456712

Step 1

Break array into 2 parts from index 2 as number of time to rotate is 2

[1 2] [3 4 5 6 7]

Step 2

Reverse both arrays

[2 1] [7 6 5 4 3]

Step 3

Reverse all

Result = [3 4 5 6 7 1 2]

Rotate Array Run Code
 1
 2#include <stdio.h>
 3
 4void reverseArr(int arr[], int start, int end)
 5{
 6    int temp = 0;
 7
 8    while (start < end) {
 9        temp = arr[start];
10        arr[start] = arr[end];
11        arr[end] = temp;
12
13        start++;
14        end--;
15    }
16
17}
18
19int main()
20{
21    int arr[] = {1, 2, 3, 4, 5, 6, 7};
22    int rotate = 2;
23    int size = 7;
24    int i = 0;
25
26    reverseArr(arr, 0, rotate - 1);
27    reverseArr(arr, rotate, size - 1);
28    reverseArr(arr, 0, size - 1);
29
30    for (i = 0; i < size; i++) {
31        printf("%d ", arr[i]);
32    }
33
34    return 0;
35}


Permutation of a string

Permutation






algorithms, array, strings

« Graph Algorithms D3.js and Octopress »

Comments