From 46ed21da2f8420118de6c670194d3ece5827d87e Mon Sep 17 00:00:00 2001 From: Premal Samale Date: Mon, 5 Jan 2026 20:42:35 +0530 Subject: [PATCH] Precourse2 completed --- Exercise_1.java | 24 +++++++++++++++++++- Exercise_2.java | 37 +++++++++++++++++++++++++++--- Exercise_3.java | 32 ++++++++++++++++++++++++++ Exercise_4.java | 50 ++++++++++++++++++++++++++++++++++++++++- Exercise_5.java | 60 ++++++++++++++++++++++++++++++++++++++++++++++++- 5 files changed, 197 insertions(+), 6 deletions(-) diff --git a/Exercise_1.java b/Exercise_1.java index c3ff1141..d69efcfd 100644 --- a/Exercise_1.java +++ b/Exercise_1.java @@ -1,8 +1,30 @@ +// Time Complexity : o(log n) +// Space Complexity :o(1) +// Did this code successfully run on Leetcode : N/A it is not a leetcode problem +// Any problem you faced while coding this :no + + +// Your code here along with comments explaining your approach +//1. consider left pointer at 0th index and right pointer at last index and middle of both. +//2. iterate until left and right not crossing +//3. check if target is matching with mid element, if yes return mid index. +//4. Else if target is greater than mid element then check the target on right side of of mid, else go towards left side. + class BinarySearch { // Returns index of x if it is present in arr[l.. r], else return -1 int binarySearch(int arr[], int l, int r, int x) { - //Write your code here + while(l<=r){ + int mid = l+(r-l)/2; + if(arr[mid]== x){ + return mid; + }else if(arr[mid] Array to be sorted, low --> Starting index, high --> Ending index */ void sort(int arr[], int low, int high) { - // Recursively sort elements before + // Recursively sort elements before // partition and after partition + if(low stack = new Stack(); + + //push initial bound to the stack + stack.push(l); + stack.push(h); + + //keep popping from stack while it is not empty + while(!stack.isEmpty()){ + h = stack.pop(); + l = stack.pop(); + if(l < h){ + int pivotIndex = partition(arr, l, h); + //If there are elements on left side of the pivot , push their indices to stack + if(pivotIndex-1>l){ + stack.push(l); + stack.push(pivotIndex-1); + } + if(pivotIndex + 1 < h){ + stack.push(pivotIndex+1); + stack.push(h); + } + } + } } // A utility function to print contents of arr