数组面试算法题

1. question: Given an integer array of which both first half and second half are sorted. Write a function to merge the two parts to create one single sorted array in place [do not use any extra space].

e.g. If input array is [1,3,6,8,-5,-2,3,8] It should be converted to: [-5,-2,1,3,3,6,8,8]

 

2.question: Maximum contigous subarry for one dimensional array, After that modified this for 2d array. Find the biggest square or rect matrix such that sum is max.

 

3. QUESTION: Given a sorted array, output all triplets <a,b,c> such that a-b = c. Expected time is O(n^2). My approach using binary search took O(n^2 logn). When you attempt an approach, test your code with this example and list your outputs for verification. Thanks.
-12, -7, -4, 0, 3, 5, 9, 10, 15, 16

answer:

The problem can be simplified to find a pair in a sorted array to have a sum value. Then repeat this operation from end to start.

1.The idea is to find (a,b,c) such that a-b=c ..in other words, a=b+c;

2. We know that if an array is sorted, we can find two numbers(b,c) which sum up to a
particular value(a) in O(n) time.

3. So start from the end of the array.For each value a[i], search for sum=a[i] between a[0] and a[i-1]. Starting from the end makes sure we can eliminate any option to the right of that element as such an element will not satisfy the equation a=b+c

4. Complexity =n*O(n) =O(n^2);

 

4. QUESTION: Given two sorted arrays a[] and b[]. Merge them and answer should be stored in a[] with minimum complexity. Suppose a has the extra spaces for the elements in B.

answer:

move all elements in a[] to the end part, then merge a[] and b[]

 

5. QUESTION: Given 2 unsorted arrays, find the intersection of the two arrays (optimal soln).
He was asking for various approaches and complexity in all those approaches.Finally, he was interested in the solution using array-sorting.

answer:

sort the smaller array. now binary search for each element of larger array in the smaller array. complexity=O(mlgm+nlgm). mlgm to sort and nlgm to check if each element of larger array exists in smaller array . doing other way round leads to complexity of O((m+n)lgn). so first way is better.

 

6. QUESTION: Given a rotated-sorted array find the point of rotation. Complexity less than O(n).

Example:
Index: 0 1 2 3 4
Value: 4 5 1 2 3
Ans: 2 (index)

answer:

use a modified binary search algorithm and the check condition is a[i]<a[i-1] 

 

7. QUESTION: search a number in a sorted array of the form
eg: 4 5 6 1 2 3 in O(logn).

answer:

use a modified binary search algorithm

 

8. QUESTION: Given an infinite size array with only 0s and 1s and sorted. find the transition point where 0s end or 1s start (written test case. coding)

answer:

This can be done by modified binary search.....
1.At first check the 2^i the index i=0,1,2,....
2.If '1' occurs at some point of index [example say 32 i.e. 2^5]
3.Apply binary search between 2^4 and 2^5 [in infinite array the problem is we ill not have the info of high to apply binary search....]

 

9. QUESTION: Given an array of elements find the largest possible number that can be formed by using the elements of the array.
eg: 10 9
ans: 910
2 3 5 78
ans: 78532
100 9
ans: 9100

answer:

use a custom string comparision algorithm when comparing two integers. suppose you are comparing DBC with ZU and you can comparing them with DBC with ZUU

 

10. QUESTION: Give an algorithm that determines the number of inversions in any permutation of n elements (stored as an array) in o(n lg n)

answer:

use a custom merge sort 

 

11. QUESTION: Given an array A[i..j] find out maximum j-i such that A[i]<a[j] in O(n) time.

 answer:

