practice-sheet5.pdf

Embed Size (px)

Citation preview

  • 8/11/2019 practice-sheet5.pdf

    1/1

    Data Structures and Algorithms : CS210A, ESO207A, ESO211

    Practice-sheet 5

    Date: 17 October, 2012.

    1. Given two binary search treesT1, T2 storingn1and n2elements, design an O(n1 + n2)

    time algorithm to merge the two trees T1 and T2.(Note that T1 and T2 lose theiridentities after merging).

    2. Recall the operation rank(x, T) defined for any element x and binary search tree T.This operation returns the number of elements in T less than x. We used additionalfield size at each node to design an O(log n) time algorithm for rank(x,T).

    (a) Write Pseudo-code forLeft-Rotate(v)which updates the size field as well suitably.

    (b) Suppose, instead of storing sizefield, you store rank of each node explicitly inthe tree. What will be the problem with this solution ?

    3. Write pseudo-code for Decrease-key operation on a Binary heap.

    4. Given k sorted lists L1,...,Lk storing n1,...nk elements respectively. Let n =

    iniDesign an O(n log k) time algorithm to merge them into a single sorted list.

    5. Given an array A storing n numbers. Design an O(n+ k log n) time algorithm tocompute k-smallest elements from A. You may modify the array A if you wish.

    6. You are given a sequencex0, . . . , xn1ofnnumbers. Design a suitable data structurewhich can perform each of the following operations in O(log n) time for any 0 i

    j < n.

    Report sum(i, j): Report the sum of all numbers {xi,...,xj}.

    Update(i, ): Add to the current value ofxi.

    7. You are given a sequenceS=b0, . . . , bn1ofn bits. Design a suitable data structurewhich can perform each of the following operations in O(log n) time for any 0 i < n.

    Report longest sequence: Report the length of the longest contiguous subsequenceof 1s in the sequence S.

    Flip bit(i): Flip bit bi.

    1 Slightly difficult problem

    1. You are given a height balanced treeT storingn elements. Design an algorithm whichtakes O(k+ log n) time to compute k predecessors of any given element xin tree T.

    2. You are given a binary heapHof sizen, a numberx, and a positive integer k . Designan O(k) time algorithm to determine ifx is smaller than kth smallest element in H.You may use O(k) extra space.

    Hint: If you are not able to solve this problem, most likely it is because you areinterpreting this problem in a wrong way.

    1