









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
CSE101 array/data structure questions and answers Graded A+
Typology: Exams
1 / 16
This page cannot be seen from the preview
Don't miss anything!










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[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]
B[index] = A[i][j] index++ 3.) Mergesort on B ----------O((kn)log(kn)) a.) return sorted array temp[kn] of size kn 4.) return temp Time Complexity: Steps 2.) and 2a.) are both O(kn) since we traverse through the whole 2D array. Step 3.) is O((kn)log(kn)) as discussed in class (Mergesort) Total Running Time = O((kn)log(kn) + kn) = O((kn)log(kn) You have an unsorted array of integers where every integer appears exactly twice, except one integer that appears once. Find it. - ✅✅A[n] of size n, boolean found 1.) For i from 0 to n- 1 -----------O(n) a.) For j from 0 to n- 1 ---------O(n) i.) if A[i] == A[j] ; break ii.)else; return A[i] Time Complexity: Steps 1.) and 1a.) are O(n) since the worse case is traversing the entire array. Total Running Time: O(n^2) Given an array, describe an algorithm to identify the contiguous subarray with the maximum sum. For example, if the input is [1, −3, 5, −2, 9, −8, −6, 4], the output
should be [5, −2, 9]. Get an 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
. 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
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 different elements. If maximum count becomes greater than n/2 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 can find the first missing number as sum of natural numbers from 1 to avg, i.e., avg*(avg+1)/2 minus the sum of array elements smaller than avg We can find the second missing number by subtracting first missing number to sum of missing numbers Given array of integers, determine if it contains a Pythagorean triple (integers a, b, c such that c 2 = a 2 + b 2 ). - ✅✅Method 1 (Naive)A simple solution is to run three loops, three loops pick three array elements and check if current three elements form a Pythagorean Triplet. The input is a sequence of ranges [x1, y1], [x2, y2],... (where each xi ≤ yi). Given two ranges that intersect, merge then into a single range by taking the union of ranges. Keep doing this until you finally get disjoint ranges. Design an algorithm that determines this output. - ✅✅
Given three arrays in non-decreasing order, find the elements that are common to all of them. Try O(1) extra storage. - ✅✅void findCommon(int ar1[], int ar2[], int ar3[], int n1, int n2, int n3) { // Initialize starting indexes for ar1[], ar2[] and ar3[] int i = 0, j = 0, k = 0; // Iterate through three arrays while all arrays have elements while (i < n1 && j < n2 && k < n3) { // If x = y and y = z, print any of them and move ahead // in all arrays if (ar1[i] == ar2[j] && ar2[j] == ar3[k]) { cout << ar1[i] << " "; i++; j++; k++; } // x < y else if (ar1[i] < ar2[j]) i++; // y < z else if (ar2[j] < ar3[k]) j++; // We reach here when x > y and z < y, i.e., z is smallest else k++; } }
/* 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 complexity of this method would be O(n)
. In a 2D array, a local maximum is defined as before, but the neighbors are both vertices and horizontal. So the neighbors of A[i][j] are A[i − 1][j], A[i + 1][j], A[i][j − 1], A[i][j + 1] (whenever they exist). Find a local maximum. - ✅✅Iterate through all the elements of Matrix and check if it is greater/equal to all its neighbors. If yes, return the element. Time Complexity: O(rows * columns)Auxiliary Space: O(1) You are given only the head pointer of a singly linked list. Determine if the linked list has a loop. (It is not difficult with O(n) storage, where n is the length of the list.) You cannot assume that the nodes store different values. The real challenge is to do this question with O(1) extra memory. - ✅✅bool 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 false; }
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 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]
Describe a stack based data structure that supports push, pop, and findmin in O(1) operations. - ✅✅