To solve this problem, we need to get two optimum indexes of arr[]: left index i and right index j. For an element arr[i], we do not need to consider arr[i] for left index if there is an element smaller than arr[i] on left side of arr[i]. Similarly, if there is a greater element on right side of arr[j] then we do not need to consider this j for right index. So we construct two auxiliary arrays LMin[] and RMax[] such that LMin[i] holds the smallest element on left side of arr[i] including arr[i], and RMax[j] holds the greatest element on right side of arr[j] including arr[j]. After constructing these two auxiliary arrays, we traverse both of these arrays from left to right. While traversing LMin[] and RMa[] if we see that LMin[i] is greater than RMax[j], then we must move ahead in LMin[] (or do i++) because all elements on left of LMin[i] are greater than or equal to LMin[i]. Otherwise we must move ahead in RMax[j] to look for a greater j – i value.

Time Complexity: O(n)
Auxiliary Space: O(n)

#include <stdio.h>   /* Utility Functions to get max and minimum of two integers */int max(int x, int y) {     return x > y? x : y; }   int min(int x, int y) {     return x < y? x : y; }   /* For a given array arr[], returns the maximum j – i such that     arr[j] > arr[i] */int maxIndexDiff(int arr[], int n) {     int maxDiff;     int i, j;       int *LMin = (int *)malloc(sizeof(int)*n);     int *RMax = (int *)malloc(sizeof(int)*n);      /* Construct LMin[] such that LMin[i] stores the minimum value        from (arr[0], arr[1], ... arr[i]) */    LMin[0] = arr[0];     for (i = 1; i < n; ++i)         LMin[i] = min(arr[i], LMin[i-1]);       /* Construct RMax[] such that RMax[j] stores the maximum value        from (arr[j], arr[j+1], ..arr[n-1]) */    RMax[n-1] = arr[n-1];     for (j = n-2; j >= 0; --j)         RMax[j] = max(arr[j], RMax[j+1]);       /* Traverse both arrays from left to right to find optimum j - i         This process is similar to merge() of MergeSort */    i = 0, j = 0, maxDiff = -1;     while (j < n && i < n)     {         if (LMin[i] < RMax[j])         {             maxDiff = max(maxDiff, j-i);             j = j + 1;         }         else            i = i+1;     }       return maxDiff; }   /* Driver program to test above functions */int main() {     int arr[] = {9, 2, 3, 4, 5, 6, 7, 8, 18, 0};     int n = sizeof(arr)/sizeof(arr[0]);     int maxDiff = maxIndexDiff(arr, n);     printf("\n %d", maxDiff);     getchar();     return 0; }


 

12. QUESTION: Given an array of ints, is it possible to divide the ints into two groups, so that the sums of the two groups are the same. Every int must be in one group or the other. Write a recursive helper method that takes whatever arguments you like, and make the initial call to your recursive helper from splitArray(). (No loops needed.)

splitArray({2, 2}) → true
splitArray({2, 3}) → false
splitArray({5, 2, 3}) → true

answer: (the algorithm may not  be correct since I do not very understand it and not verify it at all. I guess this is a backtracking problem)

//using dynamic programming

bool splitArray(int[] array){
int sum = sum(array);
int i = count(array);
return Q(array, i, sum/2);
}

Q(int[] array, int i, int sum){
if(i == 1){
return array[i]==sum?true:false;
}
if((array[i]==sum)
|| Q(array, i-1, sum-array[i]) //have a subset with array[i]
|| Q(array.removeAt(i), i-1, sum)) //have a subset without array[i]
return true;
else
return false;
}

  

13. QUESTION: Given array of integers , return an index such that it devides the array in 2 parts ,i.e.sum of all elements which are left side of the index = sum of all elements which are right side of the index. Do in linear time.

answer:

1. Caluculate the whole sum of elements presented in the Array
2. Maintain a variable which holds the sum of elements till that elements i.e.CumSum ( excludes present element).

3. Return the index of the array when 2*CumSum+ current element = sum of all elements in the array

 

14. QUESTION: Given an array containing lower case and upper case alphabets and numbers, how can you sort/arrange the array in one single pass using just one variable for swapping such that the resultant array should put the input elements into 3 buckets in the following fashion -
Input - aA1B23Cbc4
Output - abcABC1234

