DAA Lab 4
DAA Lab 4
Problems
(1) WAP to sort an Array Where Each Element is at Most k Positions Away From Its
Correct Position(K=3)
Description:
We need to sort an array where each element is at most k positions away from its correct position. A min-
heap (priority queue) is an efficient way to achieve this, as it maintains the smallest element at the top and
helps in placing elements in sorted order efficiently..
Optimization:
- A more efficient method isn’t needed since O(n log k) is optimal for this problem.
- If k is small, we can use an adaptive Insertion Sort (O(nk)), but it's not efficient for larger k
Complexity Analysis Table:
Description:
To find the k-th smallest element in an unsorted array, we can use a min-heap (priority queue) for an
efficient approach. Another efficient method is the QuickSelect algorithm, which is an optimized version of
QuickSort for finding the k-th smallest element in O(n) average time.
Analysis:
We use a max-heap of size k to maintain the smallest k elements.
The top of the heap gives the k-th smallest element.
Time Complexity:
Building the heap: O(k)
Processing remaining elements: O((n-k) log k)
Total complexity: O(n log k)
Space Complexity:
The heap stores at most k elements: O(k)
Optimization:
(3)2 Sum
Description:
We need to check if there exists a pair of elements in an array whose sum equals the given target. A simple
approach is sorting the array and then using the two-pointer technique, which ensures an O(n log n) time
complexity (due to sorting).
Analysis:
- Sorting takes O(n log n)
- Two-pointer search runs in O(n)
- Total complexity: O(n log n) + O(n) ≈ O(n log n)
Optimization:
1. We could have used map to store elements and then check if totalSum – currElement =
targetElement exists in the map or not as it takes O(1) time but in worst case O(n) space complexity.
Complexity Analysis Table: