1. Given a integer array which contains one odd repeated number and rest are even repeated numbers. Find the odd repeated number
Example:
Input:{1,2,1} returns 2
Input:{1,1,5,6,7,5,6,7,1 } return 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public static int FindOddrepNum(int[] a) { Dictionary tracker<int,bool> = new Dictionary<int,bool>(); foreach (int i in a) { if (!tracker.Keys.Contains(i)) { tracker.Add(i, true); } else { if (tracker[i]) { tracker[i] = false; } else { tracker[i]= true; } } } foreach (int i in a) { if (tracker[i]) { return i; } } return -1; } |
2.Given an integer array and a sum find the sets of corresponding two numbers in given array with that sum
Example: Input ({1,10,15,18,4,13,19,7,12,35},25)
Output :
Sum Giving Pair are:15-10
Sum Giving Pair are:7-18
Sum Giving Pair are:12-13
public static void FindSumSets(int[] a, int sum) { List tracker<int> = new List<int>(); foreach (int i in a) { tracker.Add(i); if (tracker.Contains((sum - i))) { Console.WriteLine("Sum Giving Pair are:{0}-{1}", i, sum - i); } } }
3.Given sorted integer array and a sum find the corresponding two numbers in given array with that sum
Example: Input ({1,4,7,10,12,13,15,18,19,35},25)
output:
Sum Giving Pair are:7-18
Sum Giving Pair are:10-15
Sum Giving Pair are:12-13
public static void FindSumSetsInAsc(int[] a, int sum) { int lower = 0; int upper = a.Length - 1; int testsum = 0; while (lower < upper) { testsum = a[lower] + a[upper]; if (testsum == sum) { Console.WriteLine("Sum Giving Pair are :{0}-{1}", a[lower], a[upper]); lower++; upper--; } else if (testsum < sum) { lower++; } else { upper--; } } }
3. Sort Character array
can use any standard sorting algorithm but here is the one with O(n) computing complexity.
public static char[] SortcharArray(char[] a) { int[] bucket = new int[256]; foreach (char c in a) { bucket[(int)c]++; } int k = 0; for(int i=0;i 0) { a[k] = (char)i; bucket[i]--; k++; } } return a; }
4. Given a rotated sorted array and an element. Find the position of the element.
Sorted array: {-3,3,4,6,7,8,9}
Input sorted array: {7,8,9,-3,3,4,6}
Given element 3 Output 4
public static void FindEleme(int[] a,int data) { int lower = 0; int upper = a.Length-1; int mid = 0; int range ; while (upper >=lower) { range=upper-lower; mid = ((range) / 2) + lower; if (range == 0&& a[lower]!=data) { Console.WriteLine("The Element is not in the Array"); return; } if (a[mid] == data) { Console.WriteLine("The element is {0}", mid); return; } if (a[mid + 1] > a[mid] && a[mid] > a[mid - 1]) { if (a[mid] < data) { lower = mid+1; } if (a[mid] > data) { upper = mid-1; } } if (a[mid + 1] > a[mid] && a[mid] < a[mid - 1]&&a[upper]<data) { upper = mid; } if (a[mid + 1] > a[mid] && a[mid] < a[mid - 1] && a[upper] >= data) { lower = mid; } } }

Sun, Jan 24, 2010
0 Comments