Note - ordering doesn't matter
the output could be -
ABC1234abc or 1234abcABC

You just have to arrange the data into 3 buckets in single pass using just one temp variable for swapping. Expected runtime - o(n)

answer:

use two pointers to make sure digit is on the left of the first pointer and uppercase character is on the right of the second pointer.

import java.util.Arrays;

public class Arrange {
	public static void switchElement(char[] input, int x, int y) {
		char z = input[x];
		input[x] = input[y];
		input[y] = z;
	}
	public static void arrange(char[] input) {
		int start = -1;
		int end = input.length;
		for(int i=0; i<end; ) {
			if(input[i]>='a' && input[i]<='z' && i!=0) {
				//move to begin
				switchElement(input, ++start, i);
			} else if(input[i]>='0' && input[i]<='9' && i!=input.length-1) {
				switchElement(input, i, --end);
			} else {
				i++;
			}
		}
	}
	public static void main(String[] args) {
		char[] input = "aA1B23Cbc4".toCharArray();
		System.out.println(Arrays.toString(input));
		arrange(input);
		System.out.println(Arrays.toString(input));
	}
}


15. QUESTION: Given an array of n elements such that one element repeats n/2 times and rest of the elements are distinct, how to find the repeating element ?

answer:

use two variables: one is for the current value and the other is for the count. Scan the array and if the next value is same as the current value then the count plus 1, otherwise minus 1 and if it equals 0, then use next  value as the current value......

 

16. QUESTION: There is very long array of ints, and you are given pointer to base addr of this array.. each int is 16bit representation... you need to return the pointer to tht "bit" inside array where longest sequence of "1"s start

answer:

1) use mod 2 to get binary presentation

2) search the max lengh 1 position

 

17. QUESTION: Given two arrays A [n] and B[m], find the smallest window in A that contains all the elements of B.

answer

1) find the first window in A

2) then remove the first element in A then search forward to find the second window

3) remember the index during moving

 

18. QUESTION: Find median of two sorted arrays.

answer:

Modified binary search

 

19. QUESTION: How do you determine if every digit in the binary representation of a number is a one?

answer:

Adding 1 to all 1s will produce a perfect power of 2=> n & (n+1) == 0 or return ~x==0

 

 

20. QUESTION: Check if two given strings are anagrams?

answer:

count sorting on the two strings then do compare, O(N)

 

21. QUESTION: Reverse a string as per the words, not the entire reverse. eg; "I am Sam" --> "Sam am I"

answer:

reverse (in place) each word > I ma maS
reverse whole sentence > Sam am I

 

22. QUESTION: Given a two strings, determine if one is a circular permutation of the other or not. For example abcd, cdab are circular permutations

 answer:

concatenate the original string
back to back
and then find the rotated string as a substring
if it exists you are done

 

23. QUESTION: Find the FIRST non-repeating character in a string.

answer:

I can only provide a O(N) with hashmap or count array.

With some ristriction, we can do this in O(1) space like we know it only includes 26 characters. Or we can use a long to replace the count array.

 

24. QUESTION: Write function compress(char* strSource)
it should do the following .
repeating chars in sequence should be replaced with char & count, in case count is 1 no need to add any integer.
Example - AAAABBBCXYZEEEEPPPPPKKABC
should be A4B3CXYZE4P5K2ABC.
you are supposed to iterate the array only once, and modify the same input parameter, do not create any new string.

answer:

keep 3 pointers to move and need to pay more attention on the count length like 256 etc

 

25. QUESTION: For an array of integers, find if there are 3 numbers that add up to zero. An algorithm of complexity O(n^2) was required.

answer:

1) sort the array (nlgn)

2) convert a+b+c=0 to a=-(b+c)

3) iterate the array to find the combination nxn

 


26. QUESTION: How to find the median from a randomly generated 1 billion integers? 
answer:

To think of using specific data structure or approach so that the entire integer need not be sorted (to identity integer such that half the integers fall to the left and other half fall to the right of it)

 

