Download CSE101 array/data structure questions latest upload and more Exams Advanced Education in PDF only on Docsity!
CSE101 array/data structure questions latest
upload
- Given an integer x and an array of numbers, find if two numbers in the array sum up to x. (Or, find the pair of numbers whose sum is closest to x.): Array A[n], x 1.)-----------------------Sort using Mergesort O(nlogn) 2.) Initialize two index variables to find candidit a.) Initialize first to the leftmost index: l = 0 b.) Initializ second the rightmost index: r = n - 1 3.)----------------While l < r O(n) a.) if A[l] + A[r] == x; return true b.) else if A[l] + A[r] < sum; increment l c.)else decrement r 4.) return false Time Complexity: Step 1.) uses mergesort which takes O(nlogn) as discussed in class. Step 3.) uses O(n) time since the worst case is going through the entire array. Total Running Time = O(nlogn + n) = O(nlogn)
- Given two sorted arrays, find the median of the union of elements: Arrays A[n] with size n, B[k] with size k 1.) Use mergesort on A[n] and B[k] - O((n+k)log(n+k)) a.) returns temp[n+k] of size n+k 2.) Initialize length len with n + k 3.) if len modulus 2 == 0 a.) return (temp[len/2-1] + temp[len/2])/ 4.) return (temp[len/2]) Time Complexity: Step 1.) has a time complexity of O((n+k)log((n+k)) since mergesort has to sort arrays of size n and
k. All other operations are O(1) Total Running Time = O((n+k)log(n+k))
- Given two sorted arrays, find the kth smallest element in the union of elements.: Array A[n] of size n, Array B[m] of size m, k smallest element 1.) Use Mergesort on arrays A + B - O((n+m)log(n+m) a.) return Array temp[n+m] of size n+m 2.) return temp[k - 1] Time Complexity: Step 1.) has a time complexity of O((n+m)log(n+m) since mergesort has to sort arrays of size n and m. Total Running time is O((n+m)log(n+m)
- Do the above two questions when there are l sorted arrays. What is the running time?: Q.2) Array A[n][m], B[nm] 1.) initialize an index to 0 2.)--------------------For i from 0 to n- 1 O(n) a.)---------------------For j from 0 to m- 1 O(m) i.) B[index] = A[i][j] ii.)index++; 3.)------------------Mergesort on B O((nm)log(nm)) a.) returns an array temp[n+m] of size n+m 4.) Initialize length len with n + m 5.) if len modulus 2 == 0 a.) return (temp[len/2-1] + temp[len/2])/ 6.) return (temp[len/2]) Q.3) Array A[n][m] with size n rows and size m columns, B[nm] of size n*m 1.) initialize an index to 0 2.)--------------------For i from 0 to n- 1 O(n) a.)---------------------For j from 0 to m- 1 O(m) i.) B[index] = A[i][j]
algorithm that is Θ(n^2 ) (you can do much better than that): Array A[n] of size n, Vector v 1.) int first, temp = 0; 2.)----------------------------for i from 0 to n- 1 O(n) a.) max_ending_here = max_ending_here + A[i] b.) if (max_ending_here < 0) i.) max-ending_here = 0 ii.)temp = i + 1 c.)if (max_so_far < max_ending_here) i.) max_so_far = max_ending_here ii.)last = i; iii.)first = temp; 2.) Array B[m] where m = (last-first)+ 3.)-------------------------------For i from 0 to m- 1 O(m) B[i] = A[first + i]; Time Complexity: O(n+m) since we go through the entire array
8.. Given an array A of numbers, for every index i, find the nearest index j such that A[j] > A[i]. If none exist, report −1. Output these indices sorted by the corresponding i.:
- Given an array of integers, move all the zeroes to the right end. The order of the others doesn't matter. Use O(1) extra storage.: Array A[n] with size n 1.) Initialize Count to 0 2.) For i from 0 to n - 1 a.) if (A[i] != 0) i.) arr[count++] = arr[i]; 3.) while (count < n) a.)arr[count++] = 0;
Time Complexity: O(n)
- Given an array of integers, reorder so that all the negative integers appear first, then the zeroes, and finally the positive integers. If two integers have the same sign, their order should not be changed. Use O(1) extra storage.: Array A[n] with size n, 1.) For i from 0 to n- 1 a.)
- You have a stream of numbers. Implement an algorithm to return the median of the numbers seen so far.: Method 1: Insertion Sort If we can sort the data as it appears, we can easily locate median element. Insertion Sort is one such online algorithm that sorts the data appeared so far. At any instance of sorting, say after sorting i-th element, the first i elements of array are sorted. The insertion sort doesn't depend on future data to sort data input till that point. In other words, insertion sort considers data sorted so far while inserting next element. This is the key part of insertion sort that makes it an online algorithm.
- A majority element in an array is an element that appears more than n/2 times (where n is the size of the array). Give an algorithm to find a majority element. More generally, give an algorithm to find all elements that appear more than n/3 times. Use O(1) extra storage.: METHOD 1 (Basic)The basic solution is to have two loops and keep track of maximum count for all ditterent elements. If maximum count becomes greater than n/ then break the loops and return the element having maximum count. If maximum count doesn't become more than n/2 then majority element doesn't exist.
- Given an array of integers containing all the elements from 1, 2,... , n except one of them. Find which one. Try doing it using O(1) memory. What if two elements were missing?: Method 2 - O(n) time complexity and O(1) Extra Space The idea is based on this popular solution for finding one missing numbers. We extend the solution so that two missing elements are printed. One of the numbers will be less than or equal to avg while the other one will be strictly greater then avg. Two numbers can never be equal since all the given numbers are distinct.
// We reach here when x > y and z < y, i.e., z is smallest else k++; } }
- Consider two sorted arrays that are identical, except one array has an extra element. Find that element and its index: int findExtra(int arr1[], int arr2[], int n) { for (int i = 0; i < n; i+ +) if (arr1[i] != arr2[i]) return i; return n; }
- Given a sorted array, find the closest element (in terms of absolute differ-ence) to a given number.: // Returns element closest to target in arr[] int findClosest(int arr[], int n, int target) { // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2;
if (arr[mid] == target) return arr[mid]; /* If target is less than array element, then search in left / if (target < arr[mid]) { // If target is greater than previous // to mid, return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); / Repeat for left half */ j = mid; } // If target is greater than mid else { if (mid < n - 1 && target < arr[mid
- 1]) return getClosest(arr[mid], arr[mid + 1], target); // update i i = mid + 1; } } // Only single element left after search return arr[mid]; }
- Given an array, a local maximum is an element A[i] such that is greater than or equal to the neighboring elements in the array. (There can be two neighboring elements, or just one if i = 0 or i is the last index.) Find a local maximum.: A simple solution is to do a linear scan of array and as soon as we find a local maxima, we return it. The worst case time
10 / 12 temp; // Get to the next node in the list head = nex; } return false; }
- Going beyond the problem above, find the first node on the loop. (The first node means that first node on the loop that is encountered, if you traversed from the head.) Use O(1) extra memory.: Node* detectLoop(Node* head) { // Create a temporary node Node* temp = new Node; while (head != NULL) { // This condition is for the case // when there is no loop if (head->next == NULL) { return NULL; } // Check if next is already // pointing to temp if (head->next == temp) { break; } // Store the pointer to the next node // in order to get to it in the next step Node* nex = head->next; // Make next point to temp head->next = temp; // Get to the next node in the list
11 / 12 head = nex; } return head; }
- Consider the "stock market" problem. There is an input array A of prices, of (say) one unit of stock. You need to find out the maximum profit that can be made, assuming you buy (one unit of) stock on a day and sell it on a subsequent day.: int maxProfit(int price[], int start, int end) { // If the stocks can't be bought if (end <= start) return 0; // Initialise the profit int profit = 0; // The day at which the stock // must be bought for (int i = start; i < end; i++) { // The day at which the // stock must be sold for (int j = i + 1; j <= end; j++) { // If byuing the stock at ith day and // selling it at jth day is profitable if (price[j] > price[i]) { // Update the current profit int curr_profit = price[j] - price[i]
- maxProfit(price, start, i - 1)
- maxProfit(price, j + 1, end); // Update the maximum profit so far profit = max(profit, curr_profit); }