diff --git a/Exercise_1.java b/Exercise_1.java index c3ff1141..1277469d 100644 --- a/Exercise_1.java +++ b/Exercise_1.java @@ -1,8 +1,33 @@ -class BinarySearch { +// Time Complexity : O(log n), assuming input array is sorted +// Space Complexity : O(1), no additional space needed +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : no + +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 + { + int length = arr.length; + int result = -1; + if(length == 0) return result; + while(l <= r){ + // Find the mid of the sorted array + int mid = (l+r)/2; + + // return mid index if it equals the target value + if(arr[mid] == x){ + return mid; + } + + // search in the second of the array if target > mid value, else search in other half + if(x < arr[mid]){ + r = mid-1; + }else { + l = mid+1; + } + } + + return result; } // Driver method to test above @@ -11,7 +36,7 @@ public static void main(String args[]) BinarySearch ob = new BinarySearch(); int arr[] = { 2, 3, 4, 10, 40 }; int n = arr.length; - int x = 10; + int x = 10; int result = ob.binarySearch(arr, 0, n - 1, x); if (result == -1) System.out.println("Element not present"); diff --git a/Exercise_2.java b/Exercise_2.java index d0b5fa5f..ba710dba 100644 --- a/Exercise_2.java +++ b/Exercise_2.java @@ -1,27 +1,58 @@ -class QuickSort -{ - /* This function takes last element as pivot, - places the pivot element at its correct - position in sorted array, and places all - smaller (smaller than pivot) to left of - pivot and all greater elements to right - of pivot */ +// Time Complexity : Average case - O(n logn), Worst Case - O(n^2) - based on what we choose as pivot +// Space Complexity : In place swapping, 0(1) +// Did this code successfully run on Leetcode : +// Ran into time limit exceeded error +// Any problem you faced while coding this : No +class QuickSort +{ + /* A utility function to swap elements at i and j index */ void swap(int arr[],int i,int j){ - //Your code here + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; } - + + /* This function takes last element as pivot, + places the pivot element at its correct + position in sorted array, and places all + smaller (smaller than pivot) to left of + pivot and all greater elements to right + of pivot */ int partition(int arr[], int low, int high) - { - //Write code here for Partition and Swap + { + // select last element in the array for comparison + int lastIndex = high; + while (low < high) { + // find first larger value(than the last value) from left + while(low < high && arr[low] <= arr[lastIndex]){ + low++; + } + // find first smaller value(than the last value) from right + while(low < high && arr[high] >= arr[lastIndex]){ + high--; + } + if(low >= high) break; + // swap the larger and smaller value, so that all smaller values + // are on left and larger values are on right + swap(arr, low, high); + } + + return low; } /* The main function that implements QuickSort() arr[] --> Array to be sorted, low --> Starting index, - high --> Ending index */ + high --> Ending index + Find the pivot, swap the pivot value with last element, so that array is divided into 2 halves, + sort the left side of the pivot and the right side of the pivot*/ void sort(int arr[], int low, int high) - { - // Recursively sort elements before - // partition and after partition + { + if(low >= high) return; + + int pivotIndex = partition(arr, low, high); + swap(arr, pivotIndex, high); + sort(arr, low, pivotIndex-1); + sort(arr, pivotIndex+1, high); } /* A utility function to print array of size n */ @@ -36,8 +67,8 @@ static void printArray(int arr[]) // Driver program public static void main(String args[]) { - int arr[] = {10, 7, 8, 9, 1, 5}; - int n = arr.length; + int arr[] = {10, 7, 8, 9, 1, 5}; + int n = arr.length; QuickSort ob = new QuickSort(); ob.sort(arr, 0, n-1); diff --git a/Exercise_3.java b/Exercise_3.java index 1f9b752a..2c8c36e9 100644 --- a/Exercise_3.java +++ b/Exercise_3.java @@ -1,53 +1,77 @@ -class LinkedList -{ +// Time Complexity : O(N) - Need to go through all linked list nodes at least once +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No +class LinkedList +{ Node head; // head of linked list - + /* Linked list node */ - class Node - { - int data; - Node next; - Node(int d) - { - data = d; - next = null; - } - } - + class Node + { + int data; + Node next; + Node(int d) + { + data = d; + next = null; + } + } + /* Function to print middle of linked list */ //Complete this function - void printMiddle() - { - //Write your code here - //Implement using Fast and slow pointers - } - - public void push(int new_data) - { - Node new_node = new Node(new_data); - new_node.next = head; - head = new_node; - } + void printMiddle() + { + if (head == null) { + System.out.println("List is empty!!"); + return; + } + + if(head.next == null){ + System.out.println(head.data); + return; + } + + // Keep 2 points, slow moves one node at a time, fast moves 2 nodes at a time, + // By the time fast pointer reaches the end of the Linked list, slow pointer covers only half distance and + // reaches middle. + Node slow = head; + Node fast = slow.next.next; + while(fast != null){ + fast = fast.next; + if(fast == null) break; + fast = fast.next; + slow = slow.next; + } + System.out.println(slow.next.data); + } + + public void push(int new_data) + { + Node new_node = new Node(new_data); + new_node.next = head; + head = new_node; + } + + public void printList() + { + Node tnode = head; + while (tnode != null) + { + System.out.print(tnode.data+"->"); + tnode = tnode.next; + } + System.out.println("NULL"); + } - public void printList() - { - Node tnode = head; - while (tnode != null) - { - System.out.print(tnode.data+"->"); - tnode = tnode.next; - } - System.out.println("NULL"); - } - - public static void main(String [] args) - { - LinkedList llist = new LinkedList(); - for (int i=15; i>0; --i) - { - llist.push(i); - llist.printList(); - llist.printMiddle(); - } - } + public static void main(String [] args) + { + LinkedList llist = new LinkedList(); + for (int i=15; i>0; --i) + { + llist.push(i); + llist.printList(); + llist.printMiddle(); + } + } } \ No newline at end of file diff --git a/Exercise_4.java b/Exercise_4.java index 81afd3c2..278e22c7 100644 --- a/Exercise_4.java +++ b/Exercise_4.java @@ -1,19 +1,63 @@ -class MergeSort +// Time Complexity : Average case - O(n logn), +// Space Complexity : Additional array created in the recursive call which can have max "n" elements, O(n) +// Did this code successfully run on Leetcode : +// Yes +// Any problem you faced while coding this : No + +class MergeSort { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) - { - //Your code here + { int arrALen = m-l+1; + int arrBLen = r-m; + int[] arrA = new int[arrALen]; + int[] arrB = new int[arrBLen]; + + // copy the array into 2 sub arrays + int startIndex = l; + for(int i = 0; i < arrALen; i++){ + arrA[i] = arr[startIndex++]; + } + + startIndex = m+1; + for(int i = 0; i < arrBLen; i++){ + arrB[i] = arr[startIndex++]; + } + int i = 0, j = 0, index = l; + + // compare the sorted array and combine + while(i < arrALen && j < arrBLen){ + if(arrA[i] <= arrB[j]){ + arr[index++] = arrA[i++]; + }else{ + arr[index++] = arrB[j++]; + } + } + + while(i < arrALen){ + arr[index++] = arrA[i++]; + } + + while(j < arrBLen){ + arr[index++] = arrB[j++]; + } + } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { - //Write your code here - //Call mergeSort from here + if(l>=r) return; + int mid = (l+r)/2; + // Divide the array from the middle + sort(arr, l, mid); + sort(arr, mid+1, r); + + // merge the array comparing sub arrays + merge(arr, l, mid, r); } /* A utility function to print array of size n */ diff --git a/Exercise_5.java b/Exercise_5.java index 30e82675..1ce2f3c7 100644 --- a/Exercise_5.java +++ b/Exercise_5.java @@ -1,20 +1,65 @@ -class IterativeQuickSort { +// Time Complexity : Average case - O(n logn), Worst Case - O(n^2) - based on what we choose as pivot +// Space Complexity : In place swapping, 0(1) +// Did this code successfully run on Leetcode : +// Ran into time limit exceeded error +// Any problem you faced while coding this : No +import java.util.Stack; + +class IterativeQuickSort { void swap(int arr[], int i, int j) - { - //Try swapping without extra variable + { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; } /* This function is same in both iterative and recursive*/ - int partition(int arr[], int l, int h) - { - //Compare elements and swap. + int partition(int arr[], int low, int high) + { + int lastIndex = high; + while (low < high) { + while(low < high && arr[low] <= arr[lastIndex]){ + low++; + } + + while(low < high && arr[high] >= arr[lastIndex]){ + high--; + } + if(low >= high) break; + swap(arr, low, high); + } + + return low; } // Sorts arr[l..h] using iterative QuickSort void QuickSort(int arr[], int l, int h) - { - //Try using Stack Data Structure to remove recursion. + { + // maintain 2 separate stack to capture the current state, that is, lower and higher indices. + Stack lowerIndex = new Stack<>(); + Stack endIndex = new Stack<>(); + + lowerIndex.push(l); + endIndex.push(h); + + while(!lowerIndex.isEmpty()){ + int lower = lowerIndex.pop(); + int high = endIndex.pop(); + + int pivot = partition(arr, lower, high); + swap(arr, pivot, high); + + if(lower < pivot){ + lowerIndex.push(lower); + endIndex.push(pivot-1); + } + + if(pivot < high){ + lowerIndex.push(pivot+1); + endIndex.push(high); + } + } } // A utility function to print contents of arr @@ -28,9 +73,9 @@ void printArr(int arr[], int n) // Driver code to test above public static void main(String args[]) { - IterativeQuickSort ob = new IterativeQuickSort(); - int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; - ob.QuickSort(arr, 0, arr.length - 1); + IterativeQuickSort ob = new IterativeQuickSort(); + int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; + ob.QuickSort(arr, 0, arr.length - 1); ob.printArr(arr, arr.length); } } \ No newline at end of file