


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



For each of the following statements indicate whether the statement is true or false. Briefly explain/justify your answers. The justification is more important than the true/false answer.
In this problem we will design algorithms for solving a problem known as k-sum; we will focus on 3- sum and 4-sum. You are given an array of n integers A (positive and negative integers). In the 3-sum problem, the goal is to determine if there exists 3 integers in A such that x + y + z = 0. Similarly, in the 4-sum problem, the goal is to determine if there exists 4 integers in A such that w + x + y + z = 0. In the below questions, you are not allowed to sort the array A.
4sum(A) for i from 0 to n - 1 for j from 0 to n - 1 for k from 0 to n - 1 for p from 0 to n - 1 if A[i] + A[j] + A[k] + A[p] == 0 return true return false
4sum(A) for i from 0 to n - 1 for j from 0 to n - 1 insert-to-set(A[i] + A{j]) for i from 0 to n - 1 for j from 0 to n - 1 temp = A[i] + A[j] if is-in-set(-temp) return true return false
Everyone is familiar with the standard stack (last-in-first-out) and queue (first-in-first-out) data struc- tures. In this problem we will analyze a special type of queue which is implemented using two stacks A and B. In other words, assuming that a stack has three operations, push, pop, isempty, each with cost O(1), we implement the queue as follows:
enqueue(x): push x onto stack A dequeue(): if stack B is empty then pop the entire contents of stack A pushing each element in turn onto stack B. Now pop from stack B and return the result.
It is not hard to see that this implementation will result in the correct queue behavior. Show that a sequence of n operations (enqueue and dequeue) will take O(n) time in the worst case and not O(n^2 ).