27. QUESTION:  Write a program to remove duplicate elements from array.(Array contains elements in range 1...N). Algorithm must be O(N) in time and O(1) in space. Come up with as many test cases as you can.

Answer:

same as the next

 


28. QUESTION: Array A[n] it contains numbers from 1 to n but 1 number repeated. Find out missing number.

Answer:

[Solution 1]

1) calculate the sum with normal and present to know x-y=m

2) calculate the product with normal and present to know x/y=n

3) calculate x and y

 

[Solution 2]

(No extra spaces used and time complexity is O(n))

public class Test {
	public static int checkMissing(int[] array) {
		int missing = -1;
		int index = 0;
		while (index < array.length) {
			if (array[index] < 0 /* no target */|| array[index] == index + 1 /* in place */) {
				index++;
				continue;
			} else {
				if (array[index] == array[array[index] - 1]) {
					array[index] = 0 - array[index];
				} else {
					int n = array[array[index] - 1];
					array[array[index] - 1] = array[index];
					array[index] = n;
				}
			}
		}
		for (int i = 0; i < array.length; i++) {
			if (array[i] < 0) {
				missing = i + 1;
			}
		}
		return missing;
	}

	public static void main(String[] args) {
		System.out.println(checkMissing(new int[] { 11, 6, 2, 9, 1, 9, 4, 7, 3, 8, 10, 13, 12 }));
	}
}  

29. QUESTION: Given an array of size 2N, such that its elements are as follows:{a1,a2,a3,...,an,b1,b2,b3...,bn}You have to rearrange this array, without using any extra array such that resulting array would be:{a1,b1,a2,b2,...,an,bn} answer:First swap elements in the middle pairNext swap elements in the middle two pairsNext swap elements in the middle three pairs iterate n-1 steps 30: question: Write a function to print all unique partitions on n tht are of size m. eg: n=10, m=4. it should print 7 1 1 1, 6 2 1 1, 5 3 1 1, 3 3 2 2,, so onanswer:this should be a backtracking problem 31: QUESTION:if you had an array of numbers from 0 to 1 million, how would you figure out the missing numberanswer:Use XOR on all elements in this array, then XOR on all elements from 1 to 1 million 32: QUESION: two arrays a and b of size n+2 and n, resp. The array b is obtained from a by removing two distinct elements, say x and y, and randomly shuffling the remaining ones. Given a and b, find the removed elements x and y. Do this in O(n) time and O(1) space.answer:First, I assume you know how to solve the simpler problem when A and B have size n+1 and n and they differ by only one element, where you just XOR all the elements of both arrays together and all the common values cancel each other out, leaving the unique value.The problem for two elements is a reduction to that special case. If you XOR all the elements of A and B then you get z = x ^ y as the result. Since x and y are presumed distinct, they must differ in at least one bit, and hence z must be nonzero in at least one bit, let's say the i-th. That partitions each of A and B into two parts, one where elements have 0 in their i-th bit, and one where elements have 1 in their i-th bit. By construction, x and y occur in separate parts, so we get a reduction to the earlier special caseusing the following code to find the different bitint m = 1;while (!(z & m))m <<= 1;To this:int m = z ^ (z-1);XOR-ing the number to it's -1 decremented pair will give you the rightmost set bit.(Of course your solution works too).

33: QUESTION: Given an array of integers, find second largest element in an array.

This can be solved in n +logn -2 comparision using tournament method or max heap

34: Given an array of positive and negative integers find the first subarray with zero sum? no 0's will be a part of the input array and handle all the edge cases

Answer:

1) put the first element into a hash map as the form <sum, index>

2) loop from the second element to the end, calculate the sum from the first to the present and check if the sum is 0, it should be the subarray from the first to now. if it equals any of the sum, the subarray should be from that index to no, otherwise, continue the loop.

3) the overflow should be taken into consideration in the algorithm.









  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值