From 75602fb574e5a371a2ef61387281d8f9846e3dc7 Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Thu, 18 Apr 2024 09:08:22 +0530 Subject: [PATCH 01/17] Changing Structure --- .../array => 1 Arrays}/MaximumSubArray.java | 3 +- .../RemoveDuplicatesSortedArray.java | 6 +- .../SurfaceAreaOf3DShapes.java | 39 ++--- .../dsa/array => 1 Arrays}/TwoSum.java | 5 +- .../dsa/array => 1 Arrays}/ValidSudoku.java | 48 +++---- .../recursion => 10 Recursion}/Factorial.java | 8 +- .../recursion => 10 Recursion}/Fibonacci.java | 11 +- .../InorderTraversalIterative.java | 3 +- .../InorderTraversalRecursive.java | 7 +- .../PostorderTraversalIterative.java | 3 +- .../PostorderTraversalRecursive.java | 6 +- .../PreorderTraversalIterative.java | 3 +- .../PreorderTraversalRecursive.java | 8 +- .../model/TreeNode.java | 13 +- .../stack => 12 Stack}/ValidParenthesis.java | 3 +- .../dsa/queue => 13 Queue}/RecentCounter.java | 14 +- .../IntersectionOfTwoArrays.java | 3 +- .../IntersectionOfTwoArrays2.java | 3 +- .../MiniMahjongWinningHand.java | 64 +++++---- .../TwoSum.java | 5 +- .../SearchInBST.java | 21 +-- .../graph => 16 Graph}/FindTheTownJudge.java | 7 +- .../InvertBinaryTree.java | 12 +- .../dsa/dfs => 17 DFS and BFS}/PathSum.java | 13 +- 17 DFS and BFS/Solitaire.java | 136 ++++++++++++++++++ .../BestTimeToBuyAndSellStock.java | 3 +- .../MiniMahjongWinningHand2.java | 132 +++++++++-------- .../GenerateParentheses.java | 21 +-- 19 Backtracking/NQueen.java | 103 +++++++++++++ .../Subsets.java | 9 +- 2 Time Complexity/ArrayCopy.java | 15 ++ .../ArraySum.java | 7 +- .../complexity => 2 Time Complexity}/Sum.java | 3 +- .../heap => 20 Heap}/KthLargestElement.java | 11 +- .../ClimbingStairs.java | 9 +- .../RodCutting.java | 16 +-- .../Subsets.java | 8 +- .../ContainsDuplicate2.java | 6 +- ...87 First Unique Character in a String.java | 22 +++ 3 Strings/GenerateParentheses.java | 67 +++++++++ .../LongestCommonPrefix.java | 7 +- .../strings => 3 Strings}/ReverseString.java | 3 +- .../ValidPalindrome.java | 12 +- .../dsa/math => 4 Math}/AddStrings.java | 12 +- .../ConvertNumberToHexadecimal.java | 13 +- .../dsa/math => 4 Math}/CountPrimes.java | 9 +- .../ExcelSheetColumnNumber.java | 10 +- .../dsa/math => 4 Math}/PalindromeNumber.java | 6 +- .../dsa/math => 4 Math}/PlusOne.java | 8 +- .../dsa/math => 4 Math}/RomanToInteger.java | 22 ++- .../dsa/math => 4 Math}/RotateArray.java | 15 +- .../algos/BubbleSort.java | 9 +- .../algos/InsertionSort.java | 7 +- .../algos/MergeSort.java | 7 +- .../algos/QuickSort.java | 9 +- .../algos/SelectionSort.java | 5 +- .../algos/SortingAlgo.java | 1 - .../problems/CountElements.java | 9 +- .../problems/KthLargestElement.java | 15 +- .../problems/MergeSortedArray.java | 12 +- .../problems/SquaresOfSortedArray.java | 3 +- .../problems/ThreeSum.java | 5 +- .../algos/BinarySearch.java | 3 +- .../problems/ArrangingCoins.java | 13 +- .../problems/FirstBadVersion.java | 13 +- .../problems/GuessNumberHigherOrLower.java | 24 ++-- .../problems/SearchIn2DMatrix.java | 15 +- .../problems/SearchInRotatedSortedArray.java | 17 +-- .../problems/SearchInsertPosition.java | 3 +- .../problems/SingleElementInASortedArray.java | 19 +-- .../problems/SquareRoot.java | 5 +- .../ConvertNumberToHexadecimal.java | 16 +-- .../FindTheDifference.java | 9 +- .../MissingNumber.java | 9 +- .../SingleNumber.java | 3 +- .../MergeTwoSortedList.java | 6 +- .../PalindromeLinkedList.java | 13 +- .../PascalTriangle.java | 3 +- .../ContainerWithMostWater.java | 11 +- .../MoveZeros.java | 7 +- .../RemoveElement.java | 3 +- .../dsa/ListNode.java => ListNode.java | 8 +- src/in/knowledgegate/dsa/Main.java | 7 - .../dsa/backtracking/NQueen.java | 24 ++-- .../dsa/complexity/ArrayCopy.java | 8 +- src/in/knowledgegate/dsa/dfs/Solitaire.java | 136 ------------------ ...87 First Unique Character in a String.java | 23 +++ .../dsa/strings/GenerateParentheses.java | 15 +- 88 files changed, 810 insertions(+), 678 deletions(-) rename {src/in/knowledgegate/dsa/array => 1 Arrays}/MaximumSubArray.java (92%) rename {src/in/knowledgegate/dsa/array => 1 Arrays}/RemoveDuplicatesSortedArray.java (93%) rename {src/in/knowledgegate/dsa/array => 1 Arrays}/SurfaceAreaOf3DShapes.java (65%) rename {src/in/knowledgegate/dsa/array => 1 Arrays}/TwoSum.java (90%) rename {src/in/knowledgegate/dsa/array => 1 Arrays}/ValidSudoku.java (60%) rename {src/in/knowledgegate/dsa/recursion => 10 Recursion}/Factorial.java (57%) rename {src/in/knowledgegate/dsa/recursion => 10 Recursion}/Fibonacci.java (84%) rename {src/in/knowledgegate/dsa/binarytree => 11 Tree and Binary Tree}/InorderTraversalIterative.java (88%) rename {src/in/knowledgegate/dsa/binarytree => 11 Tree and Binary Tree}/InorderTraversalRecursive.java (82%) rename {src/in/knowledgegate/dsa/binarytree => 11 Tree and Binary Tree}/PostorderTraversalIterative.java (90%) rename {src/in/knowledgegate/dsa/binarytree => 11 Tree and Binary Tree}/PostorderTraversalRecursive.java (82%) rename {src/in/knowledgegate/dsa/binarytree => 11 Tree and Binary Tree}/PreorderTraversalIterative.java (89%) rename {src/in/knowledgegate/dsa/binarytree => 11 Tree and Binary Tree}/PreorderTraversalRecursive.java (75%) rename {src/in/knowledgegate/dsa/binarytree => 11 Tree and Binary Tree}/model/TreeNode.java (60%) rename {src/in/knowledgegate/dsa/stack => 12 Stack}/ValidParenthesis.java (95%) rename {src/in/knowledgegate/dsa/queue => 13 Queue}/RecentCounter.java (76%) rename {src/in/knowledgegate/dsa/hashingAndMaps => 14 Hashing and Maps}/IntersectionOfTwoArrays.java (91%) rename {src/in/knowledgegate/dsa/hashingAndMaps => 14 Hashing and Maps}/IntersectionOfTwoArrays2.java (93%) rename {src/in/knowledgegate/dsa/hashingAndMaps => 14 Hashing and Maps}/MiniMahjongWinningHand.java (65%) rename {src/in/knowledgegate/dsa/hashingAndMaps => 14 Hashing and Maps}/TwoSum.java (91%) rename {src/in/knowledgegate/dsa/binarysearchtree => 15 Binary Search Tree}/SearchInBST.java (76%) rename {src/in/knowledgegate/dsa/graph => 16 Graph}/FindTheTownJudge.java (90%) rename {src/in/knowledgegate/dsa/bfs => 17 DFS and BFS}/InvertBinaryTree.java (76%) rename {src/in/knowledgegate/dsa/dfs => 17 DFS and BFS}/PathSum.java (87%) create mode 100644 17 DFS and BFS/Solitaire.java rename {src/in/knowledgegate/dsa/greedy => 18 Greedy}/BestTimeToBuyAndSellStock.java (94%) rename {src/in/knowledgegate/dsa/greedy => 18 Greedy}/MiniMahjongWinningHand2.java (52%) rename {src/in/knowledgegate/dsa/backtracking => 19 Backtracking}/GenerateParentheses.java (75%) create mode 100644 19 Backtracking/NQueen.java rename {src/in/knowledgegate/dsa/backtracking => 19 Backtracking}/Subsets.java (89%) create mode 100644 2 Time Complexity/ArrayCopy.java rename {src/in/knowledgegate/dsa/complexity => 2 Time Complexity}/ArraySum.java (55%) rename {src/in/knowledgegate/dsa/complexity => 2 Time Complexity}/Sum.java (78%) rename {src/in/knowledgegate/dsa/heap => 20 Heap}/KthLargestElement.java (76%) rename {src/in/knowledgegate/dsa/dynamicprogramming => 21 Dynamic Programming}/ClimbingStairs.java (86%) rename {src/in/knowledgegate/dsa/dynamicprogramming => 21 Dynamic Programming}/RodCutting.java (81%) rename {src/in/knowledgegate/dsa/dynamicprogramming => 21 Dynamic Programming}/Subsets.java (85%) rename {src/in/knowledgegate/dsa/slidingwindow => 22 Sliding Window}/ContainsDuplicate2.java (86%) create mode 100644 3 Strings/387 First Unique Character in a String.java create mode 100644 3 Strings/GenerateParentheses.java rename {src/in/knowledgegate/dsa/strings => 3 Strings}/LongestCommonPrefix.java (85%) rename {src/in/knowledgegate/dsa/strings => 3 Strings}/ReverseString.java (90%) rename {src/in/knowledgegate/dsa/strings => 3 Strings}/ValidPalindrome.java (87%) rename {src/in/knowledgegate/dsa/math => 4 Math}/AddStrings.java (83%) rename {src/in/knowledgegate/dsa/math => 4 Math}/ConvertNumberToHexadecimal.java (72%) rename {src/in/knowledgegate/dsa/math => 4 Math}/CountPrimes.java (80%) rename {src/in/knowledgegate/dsa/math => 4 Math}/ExcelSheetColumnNumber.java (78%) rename {src/in/knowledgegate/dsa/math => 4 Math}/PalindromeNumber.java (90%) rename {src/in/knowledgegate/dsa/math => 4 Math}/PlusOne.java (91%) rename {src/in/knowledgegate/dsa/math => 4 Math}/RomanToInteger.java (90%) rename {src/in/knowledgegate/dsa/math => 4 Math}/RotateArray.java (88%) rename {src/in/knowledgegate/dsa/sorting => 5 Sorting}/algos/BubbleSort.java (76%) rename {src/in/knowledgegate/dsa/sorting => 5 Sorting}/algos/InsertionSort.java (64%) rename {src/in/knowledgegate/dsa/sorting => 5 Sorting}/algos/MergeSort.java (88%) rename {src/in/knowledgegate/dsa/sorting => 5 Sorting}/algos/QuickSort.java (83%) rename {src/in/knowledgegate/dsa/sorting => 5 Sorting}/algos/SelectionSort.java (84%) rename {src/in/knowledgegate/dsa/sorting => 5 Sorting}/algos/SortingAlgo.java (57%) rename {src/in/knowledgegate/dsa/sorting => 5 Sorting}/problems/CountElements.java (90%) rename {src/in/knowledgegate/dsa/sorting => 5 Sorting}/problems/KthLargestElement.java (77%) rename {src/in/knowledgegate/dsa/sorting => 5 Sorting}/problems/MergeSortedArray.java (88%) rename {src/in/knowledgegate/dsa/sorting => 5 Sorting}/problems/SquaresOfSortedArray.java (92%) rename {src/in/knowledgegate/dsa/sorting => 5 Sorting}/problems/ThreeSum.java (91%) rename {src/in/knowledgegate/dsa/binarysearch => 6 Binary Search}/algos/BinarySearch.java (86%) rename {src/in/knowledgegate/dsa/binarysearch => 6 Binary Search}/problems/ArrangingCoins.java (78%) rename {src/in/knowledgegate/dsa/binarysearch => 6 Binary Search}/problems/FirstBadVersion.java (83%) rename {src/in/knowledgegate/dsa/binarysearch => 6 Binary Search}/problems/GuessNumberHigherOrLower.java (77%) rename {src/in/knowledgegate/dsa/binarysearch => 6 Binary Search}/problems/SearchIn2DMatrix.java (78%) rename {src/in/knowledgegate/dsa/binarysearch => 6 Binary Search}/problems/SearchInRotatedSortedArray.java (81%) rename {src/in/knowledgegate/dsa/binarysearch => 6 Binary Search}/problems/SearchInsertPosition.java (92%) rename {src/in/knowledgegate/dsa/binarysearch => 6 Binary Search}/problems/SingleElementInASortedArray.java (66%) rename {src/in/knowledgegate/dsa/binarysearch => 6 Binary Search}/problems/SquareRoot.java (88%) rename {src/in/knowledgegate/dsa/bitmanipulation => 7 Bit Manipulation}/ConvertNumberToHexadecimal.java (70%) rename {src/in/knowledgegate/dsa/bitmanipulation => 7 Bit Manipulation}/FindTheDifference.java (85%) rename {src/in/knowledgegate/dsa/bitmanipulation => 7 Bit Manipulation}/MissingNumber.java (88%) rename {src/in/knowledgegate/dsa/bitmanipulation => 7 Bit Manipulation}/SingleNumber.java (90%) rename {src/in/knowledgegate/dsa/linkedlist => 8 Linked List}/MergeTwoSortedList.java (90%) rename {src/in/knowledgegate/dsa/linkedlist => 8 Linked List}/PalindromeLinkedList.java (81%) rename {src/in/knowledgegate/dsa/linkedlist => 8 Linked List}/PascalTriangle.java (93%) rename {src/in/knowledgegate/dsa/twopointer => 9 Two Pointers}/ContainerWithMostWater.java (82%) rename {src/in/knowledgegate/dsa/twopointer => 9 Two Pointers}/MoveZeros.java (84%) rename {src/in/knowledgegate/dsa/twopointer => 9 Two Pointers}/RemoveElement.java (93%) rename src/in/knowledgegate/dsa/ListNode.java => ListNode.java (71%) delete mode 100644 src/in/knowledgegate/dsa/Main.java delete mode 100644 src/in/knowledgegate/dsa/dfs/Solitaire.java create mode 100644 src/in/knowledgegate/dsa/strings/387 First Unique Character in a String.java diff --git a/src/in/knowledgegate/dsa/array/MaximumSubArray.java b/1 Arrays/MaximumSubArray.java similarity index 92% rename from src/in/knowledgegate/dsa/array/MaximumSubArray.java rename to 1 Arrays/MaximumSubArray.java index 3a9e195..6211ac9 100644 --- a/src/in/knowledgegate/dsa/array/MaximumSubArray.java +++ b/1 Arrays/MaximumSubArray.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.array; /** * Given an integer array nums, find the contiguous subarray (containing at @@ -15,7 +14,7 @@ *

* Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 */ -public class MaximumSubArray { +class MaximumSubArray { public int maxSubArray(int[] nums) { int maxEndingHere = nums[0], maxSoFar = nums[0]; for (int i = 1; i < nums.length; i++) { diff --git a/src/in/knowledgegate/dsa/array/RemoveDuplicatesSortedArray.java b/1 Arrays/RemoveDuplicatesSortedArray.java similarity index 93% rename from src/in/knowledgegate/dsa/array/RemoveDuplicatesSortedArray.java rename to 1 Arrays/RemoveDuplicatesSortedArray.java index 391b501..2277f1b 100644 --- a/src/in/knowledgegate/dsa/array/RemoveDuplicatesSortedArray.java +++ b/1 Arrays/RemoveDuplicatesSortedArray.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.array; /** * Given an integer array nums sorted in non-decreasing order, remove the @@ -29,9 +28,10 @@ * Constraints: 1 <= nums.length <= 3 * 104 -100 <= nums[i] <= 100 nums is * sorted in non-decreasing order. */ -public class RemoveDuplicatesSortedArray { +class RemoveDuplicatesSortedArray { public int removeDuplicates(int[] nums) { - if (nums.length == 0) return 0; + if (nums.length == 0) + return 0; int prev = 0; for (int i = 1; i < nums.length; i++) { diff --git a/src/in/knowledgegate/dsa/array/SurfaceAreaOf3DShapes.java b/1 Arrays/SurfaceAreaOf3DShapes.java similarity index 65% rename from src/in/knowledgegate/dsa/array/SurfaceAreaOf3DShapes.java rename to 1 Arrays/SurfaceAreaOf3DShapes.java index b49d58a..04f6385 100644 --- a/src/in/knowledgegate/dsa/array/SurfaceAreaOf3DShapes.java +++ b/1 Arrays/SurfaceAreaOf3DShapes.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.array; /** * You are given an n x n grid where you have @@ -18,13 +17,13 @@ * * Example 1: * Input: grid = [[1,2], - * [3,4]] + * [3,4]] * Output: 34 = 4 + 7 + 10 + 13 = 34 * * Example 2: * Input: grid = [[1,1,1], - * [1,0,1], - * [1,1,1]] + * [1,0,1], + * [1,1,1]] * Output: 32 * * Example 3: @@ -36,34 +35,33 @@ * 1 <= n <= 50 * 0 <= grid[i][j] <= 50 */ -public class SurfaceAreaOf3DShapes { +class SurfaceAreaOf3DShapes { public static void main(String[] args) { - SurfaceAreaOf3DShapes shapes = - new SurfaceAreaOf3DShapes(); - int[][] grid = new int[][]{{1,2},{3,4}}; + SurfaceAreaOf3DShapes shapes = new SurfaceAreaOf3DShapes(); + int[][] grid = new int[][] { { 1, 2 }, { 3, 4 } }; System.out.println("Area is:" + shapes.surfaceArea(grid)); } public int surfaceArea(int[][] grid) { int total = 0; int size = grid.length; - for (int i = 0 ; i< size; i++) { + for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { - if (grid[i][j] == 0) continue; - int areaGained = - 4 * grid[i][j] + 2; + if (grid[i][j] == 0) + continue; + int areaGained = 4 * grid[i][j] + 2; int areaLost = 0; if (i - 1 >= 0) { - areaLost += Math.min(grid[i][j], grid[i-1][j]); + areaLost += Math.min(grid[i][j], grid[i - 1][j]); } if (i + 1 < size) { - areaLost += Math.min(grid[i][j], grid[i+1][j]); + areaLost += Math.min(grid[i][j], grid[i + 1][j]); } if (j - 1 >= 0) { - areaLost += Math.min(grid[i][j], grid[i][j-1]); + areaLost += Math.min(grid[i][j], grid[i][j - 1]); } if (j + 1 < size) { - areaLost += Math.min(grid[i][j], grid[i][j+1]); + areaLost += Math.min(grid[i][j], grid[i][j + 1]); } total += areaGained - areaLost; } @@ -72,12 +70,3 @@ public int surfaceArea(int[][] grid) { return total; } } - - - - - - - - - diff --git a/src/in/knowledgegate/dsa/array/TwoSum.java b/1 Arrays/TwoSum.java similarity index 90% rename from src/in/knowledgegate/dsa/array/TwoSum.java rename to 1 Arrays/TwoSum.java index 0a63e23..75d98ea 100644 --- a/src/in/knowledgegate/dsa/array/TwoSum.java +++ b/1 Arrays/TwoSum.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.array; /** * Given an array of integers nums and an integer @@ -23,12 +22,12 @@ * nums[i] <= 109 -109 <= target <= 109 Only one * valid answer exists. */ -public class TwoSum { +class TwoSum { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { - return new int[] {i , j}; + return new int[] { i, j }; } } } diff --git a/src/in/knowledgegate/dsa/array/ValidSudoku.java b/1 Arrays/ValidSudoku.java similarity index 60% rename from src/in/knowledgegate/dsa/array/ValidSudoku.java rename to 1 Arrays/ValidSudoku.java index 9846228..bcb316b 100644 --- a/src/in/knowledgegate/dsa/array/ValidSudoku.java +++ b/1 Arrays/ValidSudoku.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.array; import java.util.HashSet; import java.util.Set; @@ -23,15 +22,15 @@ * * Example 1: * Input: board = - * { {'5','3','.','.','7','.','.','.','.'} - * , {'6','.','.','1','9','5','.','.','.'} - * , {'.','9','8','.','.','.','.','6','.'} - * , {'8','.','.','.','6','.','.','.','3'} - * , {'4','.','.','8','.','3','.','.','1'} - * , {'7','.','.','.','2','.','.','.','6'} - * , {'.','6','.','.','.','.','2','8','.'} - * , {'.','.','.','4','1','9','.','.','5'} - * , {'.','.','.','.','8','.','.','7','9'}} + * { {'5','3','.','.','7','.','.','.','.'} + * , {'6','.','.','1','9','5','.','.','.'} + * , {'.','9','8','.','.','.','.','6','.'} + * , {'8','.','.','.','6','.','.','.','3'} + * , {'4','.','.','8','.','3','.','.','1'} + * , {'7','.','.','.','2','.','.','.','6'} + * , {'.','6','.','.','.','.','2','8','.'} + * , {'.','.','.','4','1','9','.','.','5'} + * , {'.','.','.','.','8','.','.','7','9'}} * Output: true * * Example 2: @@ -58,19 +57,14 @@ * board[i].length == 9 * board[i][j] is a digit 1-9 or '.'. */ -public class ValidSudoku { +class ValidSudoku { public static void main(String[] args) { ValidSudoku checker = new ValidSudoku(); - char[][] puzzle = new char[][] - {{'5','3','.','.','7','.','.','.','.'} - ,{'6','.','.','1','9','5','.','.','.'} - ,{'.','9','8','.','.','.','.','6','.'} - ,{'8','.','.','.','6','.','.','.','3'} - ,{'4','.','.','8','.','3','.','.','1'} - ,{'7','.','.','.','2','.','.','.', '6'} - ,{'.','6','.','.','.','.','2','8','.'} - ,{'.','.','.','4','1','9','.','.','5'} - ,{'.','.','.','.','8','.','.', '7','9'}}; + char[][] puzzle = new char[][] { { '5', '3', '.', '.', '7', '.', '.', '.', '.' }, + { '6', '.', '.', '1', '9', '5', '.', '.', '.' }, { '.', '9', '8', '.', '.', '.', '.', '6', '.' }, + { '8', '.', '.', '.', '6', '.', '.', '.', '3' }, { '4', '.', '.', '8', '.', '3', '.', '.', '1' }, + { '7', '.', '.', '.', '2', '.', '.', '.', '6' }, { '.', '6', '.', '.', '.', '.', '2', '8', '.' }, + { '.', '.', '.', '4', '1', '9', '.', '.', '5' }, { '.', '.', '.', '.', '8', '.', '.', '7', '9' } }; System.out.println("IsValid:" + checker.isValidSudoku(puzzle)); } @@ -79,10 +73,11 @@ public boolean isValidSudoku(char[][] board) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { char c = board[i][j]; - if (c == '.') continue; - if (!visited.add(c +"row" + i) || - !visited.add(c + "col" + j) || - !visited.add(c + "box" + i/3 + "-" + j/3)) { + if (c == '.') + continue; + if (!visited.add(c + "row" + i) || + !visited.add(c + "col" + j) || + !visited.add(c + "box" + i / 3 + "-" + j / 3)) { return false; } } @@ -90,6 +85,3 @@ public boolean isValidSudoku(char[][] board) { return true; } } - - - diff --git a/src/in/knowledgegate/dsa/recursion/Factorial.java b/10 Recursion/Factorial.java similarity index 57% rename from src/in/knowledgegate/dsa/recursion/Factorial.java rename to 10 Recursion/Factorial.java index 86b3265..1ced49e 100644 --- a/src/in/knowledgegate/dsa/recursion/Factorial.java +++ b/10 Recursion/Factorial.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.recursion; /** * Factorial @@ -9,9 +8,10 @@ * F(3) = 6 = 3 * 2 * F(n) = n * F(n-1), n >= 1 */ -public class Factorial { +class Factorial { public int fact(int n) { - if (n == 0 || n == 1) return 1; - return n * fact(n-1); + if (n == 0 || n == 1) + return 1; + return n * fact(n - 1); } } diff --git a/src/in/knowledgegate/dsa/recursion/Fibonacci.java b/10 Recursion/Fibonacci.java similarity index 84% rename from src/in/knowledgegate/dsa/recursion/Fibonacci.java rename to 10 Recursion/Fibonacci.java index 2c66979..7bf1b80 100644 --- a/src/in/knowledgegate/dsa/recursion/Fibonacci.java +++ b/10 Recursion/Fibonacci.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.recursion; /** * The Fibonacci numbers, commonly denoted F(n) @@ -30,15 +29,17 @@ * Constraints: * 0 <= n <= 30 */ -public class Fibonacci { +class Fibonacci { public int fibRecursive(int n) { - if (n == 0 || n == 1) return n; + if (n == 0 || n == 1) + return n; return fibRecursive(n - 1) + - fibIterative( n - 2); + fibIterative(n - 2); } public int fibIterative(int n) { - if (n == 0 || n == 1) return n; + if (n == 0 || n == 1) + return n; int first = 0, second = 1; for (int i = 1; i < n; i++) { int next = first + second; diff --git a/src/in/knowledgegate/dsa/binarytree/InorderTraversalIterative.java b/11 Tree and Binary Tree/InorderTraversalIterative.java similarity index 88% rename from src/in/knowledgegate/dsa/binarytree/InorderTraversalIterative.java rename to 11 Tree and Binary Tree/InorderTraversalIterative.java index c39fec2..c192afd 100644 --- a/src/in/knowledgegate/dsa/binarytree/InorderTraversalIterative.java +++ b/11 Tree and Binary Tree/InorderTraversalIterative.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarytree; import in.knowledgegate.dsa.binarytree.model.TreeNode; @@ -10,7 +9,7 @@ * Write Inorder traversal of a binary tree using * iterative approach */ -public class InorderTraversalIterative { +class InorderTraversalIterative { public List inorderTraversal(TreeNode root) { Stack stack = new Stack<>(); List result = new ArrayList<>(); diff --git a/src/in/knowledgegate/dsa/binarytree/InorderTraversalRecursive.java b/11 Tree and Binary Tree/InorderTraversalRecursive.java similarity index 82% rename from src/in/knowledgegate/dsa/binarytree/InorderTraversalRecursive.java rename to 11 Tree and Binary Tree/InorderTraversalRecursive.java index f8e8681..46a7c11 100644 --- a/src/in/knowledgegate/dsa/binarytree/InorderTraversalRecursive.java +++ b/11 Tree and Binary Tree/InorderTraversalRecursive.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarytree; import in.knowledgegate.dsa.binarytree.model.TreeNode; @@ -9,15 +8,17 @@ * Write Inorder traversal of a binary tree using * recursive approach */ -public class InorderTraversalRecursive { +class InorderTraversalRecursive { public List inorderTraversal(TreeNode root) { List result = new ArrayList<>(); inorderTraversal(root, result); return result; } + private void inorderTraversal(TreeNode root, List result) { - if (root == null) return; + if (root == null) + return; inorderTraversal(root.left, result); result.add(root.val); inorderTraversal(root.right, result); diff --git a/src/in/knowledgegate/dsa/binarytree/PostorderTraversalIterative.java b/11 Tree and Binary Tree/PostorderTraversalIterative.java similarity index 90% rename from src/in/knowledgegate/dsa/binarytree/PostorderTraversalIterative.java rename to 11 Tree and Binary Tree/PostorderTraversalIterative.java index 879211f..09197ee 100644 --- a/src/in/knowledgegate/dsa/binarytree/PostorderTraversalIterative.java +++ b/11 Tree and Binary Tree/PostorderTraversalIterative.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarytree; import in.knowledgegate.dsa.binarytree.model.TreeNode; @@ -10,7 +9,7 @@ * Write Postorder traversal of a binary tree * using iterative approach */ -public class PostorderTraversalIterative { +class PostorderTraversalIterative { public List iterativePostorder(TreeNode root) { List result = new ArrayList<>(); if (root == null) { diff --git a/src/in/knowledgegate/dsa/binarytree/PostorderTraversalRecursive.java b/11 Tree and Binary Tree/PostorderTraversalRecursive.java similarity index 82% rename from src/in/knowledgegate/dsa/binarytree/PostorderTraversalRecursive.java rename to 11 Tree and Binary Tree/PostorderTraversalRecursive.java index 10a1fee..b23ba85 100644 --- a/src/in/knowledgegate/dsa/binarytree/PostorderTraversalRecursive.java +++ b/11 Tree and Binary Tree/PostorderTraversalRecursive.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarytree; import in.knowledgegate.dsa.binarytree.model.TreeNode; @@ -9,7 +8,7 @@ * Write Postorder traversal of a binary tree * using recursive approach */ -public class PostorderTraversalRecursive { +class PostorderTraversalRecursive { public List postorderTraversal(TreeNode root) { List list = new ArrayList<>(); postorderTraversal(root, list); @@ -18,7 +17,8 @@ public List postorderTraversal(TreeNode root) { private void postorderTraversal(TreeNode root, List result) { - if (root == null) return; + if (root == null) + return; postorderTraversal(root.left, result); postorderTraversal(root.right, result); result.add(root.val); diff --git a/src/in/knowledgegate/dsa/binarytree/PreorderTraversalIterative.java b/11 Tree and Binary Tree/PreorderTraversalIterative.java similarity index 89% rename from src/in/knowledgegate/dsa/binarytree/PreorderTraversalIterative.java rename to 11 Tree and Binary Tree/PreorderTraversalIterative.java index f006515..28b00b2 100644 --- a/src/in/knowledgegate/dsa/binarytree/PreorderTraversalIterative.java +++ b/11 Tree and Binary Tree/PreorderTraversalIterative.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarytree; import in.knowledgegate.dsa.binarytree.model.TreeNode; @@ -10,7 +9,7 @@ * Write Preorder traversal of a binary tree using * iterative approach */ -public class PreorderTraversalIterative { +class PreorderTraversalIterative { public List iterativePreorder(TreeNode root) { List result = new ArrayList<>(); if (root == null) { diff --git a/src/in/knowledgegate/dsa/binarytree/PreorderTraversalRecursive.java b/11 Tree and Binary Tree/PreorderTraversalRecursive.java similarity index 75% rename from src/in/knowledgegate/dsa/binarytree/PreorderTraversalRecursive.java rename to 11 Tree and Binary Tree/PreorderTraversalRecursive.java index 2c0a0db..2bfc788 100644 --- a/src/in/knowledgegate/dsa/binarytree/PreorderTraversalRecursive.java +++ b/11 Tree and Binary Tree/PreorderTraversalRecursive.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarytree; import in.knowledgegate.dsa.binarytree.model.TreeNode; @@ -9,7 +8,7 @@ * Write Preorder traversal of a binary tree using * recursive approach */ -public class PreorderTraversalRecursive { +class PreorderTraversalRecursive { public List preorderTraversal(TreeNode root) { List result = new ArrayList<>(); preorderTraversal(root, result); @@ -17,8 +16,9 @@ public List preorderTraversal(TreeNode root) { } public void preorderTraversal(TreeNode root, - List result) { - if (root == null) return; + List result) { + if (root == null) + return; result.add(root.val); preorderTraversal(root.left, result); preorderTraversal(root.right, result); diff --git a/src/in/knowledgegate/dsa/binarytree/model/TreeNode.java b/11 Tree and Binary Tree/model/TreeNode.java similarity index 60% rename from src/in/knowledgegate/dsa/binarytree/model/TreeNode.java rename to 11 Tree and Binary Tree/model/TreeNode.java index c2d7235..9c2fa7e 100644 --- a/src/in/knowledgegate/dsa/binarytree/model/TreeNode.java +++ b/11 Tree and Binary Tree/model/TreeNode.java @@ -1,11 +1,16 @@ -package in.knowledgegate.dsa.binarytree.model; -public class TreeNode { +class TreeNode { public int val; public TreeNode left; public TreeNode right; - TreeNode() {} - TreeNode(int val) { this.val = val; } + + TreeNode() { + } + + TreeNode(int val) { + this.val = val; + } + TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; diff --git a/src/in/knowledgegate/dsa/stack/ValidParenthesis.java b/12 Stack/ValidParenthesis.java similarity index 95% rename from src/in/knowledgegate/dsa/stack/ValidParenthesis.java rename to 12 Stack/ValidParenthesis.java index abdf5fb..44d34aa 100644 --- a/src/in/knowledgegate/dsa/stack/ValidParenthesis.java +++ b/12 Stack/ValidParenthesis.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.stack; import java.util.Stack; @@ -18,7 +17,7 @@ *

* Constraints: 1 <= s.length <= 104 s consists of parentheses only '()[]{}'. */ -public class ValidParenthesis { +class ValidParenthesis { public boolean isValid(String s) { Stack stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { diff --git a/src/in/knowledgegate/dsa/queue/RecentCounter.java b/13 Queue/RecentCounter.java similarity index 76% rename from src/in/knowledgegate/dsa/queue/RecentCounter.java rename to 13 Queue/RecentCounter.java index fca9037..97943b0 100644 --- a/src/in/knowledgegate/dsa/queue/RecentCounter.java +++ b/13 Queue/RecentCounter.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.queue; import java.util.LinkedList; import java.util.Queue; @@ -34,10 +33,13 @@ * * Explanation * RecentCounter recentCounter = new RecentCounter(); - * recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1 - * recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2 - * recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3 - * recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3 + * recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1 + * recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return + * 2 + * recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], + * return 3 + * recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is + * [2,3002], return 3 * * * Constraints: @@ -47,7 +49,7 @@ * increasing values of t. * At most 104 calls will be made to ping */ -public class RecentCounter { +class RecentCounter { private Queue queue; diff --git a/src/in/knowledgegate/dsa/hashingAndMaps/IntersectionOfTwoArrays.java b/14 Hashing and Maps/IntersectionOfTwoArrays.java similarity index 91% rename from src/in/knowledgegate/dsa/hashingAndMaps/IntersectionOfTwoArrays.java rename to 14 Hashing and Maps/IntersectionOfTwoArrays.java index 51844d1..346e46c 100644 --- a/src/in/knowledgegate/dsa/hashingAndMaps/IntersectionOfTwoArrays.java +++ b/14 Hashing and Maps/IntersectionOfTwoArrays.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.hashingAndMaps; import java.util.HashSet; @@ -21,7 +20,7 @@ * 1 <= nums1.length, nums2.length <= 1000 * 0 <= nums1[i], nums2[i] <= 1000 */ -public class IntersectionOfTwoArrays { +class IntersectionOfTwoArrays { public int[] intersection(int[] nums1, int[] nums2) { HashSet set = new HashSet<>(); for (int num : nums1) { diff --git a/src/in/knowledgegate/dsa/hashingAndMaps/IntersectionOfTwoArrays2.java b/14 Hashing and Maps/IntersectionOfTwoArrays2.java similarity index 93% rename from src/in/knowledgegate/dsa/hashingAndMaps/IntersectionOfTwoArrays2.java rename to 14 Hashing and Maps/IntersectionOfTwoArrays2.java index 2c56386..2ab9dd2 100644 --- a/src/in/knowledgegate/dsa/hashingAndMaps/IntersectionOfTwoArrays2.java +++ b/14 Hashing and Maps/IntersectionOfTwoArrays2.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.hashingAndMaps; import java.util.ArrayList; import java.util.HashMap; @@ -25,7 +24,7 @@ * 1 <= nums1.length, nums2.length <= 1000 * 0 <= nums1[i], nums2[i] <= 1000 */ -public class IntersectionOfTwoArrays2 { +class IntersectionOfTwoArrays2 { public int[] intersect(int[] nums1, int[] nums2) { Map cardi = new HashMap<>(); for (int num : nums1) { diff --git a/src/in/knowledgegate/dsa/hashingAndMaps/MiniMahjongWinningHand.java b/14 Hashing and Maps/MiniMahjongWinningHand.java similarity index 65% rename from src/in/knowledgegate/dsa/hashingAndMaps/MiniMahjongWinningHand.java rename to 14 Hashing and Maps/MiniMahjongWinningHand.java index 11f0d4b..61ced0b 100644 --- a/src/in/knowledgegate/dsa/hashingAndMaps/MiniMahjongWinningHand.java +++ b/14 Hashing and Maps/MiniMahjongWinningHand.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.hashingAndMaps; import java.util.HashMap; import java.util.Map; @@ -22,35 +21,39 @@ * exactly one pair, and each tile is used in * exactly one triple or pair. * - * Write a function that takes a string representation of a collection of tiles in no particular order, and returns true or false depending on whether or not the collection represents a complete hand. + * Write a function that takes a string representation of a collection of tiles + * in no particular order, and returns true or false depending on whether or not + * the collection represents a complete hand. * - * tiles1 = "11133555" # True. 111 33 555 - * tiles2 = "111333555" # False. There are three triples, 111 333 555 but no pair. - * tiles3 = "00000111" # True. 000 00 111. Your pair and a triplet can be of the same value - * # There is also no limit to how many of each tile there is. - * tiles4 = "13233121" # True. Tiles are not guaranteed to be in order - * tiles5 = "11223344555" # False. There cannot be more than one pair - * tiles6 = "99999999" # True. You can have many of one tile - * tiles7 = "999999999" # False. - * tiles8 = "9" # False. - * tiles9 = "99" # True. One pair. - * tiles10 = "000022" # False. - * tiles11 = "888889" # False. There cannot be any tiles left over. - * tiles12 = "889" # False. There cannot be any tiles left over. - * tiles13 = "88888844" # True. Two triples and one pair - * tiles14 = "77777777777777" # True. Four triples and one pair - * tiles15 = "1111111" # False. - * tiles16 = "1111122222" # False. + * tiles1 = "11133555" # True. 111 33 555 + * tiles2 = "111333555" # False. There are three triples, 111 333 555 but no + * pair. + * tiles3 = "00000111" # True. 000 00 111. Your pair and a triplet can be of the + * same value + * # There is also no limit to how many of each tile there is. + * tiles4 = "13233121" # True. Tiles are not guaranteed to be in order + * tiles5 = "11223344555" # False. There cannot be more than one pair + * tiles6 = "99999999" # True. You can have many of one tile + * tiles7 = "999999999" # False. + * tiles8 = "9" # False. + * tiles9 = "99" # True. One pair. + * tiles10 = "000022" # False. + * tiles11 = "888889" # False. There cannot be any tiles left over. + * tiles12 = "889" # False. There cannot be any tiles left over. + * tiles13 = "88888844" # True. Two triples and one pair + * tiles14 = "77777777777777" # True. Four triples and one pair + * tiles15 = "1111111" # False. + * tiles16 = "1111122222" # False. * - * complete(tiles1) => True - * complete(tiles2) => False - * complete(tiles3) => True - * complete(tiles4) => True - * complete(tiles5) => False - * complete(tiles6) => True - * complete(tiles7) => False - * complete(tiles8) => False - * complete(tiles9) => True + * complete(tiles1) => True + * complete(tiles2) => False + * complete(tiles3) => True + * complete(tiles4) => True + * complete(tiles5) => False + * complete(tiles6) => True + * complete(tiles7) => False + * complete(tiles8) => False + * complete(tiles9) => True * complete(tiles10) => False * complete(tiles11) => False * complete(tiles12) => False @@ -62,7 +65,7 @@ * Complexity Variable * N - Number of tiles in the input string */ -public class MiniMahjongWinningHand { +class MiniMahjongWinningHand { public boolean isWinningHand(String hand) { Map map = new HashMap<>(); for (int i = 0; i < hand.length(); i++) { @@ -103,8 +106,7 @@ public static void main(String[] args) { String tiles14 = "77777777777777"; String tiles15 = "1111111"; String tiles16 = "1111122222"; - MiniMahjongWinningHand obj = - new MiniMahjongWinningHand(); + MiniMahjongWinningHand obj = new MiniMahjongWinningHand(); System.out.println(tiles1 + ":" + obj.isWinningHand(tiles1)); System.out.println(tiles2 + ":" + obj.isWinningHand(tiles2)); System.out.println(tiles3 + ":" + obj.isWinningHand(tiles3)); diff --git a/src/in/knowledgegate/dsa/hashingAndMaps/TwoSum.java b/14 Hashing and Maps/TwoSum.java similarity index 91% rename from src/in/knowledgegate/dsa/hashingAndMaps/TwoSum.java rename to 14 Hashing and Maps/TwoSum.java index 1acbce1..1de0147 100644 --- a/src/in/knowledgegate/dsa/hashingAndMaps/TwoSum.java +++ b/14 Hashing and Maps/TwoSum.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.hashingAndMaps; import java.util.HashMap; import java.util.Map; @@ -20,7 +19,7 @@ * Constraints: 2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= * 109 Only one valid answer exists. */ -public class TwoSum { +class TwoSum { public int[] twoSum(int[] nums, int target) { Map map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { @@ -31,7 +30,7 @@ public int[] twoSum(int[] nums, int target) { int num = target - nums[i]; int result = map.getOrDefault(num, -1); if (result >= 0 && result != i) { - return new int[]{i, result}; + return new int[] { i, result }; } } diff --git a/src/in/knowledgegate/dsa/binarysearchtree/SearchInBST.java b/15 Binary Search Tree/SearchInBST.java similarity index 76% rename from src/in/knowledgegate/dsa/binarysearchtree/SearchInBST.java rename to 15 Binary Search Tree/SearchInBST.java index 1fbf246..df68249 100644 --- a/src/in/knowledgegate/dsa/binarysearchtree/SearchInBST.java +++ b/15 Binary Search Tree/SearchInBST.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarysearchtree; import in.knowledgegate.dsa.binarytree.model.TreeNode; @@ -12,16 +11,16 @@ * return null. * * Example 1: - * 4 - * 2 7 - * 1 3 X X + * 4 + * 2 7 + * 1 3 X X * Input: root = [4,2,7,1,3], val = 2 * Output: [2,1,3] * * Example 2: - * 4 - * 2 7 - * 1 3 X X + * 4 + * 2 7 + * 1 3 X X * Input: root = [4,2,7,1,3], val = 5 * Output: [] * @@ -34,10 +33,12 @@ * root is a binary search tree. * 1 <= val <= 107 */ -public class SearchInBST { +class SearchInBST { public TreeNode searchBST(TreeNode root, int val) { - if (root == null) return null; - if (root.val == val) return root; + if (root == null) + return null; + if (root.val == val) + return root; if (root.val < val) { return searchBST(root.right, val); } diff --git a/src/in/knowledgegate/dsa/graph/FindTheTownJudge.java b/16 Graph/FindTheTownJudge.java similarity index 90% rename from src/in/knowledgegate/dsa/graph/FindTheTownJudge.java rename to 16 Graph/FindTheTownJudge.java index ac11819..790b15e 100644 --- a/src/in/knowledgegate/dsa/graph/FindTheTownJudge.java +++ b/16 Graph/FindTheTownJudge.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.graph; /** * In a town, there are n people labeled from @@ -41,16 +40,16 @@ * ai != bi * 1 <= ai, bi <= n */ -public class FindTheTownJudge { +class FindTheTownJudge { public int findJudge(int n, int[][] trust) { int[] count = new int[n + 1]; - for (int[] trustRow: trust) { + for (int[] trustRow : trust) { count[trustRow[0]]--; count[trustRow[1]]++; } for (int i = 1; i < count.length; i++) { - if (count[i] == n-1) { + if (count[i] == n - 1) { return i; } } diff --git a/src/in/knowledgegate/dsa/bfs/InvertBinaryTree.java b/17 DFS and BFS/InvertBinaryTree.java similarity index 76% rename from src/in/knowledgegate/dsa/bfs/InvertBinaryTree.java rename to 17 DFS and BFS/InvertBinaryTree.java index 2d1aed5..01cc796 100644 --- a/src/in/knowledgegate/dsa/bfs/InvertBinaryTree.java +++ b/17 DFS and BFS/InvertBinaryTree.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.bfs; import in.knowledgegate.dsa.binarytree.model.TreeNode; @@ -7,9 +6,9 @@ * tree, and return its root. * * Example 1: - * 4 4 - * 2 7 7 2 - * 1 3 6 9 9 6 3 1 + * 4 4 + * 2 7 7 2 + * 1 3 6 9 9 6 3 1 * * Input: root = [4,2,7,1,3,6,9] * Output: [4,7,2,9,6,3,1] @@ -23,9 +22,10 @@ * range [0, 100]. * -100 <= Node.val <= 100 */ -public class InvertBinaryTree { +class InvertBinaryTree { public TreeNode invertTree(TreeNode root) { - if (root == null) return null; + if (root == null) + return null; TreeNode temp = root.left; root.left = root.right; root.right = temp; diff --git a/src/in/knowledgegate/dsa/dfs/PathSum.java b/17 DFS and BFS/PathSum.java similarity index 87% rename from src/in/knowledgegate/dsa/dfs/PathSum.java rename to 17 DFS and BFS/PathSum.java index 1dc61f4..300678b 100644 --- a/src/in/knowledgegate/dsa/dfs/PathSum.java +++ b/17 DFS and BFS/PathSum.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.dfs; import in.knowledgegate.dsa.binarytree.model.TreeNode; @@ -11,8 +10,8 @@ * A leaf is a node with no children. * * Example 1: - * 1 - * 2 3 + * 1 + * 2 3 * * Input: root = [1,2,3], targetSum = 5 * Output: false @@ -37,10 +36,12 @@ * -1000 <= Node.val <= 1000 * -1000 <= targetSum <= 1000 */ -public class PathSum { +class PathSum { public boolean hasPathSum(TreeNode root, int targetSum) { - if (root == null) return false; - if (root.val == targetSum && isLeaf(root)) return true; + if (root == null) + return false; + if (root.val == targetSum && isLeaf(root)) + return true; int newTargetSum = targetSum - root.val; return hasPathSum(root.left, newTargetSum) || hasPathSum(root.right, newTargetSum); diff --git a/17 DFS and BFS/Solitaire.java b/17 DFS and BFS/Solitaire.java new file mode 100644 index 0000000..ddbdb80 --- /dev/null +++ b/17 DFS and BFS/Solitaire.java @@ -0,0 +1,136 @@ + +/** + * While your players are waiting for a game, + * you've developed a solitaire game for the + * players to pass the time with. + * The player is given an NxM board of tiles from + * 0 to 9 like this: + * 4 4 4 4 + * 5 5 5 4 + * 2 5 7 5 + * The player selects one of these tiles, and that + * tile will disappear, along with any tiles with + * the same number that are connected with that tile + * (up, down, left, or right), and any tiles with the + * same number connected with those, and so on. For + * example, if the 4 in the upper left corner is + * selected, these five tiles disappear + * >4< >4< >4< >4< + * 5 5 5 >4< + * 2 5 7 5 + * If the 5 just below it is selected, these four + * tiles disappear. Note that tiles are not + * connected diagonally. + * 4 4 4 4 + * >5< >5< >5< 4 + * 2 >5< 7 5 + * Write a function that, given a grid of tiles + * and a selected row and column of a tile, + * returns how many tiles will disappear. + * grid1 = [[4, 4, 4, 4], + * [5, 5, 5, 4], + * [2, 5, 7, 5]] + * disappear(grid1, 0, 0) => 5 + * disappear(grid1, 1, 1) => 4 + * disappear(grid1, 1, 0) => 4 + * This is the grid from above. + * + * Additional Inputs + * grid2 = [[0, 3, 3, 3, 3, 3, 3], + * [0, 1, 1, 1, 1, 1, 3], + * [0, 2, 2, 0, 2, 1, 4], + * [0, 1, 2, 2, 2, 1, 3], + * [0, 1, 1, 1, 1, 1, 3], + * [0, 0, 0, 0, 0, 0, 0]] + * + * grid3 = [[0]] + * + * grid4 = [[1, 1, 1], + * [1, 1, 1], + * [1, 1, 1]] + * + * All Test Cases + * disappear(grid1, 0, 0) => 5 + * disappear(grid1, 1, 1) => 4 + * disappear(grid1, 1, 0) => 4 + * disappear(grid2, 0, 0) => 12 + * disappear(grid2, 3, 0) => 12 + * disappear(grid2, 1, 1) => 13 + * disappear(grid2, 2, 2) => 6 + * disappear(grid2, 0, 3) => 7 + * disappear(grid3, 0, 0) => 1 + * disappear(grid4, 0, 0) => 9 + * + * N - Width of the grid + * M - Height of the grid + * + * Clarifications + * - All values are between 0 and 9 + * - The grid will not be empty + * - The input board is immutable. If the + * candidate suggests modifying the board you + * should suggest they make a deep copy of the board + * instead. This does not constitute handholding. + * - The input row and column will always be on + * the board. + */ +class Solitaire { + public int disappear(int[][] grid, int x, + int y) { + if (grid.length <= 0) + return 0; + int[][] newGrid = new int[grid.length][grid[0].length]; + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[i].length; j++) { + newGrid[i][j] = grid[i][j]; + } + } + return disappear(newGrid, x, y, newGrid[x][y]); + } + + public int disappear(int[][] grid, int x, + int y, int num) { + if (x >= grid.length || y >= grid[0].length || + x < 0 || y < 0 || grid[x][y] != num || + grid[x][y] == -1) + return 0; + + grid[x][y] = -1; + return 1 + disappear(grid, x, y + 1, num) + + disappear(grid, x + 1, y, num) + + disappear(grid, x - 1, y, num) + + disappear(grid, x, y - 1, num); + } + + public static void main(String[] args) { + int[][] grid1 = { { 4, 4, 4, 4 }, + { 5, 5, 5, 4 }, + { 2, 5, 7, 5 } }; + int[][] grid2 = { { 0, 3, 3, 3, 3, 3, 3 }, + { 0, 1, 1, 1, 1, 1, 3 }, + { 0, 2, 2, 0, 2, 1, 4 }, + { 0, 1, 2, 2, 2, 1, 3 }, + { 0, 1, 1, 1, 1, 1, 3 }, + { 0, 0, 0, 0, 0, 0, 0 } }; + int[][] grid3 = { { 0 } }; + int[][] grid4 = { { 1, 1, 1 }, + { 1, 1, 1 }, + { 1, 1, 1 } }; + + Solitaire solitaire = new Solitaire(); + System.out.println(solitaire.disappear(grid1, 0, 0)); + System.out.println(solitaire.disappear(grid1, 1, 0)); + System.out.println(solitaire.disappear(grid1, 2, 0)); + System.out.println(solitaire.disappear(grid1, 2, 2)); + + System.out.println(solitaire.disappear(grid2, 0, 0)); + System.out.println(solitaire.disappear(grid2, 0, 1)); + System.out.println(solitaire.disappear(grid2, 1, 1)); + System.out.println(solitaire.disappear(grid2, 2, 1)); + System.out.println(solitaire.disappear(grid2, 0, 0)); + + System.out.println(solitaire.disappear(grid3, 0, 0)); + + System.out.println(solitaire.disappear(grid4, 0, 0)); + } +} diff --git a/src/in/knowledgegate/dsa/greedy/BestTimeToBuyAndSellStock.java b/18 Greedy/BestTimeToBuyAndSellStock.java similarity index 94% rename from src/in/knowledgegate/dsa/greedy/BestTimeToBuyAndSellStock.java rename to 18 Greedy/BestTimeToBuyAndSellStock.java index 6bfe166..fac1858 100644 --- a/src/in/knowledgegate/dsa/greedy/BestTimeToBuyAndSellStock.java +++ b/18 Greedy/BestTimeToBuyAndSellStock.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.greedy; /** * You are given an array prices where prices[i] @@ -32,7 +31,7 @@ * 1 <= prices.length <= 105 * 0 <= prices[i] <= 104 */ -public class BestTimeToBuyAndSellStock { +class BestTimeToBuyAndSellStock { public int maxProfit(int[] prices) { int buy = prices[0], maxProfit = 0; for (int i = 1; i < prices.length; i++) { diff --git a/src/in/knowledgegate/dsa/greedy/MiniMahjongWinningHand2.java b/18 Greedy/MiniMahjongWinningHand2.java similarity index 52% rename from src/in/knowledgegate/dsa/greedy/MiniMahjongWinningHand2.java rename to 18 Greedy/MiniMahjongWinningHand2.java index 784501b..14c0ee4 100644 --- a/src/in/knowledgegate/dsa/greedy/MiniMahjongWinningHand2.java +++ b/18 Greedy/MiniMahjongWinningHand2.java @@ -1,66 +1,65 @@ -package in.knowledgegate.dsa.greedy; import java.util.HashMap; import java.util.Map; /** - You've decided to make an advanced version of a - variant of the game Mahjong, incorporating runs. - - Players have a number of hand, each marked 0-9. - The hand can be grouped into pairs or triples of - the same tile or runs. - - A run is a series of three consecutive hand, - like 123, 678, or 456. 0 counts as the lowest tile, - so 012 is a valid run, but 890 is not. - - A complete hand consists of exactly one pair, and - any number (including zero) of triples and/or - three-tile runs. Each tile is used in exactly one - triple, pair, or run. - - Write a function that returns true or false - depending on whether or not the collection - represents a complete hand under these rules. - - hand1 = "11123" # True. 11 123 - hand2 = "12131" # True. Also 11 123. hand are not necessarily sorted. - hand3 = "11123455" # True. 111 234 55 - hand4 = "11122334" # True. 11 123 234 - hand5 = "11234" # True. 11 234 - hand6 = "123456" # False. Needs a pair - hand7 = "11133355577" # True. 111 333 555 77 - hand8 = "11223344556677" # True. 11 234 234 567 567 among others - hand9 = "12233444556677" # True. 123 234 44 567 567 - hand10 = "11234567899" # False. - hand11 = "00123457" # False. - hand12 = "0012345" # False. A run is only three hand - hand13 = "11890" # False. 890 is not a valid run - hand14 = "99" # True. - hand15 = "111223344" # False. - - All Test Cases - advanced(hand1) => True - advanced(hand2) => True - advanced(hand3) => True - advanced(hand4) => True - advanced(hand5) => True - advanced(hand6) => False - advanced(hand7) => True - advanced(hand8) => True - advanced(hand9) => True - advanced(hand10) => False - advanced(hand11) => False - advanced(hand12) => False - advanced(hand13) => False - advanced(hand14) => True - advanced(hand15) => False - - Complexity Variable - N - Number of hand in the input string + * You've decided to make an advanced version of a + * variant of the game Mahjong, incorporating runs. + * + * Players have a number of hand, each marked 0-9. + * The hand can be grouped into pairs or triples of + * the same tile or runs. + * + * A run is a series of three consecutive hand, + * like 123, 678, or 456. 0 counts as the lowest tile, + * so 012 is a valid run, but 890 is not. + * + * A complete hand consists of exactly one pair, and + * any number (including zero) of triples and/or + * three-tile runs. Each tile is used in exactly one + * triple, pair, or run. + * + * Write a function that returns true or false + * depending on whether or not the collection + * represents a complete hand under these rules. + * + * hand1 = "11123" # True. 11 123 + * hand2 = "12131" # True. Also 11 123. hand are not necessarily sorted. + * hand3 = "11123455" # True. 111 234 55 + * hand4 = "11122334" # True. 11 123 234 + * hand5 = "11234" # True. 11 234 + * hand6 = "123456" # False. Needs a pair + * hand7 = "11133355577" # True. 111 333 555 77 + * hand8 = "11223344556677" # True. 11 234 234 567 567 among others + * hand9 = "12233444556677" # True. 123 234 44 567 567 + * hand10 = "11234567899" # False. + * hand11 = "00123457" # False. + * hand12 = "0012345" # False. A run is only three hand + * hand13 = "11890" # False. 890 is not a valid run + * hand14 = "99" # True. + * hand15 = "111223344" # False. + * + * All Test Cases + * advanced(hand1) => True + * advanced(hand2) => True + * advanced(hand3) => True + * advanced(hand4) => True + * advanced(hand5) => True + * advanced(hand6) => False + * advanced(hand7) => True + * advanced(hand8) => True + * advanced(hand9) => True + * advanced(hand10) => False + * advanced(hand11) => False + * advanced(hand12) => False + * advanced(hand13) => False + * advanced(hand14) => True + * advanced(hand15) => False + * + * Complexity Variable + * N - Number of hand in the input string */ -public class MiniMahjongWinningHand2 { +class MiniMahjongWinningHand2 { public boolean isWinningHand(String hand) { Map map = new HashMap<>(); @@ -70,7 +69,8 @@ public boolean isWinningHand(String hand) { } for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() < 2) continue; + if (entry.getValue() < 2) + continue; Map newMap = new HashMap<>(map); newMap.put(entry.getKey(), entry.getValue() - 2); @@ -81,25 +81,24 @@ public boolean isWinningHand(String hand) { return false; } - private boolean isWinningHand(Map newMap) { + private boolean isWinningHand(Map newMap) { // remove triplets for (int i = 0; i <= 9; i++) { int val = newMap.getOrDefault(i, 0); newMap.put(i, val % 3); } - //remove all possible runs + // remove all possible runs for (int i = 0; i < 7; i++) { int val1 = newMap.getOrDefault(i, 0); - int val2 = newMap.getOrDefault(i+1, 0); - int val3 = newMap.getOrDefault(i+2, 0); + int val2 = newMap.getOrDefault(i + 1, 0); + int val3 = newMap.getOrDefault(i + 2, 0); int run = Math.min(Math.min(val1, val2), val3); if (run > 0) { newMap.put(i, val1 - run); - newMap.put(i+1, val2 - run); - newMap.put(i+2, val3 - run); + newMap.put(i + 1, val2 - run); + newMap.put(i + 2, val3 - run); } } @@ -129,8 +128,7 @@ public static void main(String[] args) { String hand13 = "11890"; String hand14 = "99"; String hand15 = "111223344"; - MiniMahjongWinningHand2 obj = - new MiniMahjongWinningHand2(); + MiniMahjongWinningHand2 obj = new MiniMahjongWinningHand2(); System.out.println(hand1 + ":" + obj.isWinningHand(hand1)); System.out.println(hand2 + ":" + obj.isWinningHand(hand2)); System.out.println(hand3 + ":" + obj.isWinningHand(hand3)); diff --git a/src/in/knowledgegate/dsa/backtracking/GenerateParentheses.java b/19 Backtracking/GenerateParentheses.java similarity index 75% rename from src/in/knowledgegate/dsa/backtracking/GenerateParentheses.java rename to 19 Backtracking/GenerateParentheses.java index cff5f82..3ff3637 100644 --- a/src/in/knowledgegate/dsa/backtracking/GenerateParentheses.java +++ b/19 Backtracking/GenerateParentheses.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.backtracking; import java.util.ArrayList; import java.util.List; @@ -19,12 +18,10 @@ * Constraints: * 1 <= n <= 8 */ -public class GenerateParentheses { +class GenerateParentheses { public static void main(String[] args) { - GenerateParentheses generator = - new GenerateParentheses(); - List parentheses = - generator.generateParenthesis(3); + GenerateParentheses generator = new GenerateParentheses(); + List parentheses = generator.generateParenthesis(3); System.out.println("Generate output:"); for (String parenthesis : parentheses) { System.out.print(" " + parenthesis); @@ -33,15 +30,14 @@ public static void main(String[] args) { public List generateParenthesis(int n) { List result = new ArrayList<>(); - backtrack(result, new StringBuilder(), 0, 0 - ,n); + backtrack(result, new StringBuilder(), 0, 0, n); return result; } private void backtrack(List result, StringBuilder cur, int open, int close, - int max) { - if (cur.length() == max*2) { + int max) { + if (cur.length() == max * 2) { result.add(cur.toString()); return; } @@ -60,8 +56,3 @@ private void backtrack(List result, } } } - - - - - diff --git a/19 Backtracking/NQueen.java b/19 Backtracking/NQueen.java new file mode 100644 index 0000000..f79ea99 --- /dev/null +++ b/19 Backtracking/NQueen.java @@ -0,0 +1,103 @@ + +import java.util.Scanner; + +/** + * The n-queens puzzle is the problem of placing + * n queens on an n x n chessboard such that no + * two queens attack each other. + * + * Given an integer n, return any one solution + * to the n-queens puzzle. You may + * return the answer in any order. + * + * Each solution contains a distinct board + * configuration of the n-queens' placement, + * where 'Q' and '.' both indicate a queen and + * an empty space, respectively. + * + * Example 1: + * Input: n = 4 + * Output: [["..Q.","Q...","...Q",".Q.."]] + * + * Example 2: + * Input: n = 1 + * Output: [["Q"]] + * + * Constraints: + * 1 <= n <= 30 + */ +class NQueen { + private void printBoard(int[][] board) { + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[i].length; j++) { + char out = board[i][j] == 1 ? 'Q' : '.'; + System.out.print(" " + out + " "); + } + System.out.println(); + } + } + + private boolean isMoveSafe(int[][] board, + int row, int col) { + + for (int j = 0; j < col; j++) { + if (board[row][j] == 1) { + return false; + } + } + + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { + if (board[i][j] == 1) { + return false; + } + } + + for (int i = row, j = col; j >= 0 && i < board.length; j--, i++) { + if (board[i][j] == 1) { + return false; + } + } + + return true; + } + + /** + * This method is only responsible to put queen + * in a specific column. + */ + private boolean nQueen(int[][] board, int col) { + if (col >= board.length) { + return true; + } + + for (int i = 0; i < board.length; i++) { + if (isMoveSafe(board, i, col)) { + board[i][col] = 1; + if (nQueen(board, col + 1)) + return true; + board[i][col] = 0; + } + } + + return false; + } + + private void nQueen(int size) { + int[][] board = new int[size][size]; + if (!nQueen(board, 0)) { + System.out.println("Solution does not " + + "exist"); + } else { + printBoard(board); + } + } + + public static void main(String[] args) { + try (Scanner scanner = new Scanner(System.in)) { + NQueen nQueen = new NQueen(); + System.out.print("Enter size of board: "); + int size = scanner.nextInt(); + nQueen.nQueen(size); + } + } +} diff --git a/src/in/knowledgegate/dsa/backtracking/Subsets.java b/19 Backtracking/Subsets.java similarity index 89% rename from src/in/knowledgegate/dsa/backtracking/Subsets.java rename to 19 Backtracking/Subsets.java index c87f0f8..f29ca3c 100644 --- a/src/in/knowledgegate/dsa/backtracking/Subsets.java +++ b/19 Backtracking/Subsets.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.backtracking; import java.util.ArrayList; import java.util.List; @@ -21,10 +20,10 @@ * nums[i] <= 10 All the numbers of nums are * unique. */ -public class Subsets { +class Subsets { public static void main(String[] args) { Subsets subsets = new Subsets(); - int[] nums = new int[]{}; + int[] nums = new int[] {}; System.out.println("PowerSet is :" + subsets.subsets(nums)); } @@ -39,8 +38,8 @@ public List> subsets(int[] nums) { } private void backtrack(List> output, - int length, int beg, List curr, - int[] nums) { + int length, int beg, List curr, + int[] nums) { if (curr.size() == length) { output.add(new ArrayList<>(curr)); diff --git a/2 Time Complexity/ArrayCopy.java b/2 Time Complexity/ArrayCopy.java new file mode 100644 index 0000000..1c2c518 --- /dev/null +++ b/2 Time Complexity/ArrayCopy.java @@ -0,0 +1,15 @@ + +class ArrayCopy { + + public static void main(String[] args) { + int[] newCopy = copy(new int[] { 1, 2, 3, 4, 5 }); + } + + private static int[] copy(int[] array) { + int[] newCopy = new int[array.length]; + for (int i = 0; i < array.length; i++) { + newCopy[i] = array[i]; + } + return newCopy; + } +} \ No newline at end of file diff --git a/src/in/knowledgegate/dsa/complexity/ArraySum.java b/2 Time Complexity/ArraySum.java similarity index 55% rename from src/in/knowledgegate/dsa/complexity/ArraySum.java rename to 2 Time Complexity/ArraySum.java index 27a6931..378bd5d 100644 --- a/src/in/knowledgegate/dsa/complexity/ArraySum.java +++ b/2 Time Complexity/ArraySum.java @@ -1,9 +1,8 @@ -package in.knowledgegate.dsa.complexity; -public class ArraySum { +class ArraySum { public static void main(String[] args) { - System.out.println("Sum:" + sum(new int[]{5, 6})); - System.out.println("Sum:" + sum(new int[]{1, 2, 3, 4, 5})); + System.out.println("Sum:" + sum(new int[] { 5, 6 })); + System.out.println("Sum:" + sum(new int[] { 1, 2, 3, 4, 5 })); } private static int sum(int[] array) { diff --git a/src/in/knowledgegate/dsa/complexity/Sum.java b/2 Time Complexity/Sum.java similarity index 78% rename from src/in/knowledgegate/dsa/complexity/Sum.java rename to 2 Time Complexity/Sum.java index 2d89ac1..11d7e73 100644 --- a/src/in/knowledgegate/dsa/complexity/Sum.java +++ b/2 Time Complexity/Sum.java @@ -1,6 +1,5 @@ -package in.knowledgegate.dsa.complexity; -public class Sum { +class Sum { public static void main(String[] args) { System.out.println("Sum:" + sum(5, 6)); System.out.println("Sum:" + sum(8, 10)); diff --git a/src/in/knowledgegate/dsa/heap/KthLargestElement.java b/20 Heap/KthLargestElement.java similarity index 76% rename from src/in/knowledgegate/dsa/heap/KthLargestElement.java rename to 20 Heap/KthLargestElement.java index 90f4495..ad9eca6 100644 --- a/src/in/knowledgegate/dsa/heap/KthLargestElement.java +++ b/20 Heap/KthLargestElement.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.heap; import java.util.PriorityQueue; @@ -21,18 +20,16 @@ * 1 <= k <= nums.length <= 104 * -104 <= nums[i] <= 104 */ -public class KthLargestElement { +class KthLargestElement { public static void main(String[] args) { - KthLargestElement kthLargest = - new KthLargestElement(); - int[] nums = new int[]{3,2,3,1,2,4,5,5,6}; + KthLargestElement kthLargest = new KthLargestElement(); + int[] nums = new int[] { 3, 2, 3, 1, 2, 4, 5, 5, 6 }; System.out.println("Kth largest is:" + kthLargest.findKthLargest(nums, 6)); } public int findKthLargest(int[] nums, int k) { - PriorityQueue kLargest = - new PriorityQueue<>(); + PriorityQueue kLargest = new PriorityQueue<>(); for (int num : nums) { kLargest.add(num); if (kLargest.size() > k) { diff --git a/src/in/knowledgegate/dsa/dynamicprogramming/ClimbingStairs.java b/21 Dynamic Programming/ClimbingStairs.java similarity index 86% rename from src/in/knowledgegate/dsa/dynamicprogramming/ClimbingStairs.java rename to 21 Dynamic Programming/ClimbingStairs.java index b602386..6b66de7 100644 --- a/src/in/knowledgegate/dsa/dynamicprogramming/ClimbingStairs.java +++ b/21 Dynamic Programming/ClimbingStairs.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.dynamicprogramming; /** * You are climbing a staircase. It takes n steps @@ -27,13 +26,15 @@ * Constraints: * 1 <= n <= 45 */ -public class ClimbingStairs { +class ClimbingStairs { /** * f(n) = f(n-1) + f(n-2) */ public int climbStairs(int n) { - if (n == 1) return 1; - if (n == 2) return 2; + if (n == 1) + return 1; + if (n == 2) + return 2; int first = 1, second = 2, current = 0; for (int i = 2; i < n; i++) { diff --git a/src/in/knowledgegate/dsa/dynamicprogramming/RodCutting.java b/21 Dynamic Programming/RodCutting.java similarity index 81% rename from src/in/knowledgegate/dsa/dynamicprogramming/RodCutting.java rename to 21 Dynamic Programming/RodCutting.java index 8e43f66..41800a5 100644 --- a/src/in/knowledgegate/dsa/dynamicprogramming/RodCutting.java +++ b/21 Dynamic Programming/RodCutting.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.dynamicprogramming; import java.util.HashMap; import java.util.Map; @@ -15,25 +14,23 @@ * pieces of lengths 2 and 6) * * Example: - * length | 1 2 3 4 5 6 7 8 + * length | 1 2 3 4 5 6 7 8 * -------------------------------------------- - * price | 1 5 8 9 10 17 17 20 + * price | 1 5 8 9 10 17 17 20 * And if the prices are as following, then the * maximum obtainable value is 24 (by cutting in * eight pieces of length 1) * */ -public class RodCutting { +class RodCutting { static int count = 0; public static void main(String[] args) { RodCutting rodCutting = new RodCutting(); - int price[] - = new int[] { 1, 5, 8, 9, 10, 17, 17, + int price[] = new int[] { 1, 5, 8, 9, 10, 17, 17, 20, 24 }; int n = price.length; - Map maxProfit = - new HashMap<>(); + Map maxProfit = new HashMap<>(); System.out.println( "Maximum obtained value is " + rodCutting.cutRod(price, n, maxProfit)); @@ -42,7 +39,8 @@ public static void main(String[] args) { public int cutRod(int prices[], int length, Map maxProfit) { - if (length <= 0) return 0; + if (length <= 0) + return 0; if (maxProfit.containsKey(length)) { return maxProfit.get(length); } diff --git a/src/in/knowledgegate/dsa/dynamicprogramming/Subsets.java b/21 Dynamic Programming/Subsets.java similarity index 85% rename from src/in/knowledgegate/dsa/dynamicprogramming/Subsets.java rename to 21 Dynamic Programming/Subsets.java index b913b90..4386069 100644 --- a/src/in/knowledgegate/dsa/dynamicprogramming/Subsets.java +++ b/21 Dynamic Programming/Subsets.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.dynamicprogramming; import java.util.ArrayList; import java.util.List; @@ -21,10 +20,10 @@ * nums[i] <= 10 All the numbers of nums are * unique. */ -public class Subsets { +class Subsets { public static void main(String[] args) { Subsets subsets = new Subsets(); - int[] nums = new int[]{1, 2, 3, 4}; + int[] nums = new int[] { 1, 2, 3, 4 }; System.out.println("PowerSet is:" + subsets.subsets(nums)); } @@ -36,8 +35,7 @@ public List> subsets(int[] nums) { for (int num : nums) { int length = res.size(); for (int i = 0; i < length; i++) { - List copy = - new ArrayList<>(res.get(i)); + List copy = new ArrayList<>(res.get(i)); copy.add(num); res.add(copy); } diff --git a/src/in/knowledgegate/dsa/slidingwindow/ContainsDuplicate2.java b/22 Sliding Window/ContainsDuplicate2.java similarity index 86% rename from src/in/knowledgegate/dsa/slidingwindow/ContainsDuplicate2.java rename to 22 Sliding Window/ContainsDuplicate2.java index bc49eac..bcc3c46 100644 --- a/src/in/knowledgegate/dsa/slidingwindow/ContainsDuplicate2.java +++ b/22 Sliding Window/ContainsDuplicate2.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.slidingwindow; import java.util.HashSet; import java.util.Set; @@ -26,14 +25,15 @@ * -109 <= nums[i] <= 109 * 0 <= k <= 105 */ -public class ContainsDuplicate2 { +class ContainsDuplicate2 { public boolean containsNearbyDuplicate(int[] nums, int k) { Set window = new HashSet<>(); for (int i = 0; i < nums.length; i++) { if (i > k) { window.remove(nums[i - k - 1]); } - if (!window.add(nums[i])) return true; + if (!window.add(nums[i])) + return true; } return false; } diff --git a/3 Strings/387 First Unique Character in a String.java b/3 Strings/387 First Unique Character in a String.java new file mode 100644 index 0000000..cdc5942 --- /dev/null +++ b/3 Strings/387 First Unique Character in a String.java @@ -0,0 +1,22 @@ + +import java.util.HashMap; + +class FirstUniqueCharacter { + public int firstUniqChar(String s) { + HashMap countMap = new HashMap<>(); + // Filling characters into the map + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + countMap.put(c, countMap.getOrDefault(c, 0) + 1); + } + + // Checking count 1 + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (countMap.get(c) == 1) { + return i; + } + } + return -1; + } +} diff --git a/3 Strings/GenerateParentheses.java b/3 Strings/GenerateParentheses.java new file mode 100644 index 0000000..2542cc1 --- /dev/null +++ b/3 Strings/GenerateParentheses.java @@ -0,0 +1,67 @@ + +import java.util.ArrayList; +import java.util.List; + +/** + * Given n pairs of parentheses, write a function + * to generate all combinations of well-formed + * parentheses. + * + * Example 1: + * Input: n = 3 + * Output: ["((()))","(()())","(())()","()(())","()()()"] + * + * Example 2: + * Input: n = 1 + * Output: ["()"] + * + * Constraints: + * 1 <= n <= 8 + */ +class GenerateParentheses { + + public static void main(String[] args) { + GenerateParentheses obj = new GenerateParentheses(); + System.out.println("Here is the result:"); + for (String combi : obj.generateParenthesis(3)) { + System.out.print(combi + ", "); + } + } + + public List generateParenthesis(int n) { + List combinations = new ArrayList<>(); + generateAllCombinations(new char[n * 2], 0, + combinations); + return combinations; + } + + private void generateAllCombinations(char[] current, + int pos, List combinations) { + if (pos == current.length) { + if (isValid(current)) { + combinations.add(new String(current)); + } + } else { + current[pos] = '('; + generateAllCombinations(current, pos + 1, + combinations); + current[pos] = ')'; + generateAllCombinations(current, pos + 1, + combinations); + } + } + + private boolean isValid(char[] current) { + int counter = 0; + for (int i = 0; i < current.length; i++) { + if (current[i] == '(') { + counter++; + } else { + counter--; + } + if (counter < 0) + return false; + } + return counter == 0; + } +} diff --git a/src/in/knowledgegate/dsa/strings/LongestCommonPrefix.java b/3 Strings/LongestCommonPrefix.java similarity index 85% rename from src/in/knowledgegate/dsa/strings/LongestCommonPrefix.java rename to 3 Strings/LongestCommonPrefix.java index 7d941f1..41b2503 100644 --- a/src/in/knowledgegate/dsa/strings/LongestCommonPrefix.java +++ b/3 Strings/LongestCommonPrefix.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.strings; /** * Write a function to find the longest common @@ -20,15 +19,15 @@ * strs[i].length <= 200 strs[i] consists of only * lower-case English letters. */ -public class LongestCommonPrefix { +class LongestCommonPrefix { public String longestCommonPrefix(String[] strs) { String result = ""; for (int i = 0; i < strs[0].length(); i++) { char finding = strs[0].charAt(i); for (int j = 1; j < strs.length; j++) { if (strs[j].length() <= i || - finding != strs[j].charAt(i)) { - return result; + finding != strs[j].charAt(i)) { + return result; } } result += finding; diff --git a/src/in/knowledgegate/dsa/strings/ReverseString.java b/3 Strings/ReverseString.java similarity index 90% rename from src/in/knowledgegate/dsa/strings/ReverseString.java rename to 3 Strings/ReverseString.java index 47db6aa..8433b35 100644 --- a/src/in/knowledgegate/dsa/strings/ReverseString.java +++ b/3 Strings/ReverseString.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.strings; /** * Write a function that reverses a string. The @@ -19,7 +18,7 @@ * 1 <= s.length <= 105 * s[i] is a printable ascii character. */ -public class ReverseString { +class ReverseString { public void reverseString(char[] s) { for (int i = 0; i < s.length / 2; i++) { char temp = s[i]; diff --git a/src/in/knowledgegate/dsa/strings/ValidPalindrome.java b/3 Strings/ValidPalindrome.java similarity index 87% rename from src/in/knowledgegate/dsa/strings/ValidPalindrome.java rename to 3 Strings/ValidPalindrome.java index 07edef4..937fc79 100644 --- a/src/in/knowledgegate/dsa/strings/ValidPalindrome.java +++ b/3 Strings/ValidPalindrome.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.strings; /** * A phrase is a palindrome if, after converting all uppercase letters into @@ -21,7 +20,7 @@ * Constraints: 1 <= s.length <= 2 * 105 s consists only of printable ASCII * characters. */ -public class ValidPalindrome { +class ValidPalindrome { public boolean isPalindrome(String s) { int beg = 0, end = s.length() - 1; while (beg < end) { @@ -43,9 +42,12 @@ public boolean isPalindrome(String s) { } private int validChar(char c) { - if (c >= '0' && c <= '9') return c; - if (c >= 'a' && c <= 'z') return c; - if (c >= 'A' && c <= 'Z') return c - 'A' + 'a'; + if (c >= '0' && c <= '9') + return c; + if (c >= 'a' && c <= 'z') + return c; + if (c >= 'A' && c <= 'Z') + return c - 'A' + 'a'; return -1; } } diff --git a/src/in/knowledgegate/dsa/math/AddStrings.java b/4 Math/AddStrings.java similarity index 83% rename from src/in/knowledgegate/dsa/math/AddStrings.java rename to 4 Math/AddStrings.java index f1c3092..db2afe7 100644 --- a/src/in/knowledgegate/dsa/math/AddStrings.java +++ b/4 Math/AddStrings.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.math; /** * Given two non-negative integers, num1 and num2 @@ -30,21 +29,22 @@ * num1 and num2 consist of only digits. * num1 and num2 don't have any leading zeros except for the zero itself. */ -public class AddStrings { +class AddStrings { public static void main(String[] args) { AddStrings addStrings = new AddStrings(); System.out.println("Sum is: " - + addStrings.addStrings("456765765", - "777868")); + + addStrings.addStrings("456765765", + "777868")); } + public String addStrings(String num1, String num2) { int carry = 0; StringBuilder result = new StringBuilder(); int i = num1.length() - 1; int j = num2.length() - 1; while (i >= 0 || j >= 0 || carry > 0) { - int x = i >= 0 ? num1.charAt(i--) - '0': 0; - int y = j >= 0 ? num2.charAt(j--) - '0': 0; + int x = i >= 0 ? num1.charAt(i--) - '0' : 0; + int y = j >= 0 ? num2.charAt(j--) - '0' : 0; int rem = (x + y + carry) % 10; result.insert(0, rem); carry = (x + y + carry) / 10; diff --git a/src/in/knowledgegate/dsa/math/ConvertNumberToHexadecimal.java b/4 Math/ConvertNumberToHexadecimal.java similarity index 72% rename from src/in/knowledgegate/dsa/math/ConvertNumberToHexadecimal.java rename to 4 Math/ConvertNumberToHexadecimal.java index d0d3d6d..21c8136 100644 --- a/src/in/knowledgegate/dsa/math/ConvertNumberToHexadecimal.java +++ b/4 Math/ConvertNumberToHexadecimal.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.math; /** * Given an integer num, return a string representing @@ -24,18 +23,16 @@ * Constraints: * -231 <= num <= 231 - 1 */ -public class ConvertNumberToHexadecimal { +class ConvertNumberToHexadecimal { public static void main(String[] args) { - ConvertNumberToHexadecimal converter = - new ConvertNumberToHexadecimal(); + ConvertNumberToHexadecimal converter = new ConvertNumberToHexadecimal(); System.out.println("Output is: " - + converter.toHex(156)); + + converter.toHex(156)); } public String toHex(int num) { - char[] hex = new char[]{'0', '1', '2', - '3', '4', '5', '6', '7', '8', '9', 'a' - , 'b', 'c', 'd', 'e', 'f'}; + char[] hex = new char[] { '0', '1', '2', + '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; StringBuilder sb = new StringBuilder(); while (num > 0) { int rem = num % 16; diff --git a/src/in/knowledgegate/dsa/math/CountPrimes.java b/4 Math/CountPrimes.java similarity index 80% rename from src/in/knowledgegate/dsa/math/CountPrimes.java rename to 4 Math/CountPrimes.java index 0f37983..9695090 100644 --- a/src/in/knowledgegate/dsa/math/CountPrimes.java +++ b/4 Math/CountPrimes.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.math; /** * Given an integer n, return the number of prime @@ -21,11 +20,11 @@ * Constraints: * 0 <= n <= 5 * 106 */ -public class CountPrimes { +class CountPrimes { public static void main(String[] args) { CountPrimes counter = new CountPrimes(); System.out.println("No of prime are:" - + counter.countPrimes(100)); + + counter.countPrimes(100)); } public int countPrimes(int n) { @@ -34,8 +33,8 @@ public int countPrimes(int n) { for (int i = 2; i < n; i++) { if (!notPrime[i]) { countPrime++; - for (int j = 2; i*j < n; j++) { - notPrime[i*j] = true; + for (int j = 2; i * j < n; j++) { + notPrime[i * j] = true; } } } diff --git a/src/in/knowledgegate/dsa/math/ExcelSheetColumnNumber.java b/4 Math/ExcelSheetColumnNumber.java similarity index 78% rename from src/in/knowledgegate/dsa/math/ExcelSheetColumnNumber.java rename to 4 Math/ExcelSheetColumnNumber.java index 53c67ef..468883e 100644 --- a/src/in/knowledgegate/dsa/math/ExcelSheetColumnNumber.java +++ b/4 Math/ExcelSheetColumnNumber.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.math; /** * Given a string columnTitle that represents the @@ -33,13 +32,12 @@ * columnTitle consists only of uppercase English letters. * columnTitle is in the range ["A", "FXSHRXW"]. */ -public class ExcelSheetColumnNumber { +class ExcelSheetColumnNumber { public static void main(String[] args) { - ExcelSheetColumnNumber baseConversion = - new ExcelSheetColumnNumber(); + ExcelSheetColumnNumber baseConversion = new ExcelSheetColumnNumber(); System.out.println("Output is:" + - baseConversion.titleToNumber("AB")); + baseConversion.titleToNumber("AB")); } public int titleToNumber(String columnTitle) { @@ -47,7 +45,7 @@ public int titleToNumber(String columnTitle) { for (int i = columnTitle.length() - 1; i >= 0; i--, pow++) { char c = columnTitle.charAt(i); int val = c - 'A' + 1; - result += val * (int)Math.pow(26, pow); + result += val * (int) Math.pow(26, pow); } return result; } diff --git a/src/in/knowledgegate/dsa/math/PalindromeNumber.java b/4 Math/PalindromeNumber.java similarity index 90% rename from src/in/knowledgegate/dsa/math/PalindromeNumber.java rename to 4 Math/PalindromeNumber.java index 623c82f..a3688d2 100644 --- a/src/in/knowledgegate/dsa/math/PalindromeNumber.java +++ b/4 Math/PalindromeNumber.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.math; /** * Given an integer x, return true if x is @@ -34,9 +33,10 @@ * Constraints: * -231 <= x <= 231 - 1 */ -public class PalindromeNumber { +class PalindromeNumber { public boolean isPalindrome(int x) { - if (x < 0) return false; + if (x < 0) + return false; int rev = 0; int temp = x; while (temp > 0) { diff --git a/src/in/knowledgegate/dsa/math/PlusOne.java b/4 Math/PlusOne.java similarity index 91% rename from src/in/knowledgegate/dsa/math/PlusOne.java rename to 4 Math/PlusOne.java index f43a4ff..dac75a2 100644 --- a/src/in/knowledgegate/dsa/math/PlusOne.java +++ b/4 Math/PlusOne.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.math; /** * You are given a large integer represented as an @@ -38,11 +37,10 @@ * 0 <= digits[i] <= 9 * digits does not contain any leading 0's. */ -public class PlusOne { +class PlusOne { public static void main(String[] args) { PlusOne plusOne = new PlusOne(); - int[] res = plusOne.plusOne(new int[]{9,9,9 - ,9}); + int[] res = plusOne.plusOne(new int[] { 9, 9, 9, 9 }); for (int item : res) { System.out.print(" " + item); } @@ -61,7 +59,7 @@ public int[] plusOne(int[] digits) { int[] res = new int[digits.length + 1]; res[0] = 1; for (int i = 0; i < digits.length; i++) { - res[i+1] = digits[i]; + res[i + 1] = digits[i]; } return res; } diff --git a/src/in/knowledgegate/dsa/math/RomanToInteger.java b/4 Math/RomanToInteger.java similarity index 90% rename from src/in/knowledgegate/dsa/math/RomanToInteger.java rename to 4 Math/RomanToInteger.java index 9b76a01..f3c2636 100644 --- a/src/in/knowledgegate/dsa/math/RomanToInteger.java +++ b/4 Math/RomanToInteger.java @@ -1,17 +1,16 @@ -package in.knowledgegate.dsa.math; /** * Roman numerals are represented by seven different * symbols: I, V, X, L, C, D and M. * - * Symbol Value - * I 1 - * V 5 - * X 10 - * L 50 - * C 100 - * D 500 - * M 1000 + * Symbol Value + * I 1 + * V 5 + * X 10 + * L 50 + * C 100 + * D 500 + * M 1000 * For example, 2 is written as II in Roman numeral, * just two one's added together. 12 is written as * XII, which is simply X + II. The number 27 is @@ -55,10 +54,9 @@ * It is guaranteed that s is a valid roman * numeral in the range [1, 3999]. */ -public class RomanToInteger { +class RomanToInteger { public static void main(String[] args) { - RomanToInteger converter = - new RomanToInteger(); + RomanToInteger converter = new RomanToInteger(); System.out.println("III:" + converter.romanToInt("III")); System.out.println("LVIII:" + converter.romanToInt("LVIII")); System.out.println("MCMXCIV:" + converter.romanToInt("MCMXCIV")); diff --git a/src/in/knowledgegate/dsa/math/RotateArray.java b/4 Math/RotateArray.java similarity index 88% rename from src/in/knowledgegate/dsa/math/RotateArray.java rename to 4 Math/RotateArray.java index c4d4626..cada5fd 100644 --- a/src/in/knowledgegate/dsa/math/RotateArray.java +++ b/4 Math/RotateArray.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.math; import java.util.Arrays; @@ -27,14 +26,15 @@ * -231 <= nums[i] <= 231 - 1 * 0 <= k <= 105 */ -public class RotateArray { +class RotateArray { public static void main(String[] args) { RotateArray rotateArray = new RotateArray(); - int[] nums = new int[]{1,2,3,4,5,6,7}; + int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7 }; System.out.print("Rotating " + Arrays.toString(nums)); rotateArray.rotate(nums, 10); System.out.println(" : " + Arrays.toString(nums)); } + public void rotate(int[] nums, int k) { // Another way: int[] copyArr = nums.clone(); int[] copyArr = new int[nums.length]; @@ -43,14 +43,7 @@ public void rotate(int[] nums, int k) { } for (int i = 0; i < nums.length; i++) { - nums[(i+k)%nums.length] = copyArr[i]; + nums[(i + k) % nums.length] = copyArr[i]; } } } - - - - - - - diff --git a/src/in/knowledgegate/dsa/sorting/algos/BubbleSort.java b/5 Sorting/algos/BubbleSort.java similarity index 76% rename from src/in/knowledgegate/dsa/sorting/algos/BubbleSort.java rename to 5 Sorting/algos/BubbleSort.java index 74fdd5c..925c45c 100644 --- a/src/in/knowledgegate/dsa/sorting/algos/BubbleSort.java +++ b/5 Sorting/algos/BubbleSort.java @@ -1,6 +1,5 @@ -package in.knowledgegate.dsa.sorting.algos; -public class BubbleSort implements SortingAlgo { +class BubbleSort implements SortingAlgo { private void swap(int[] nums, int i, int j) { int temp = nums[i]; @@ -12,8 +11,8 @@ private void swap(int[] nums, int i, int j) { public void sort(int[] nums) { for (int i = 0; i < nums.length - 1; i++) { for (int j = 0; j < nums.length - 1 - i; j++) { - if (nums[j] > nums[j+1]) { - swap(nums, j, j+1); + if (nums[j] > nums[j + 1]) { + swap(nums, j, j + 1); } } // printArray(nums); @@ -21,7 +20,7 @@ public void sort(int[] nums) { } public static void main(String[] args) { - int[] nums = {8, 6, 14, 77, 1, 13}; + int[] nums = { 8, 6, 14, 77, 1, 13 }; SortingAlgo sortingAlgo = new BubbleSort(); sortingAlgo.sort(nums); diff --git a/src/in/knowledgegate/dsa/sorting/algos/InsertionSort.java b/5 Sorting/algos/InsertionSort.java similarity index 64% rename from src/in/knowledgegate/dsa/sorting/algos/InsertionSort.java rename to 5 Sorting/algos/InsertionSort.java index 8cd6597..360ace8 100644 --- a/src/in/knowledgegate/dsa/sorting/algos/InsertionSort.java +++ b/5 Sorting/algos/InsertionSort.java @@ -1,19 +1,18 @@ -package in.knowledgegate.dsa.sorting.algos; /** * Implement a sorting algo for Insertion Sort */ -public class InsertionSort implements SortingAlgo { +class InsertionSort implements SortingAlgo { @Override public void sort(int[] nums) { for (int i = 1; i < nums.length; i++) { int key = nums[i]; int j = i - 1; while (j >= 0 && nums[j] > key) { - nums[j+1] = nums[j]; + nums[j + 1] = nums[j]; j--; } - nums[j+1] = key; + nums[j + 1] = key; } } } diff --git a/src/in/knowledgegate/dsa/sorting/algos/MergeSort.java b/5 Sorting/algos/MergeSort.java similarity index 88% rename from src/in/knowledgegate/dsa/sorting/algos/MergeSort.java rename to 5 Sorting/algos/MergeSort.java index dd29ec0..fd0fe51 100644 --- a/src/in/knowledgegate/dsa/sorting/algos/MergeSort.java +++ b/5 Sorting/algos/MergeSort.java @@ -1,6 +1,5 @@ -package in.knowledgegate.dsa.sorting.algos; -public class MergeSort implements SortingAlgo { +class MergeSort implements SortingAlgo { private void mergeSort(int[] nums) { int n = nums.length; @@ -26,7 +25,7 @@ private void mergeSort(int[] nums) { } private void merge(int[] result, int[] first, - int[] second) { + int[] second) { int i = 0, j = 0, k = 0; while (i < first.length && j < second.length) { if (first[i] <= second[j]) { @@ -49,7 +48,7 @@ public void sort(int[] nums) { } public static void main(String[] args) { - int[] arr = {8, 6, 14, 77, 1, 13}; + int[] arr = { 8, 6, 14, 77, 1, 13 }; int n = arr.length; SortingAlgo sort = new MergeSort(); diff --git a/src/in/knowledgegate/dsa/sorting/algos/QuickSort.java b/5 Sorting/algos/QuickSort.java similarity index 83% rename from src/in/knowledgegate/dsa/sorting/algos/QuickSort.java rename to 5 Sorting/algos/QuickSort.java index 6dc761f..d68902d 100644 --- a/src/in/knowledgegate/dsa/sorting/algos/QuickSort.java +++ b/5 Sorting/algos/QuickSort.java @@ -1,6 +1,5 @@ -package in.knowledgegate.dsa.sorting.algos; -public class QuickSort implements SortingAlgo { +class QuickSort implements SortingAlgo { private void swap(int[] arr, int i, int j) { int temp = arr[i]; @@ -9,7 +8,7 @@ private void swap(int[] arr, int i, int j) { } private int partition(int[] nums, int low, - int high) { + int high) { int pivot = nums[high]; int i = low; @@ -23,7 +22,7 @@ private int partition(int[] nums, int low, } private void quickSort(int[] nums, int low, - int high) { + int high) { if (low < high) { int partitionIndex = partition(nums, low, high); @@ -38,7 +37,7 @@ public void sort(int[] nums) { } public static void main(String[] args) { - int[] arr = {8, 6, 14, 77, 1, 13}; + int[] arr = { 8, 6, 14, 77, 1, 13 }; int n = arr.length; SortingAlgo sort = new QuickSort(); diff --git a/src/in/knowledgegate/dsa/sorting/algos/SelectionSort.java b/5 Sorting/algos/SelectionSort.java similarity index 84% rename from src/in/knowledgegate/dsa/sorting/algos/SelectionSort.java rename to 5 Sorting/algos/SelectionSort.java index c1f2099..6944483 100644 --- a/src/in/knowledgegate/dsa/sorting/algos/SelectionSort.java +++ b/5 Sorting/algos/SelectionSort.java @@ -1,6 +1,5 @@ -package in.knowledgegate.dsa.sorting.algos; -public class SelectionSort implements SortingAlgo { +class SelectionSort implements SortingAlgo { private void swap(int[] nums, int i, int j) { int temp = nums[i]; @@ -23,7 +22,7 @@ public void sort(int[] nums) { } public static void main(String[] args) { - int[] nums = {8, 6, 14, 77, 1, 13}; + int[] nums = { 8, 6, 14, 77, 1, 13 }; SortingAlgo sortingAlgo = new SelectionSort(); sortingAlgo.sort(nums); diff --git a/src/in/knowledgegate/dsa/sorting/algos/SortingAlgo.java b/5 Sorting/algos/SortingAlgo.java similarity index 57% rename from src/in/knowledgegate/dsa/sorting/algos/SortingAlgo.java rename to 5 Sorting/algos/SortingAlgo.java index 561e42e..4651408 100644 --- a/src/in/knowledgegate/dsa/sorting/algos/SortingAlgo.java +++ b/5 Sorting/algos/SortingAlgo.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.sorting.algos; public interface SortingAlgo { void sort(int[] nums); diff --git a/src/in/knowledgegate/dsa/sorting/problems/CountElements.java b/5 Sorting/problems/CountElements.java similarity index 90% rename from src/in/knowledgegate/dsa/sorting/problems/CountElements.java rename to 5 Sorting/problems/CountElements.java index 1af9b2e..27131ed 100644 --- a/src/in/knowledgegate/dsa/sorting/problems/CountElements.java +++ b/5 Sorting/problems/CountElements.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.sorting.problems; import java.util.Arrays; @@ -17,7 +16,7 @@ * In total there are 2 elements having both a strictly * smaller and a strictly greater element appear in nums. * - * Example 2: + * Example 2: * Input: nums = [-3,3,3,90] * Output: 2 * Explanation: The element 3 has the element -3 @@ -33,11 +32,11 @@ * 1 <= nums.length <= 100 * -105 <= nums[i] <= 105 */ -public class CountElements { +class CountElements { public static void main(String[] args) { CountElements elements = new CountElements(); - int[] nums = new int[]{1,1,1,1,1,1}; + int[] nums = new int[] { 1, 1, 1, 1, 1, 1 }; System.out.println("output is:" + elements.countElements(nums)); } @@ -51,7 +50,7 @@ public int countElements(int[] nums) { } } for (int i = nums.length - 1; i > 0; i--) { - if (nums[i-1] < nums[i]) { + if (nums[i - 1] < nums[i]) { end = i - 1; break; } diff --git a/src/in/knowledgegate/dsa/sorting/problems/KthLargestElement.java b/5 Sorting/problems/KthLargestElement.java similarity index 77% rename from src/in/knowledgegate/dsa/sorting/problems/KthLargestElement.java rename to 5 Sorting/problems/KthLargestElement.java index 285eaf5..04b4a00 100644 --- a/src/in/knowledgegate/dsa/sorting/problems/KthLargestElement.java +++ b/5 Sorting/problems/KthLargestElement.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.sorting.problems; /** * Given an integer array nums and an integer k, @@ -19,21 +18,20 @@ * 1 <= k <= nums.length <= 104 * -104 <= nums[i] <= 104 */ -public class KthLargestElement { +class KthLargestElement { public static void main(String[] args) { - KthLargestElement kthLargest = - new KthLargestElement(); - int[] nums = new int[]{3,2,3,1,2,4,5,5,6}; + KthLargestElement kthLargest = new KthLargestElement(); + int[] nums = new int[] { 3, 2, 3, 1, 2, 4, 5, 5, 6 }; System.out.println("Kth largest is:" + kthLargest.findKthLargest(nums, 4)); } public int findKthLargest(int[] nums, int k) { - return quickSelect(nums, 0, nums.length-1, k); + return quickSelect(nums, 0, nums.length - 1, k); } private int quickSelect(int[] nums, int beg, - int end, int k) { + int end, int k) { int pivot = beg; for (int i = pivot; i < end; i++) { if (nums[i] <= nums[end]) { @@ -43,7 +41,8 @@ private int quickSelect(int[] nums, int beg, } swap(nums, pivot, end); int count = end - pivot + 1; - if (count == k) return nums[pivot]; + if (count == k) + return nums[pivot]; if (count > k) { return quickSelect(nums, pivot + 1, end, k); } else { diff --git a/src/in/knowledgegate/dsa/sorting/problems/MergeSortedArray.java b/5 Sorting/problems/MergeSortedArray.java similarity index 88% rename from src/in/knowledgegate/dsa/sorting/problems/MergeSortedArray.java rename to 5 Sorting/problems/MergeSortedArray.java index 5e44f9c..3b99839 100644 --- a/src/in/knowledgegate/dsa/sorting/problems/MergeSortedArray.java +++ b/5 Sorting/problems/MergeSortedArray.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.sorting.problems; import java.util.Arrays; @@ -47,19 +46,18 @@ * n <= 200 1 <= m + n <= 200 -109 <= nums1[i], * nums2[j] <= 109 */ -public class MergeSortedArray { +class MergeSortedArray { public static void main(String[] args) { - MergeSortedArray merge = - new MergeSortedArray(); - int[] nums1 = new int[]{1,2,3,0,0,0,0}; - int[] nums2 = new int[]{0,2,5,6}; + MergeSortedArray merge = new MergeSortedArray(); + int[] nums1 = new int[] { 1, 2, 3, 0, 0, 0, 0 }; + int[] nums2 = new int[] { 0, 2, 5, 6 }; merge.merge(nums1, 3, nums2, 4); System.out.println("Output is:" + Arrays.toString(nums1)); } public void merge(int[] nums1, int m, - int[] nums2, int n) { + int[] nums2, int n) { int i = m - 1; int j = n - 1; int k = m + n - 1; diff --git a/src/in/knowledgegate/dsa/sorting/problems/SquaresOfSortedArray.java b/5 Sorting/problems/SquaresOfSortedArray.java similarity index 92% rename from src/in/knowledgegate/dsa/sorting/problems/SquaresOfSortedArray.java rename to 5 Sorting/problems/SquaresOfSortedArray.java index fa55627..ff66f8d 100644 --- a/src/in/knowledgegate/dsa/sorting/problems/SquaresOfSortedArray.java +++ b/5 Sorting/problems/SquaresOfSortedArray.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.sorting.problems; /** * Given an integer array nums sorted in @@ -23,7 +22,7 @@ * -104 <= nums[i] <= 104 * nums is sorted in non-decreasing order. */ -public class SquaresOfSortedArray { +class SquaresOfSortedArray { public int[] sortedSquares(int[] nums) { int beg = 0, end = nums.length - 1; int[] result = new int[nums.length]; diff --git a/src/in/knowledgegate/dsa/sorting/problems/ThreeSum.java b/5 Sorting/problems/ThreeSum.java similarity index 91% rename from src/in/knowledgegate/dsa/sorting/problems/ThreeSum.java rename to 5 Sorting/problems/ThreeSum.java index 2a4c82b..45bd344 100644 --- a/src/in/knowledgegate/dsa/sorting/problems/ThreeSum.java +++ b/5 Sorting/problems/ThreeSum.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.sorting.problems; import java.util.*; @@ -26,10 +25,10 @@ * 0 <= nums.length <= 3000 * -105 <= nums[i] <= 105 */ -public class ThreeSum { +class ThreeSum { public static void main(String[] args) { ThreeSum threeSum = new ThreeSum(); - int[] nums = new int[]{-1,0,1,2,-1,-4}; + int[] nums = new int[] { -1, 0, 1, 2, -1, -4 }; System.out.println("Possible Triplets:" + threeSum.threeSum(nums)); } diff --git a/src/in/knowledgegate/dsa/binarysearch/algos/BinarySearch.java b/6 Binary Search/algos/BinarySearch.java similarity index 86% rename from src/in/knowledgegate/dsa/binarysearch/algos/BinarySearch.java rename to 6 Binary Search/algos/BinarySearch.java index da813d3..bad1216 100644 --- a/src/in/knowledgegate/dsa/binarysearch/algos/BinarySearch.java +++ b/6 Binary Search/algos/BinarySearch.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarysearch.algos; /** * implement Binary Search on sorted array @@ -7,7 +6,7 @@ * Number to find: 7 * Number to find: 1 */ -public class BinarySearch { +class BinarySearch { public int search(int[] sortedArr, int target) { int beg = 0, end = sortedArr.length - 1; while (beg <= end) { diff --git a/src/in/knowledgegate/dsa/binarysearch/problems/ArrangingCoins.java b/6 Binary Search/problems/ArrangingCoins.java similarity index 78% rename from src/in/knowledgegate/dsa/binarysearch/problems/ArrangingCoins.java rename to 6 Binary Search/problems/ArrangingCoins.java index dcf92d7..4c1f284 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/ArrangingCoins.java +++ b/6 Binary Search/problems/ArrangingCoins.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarysearch.problems; /** * You have n coins and you want to build a staircase @@ -24,21 +23,21 @@ * Constraints: * 1 <= n <= 231 - 1 */ -public class ArrangingCoins { +class ArrangingCoins { public static void main(String[] args) { - ArrangingCoins arrange = - new ArrangingCoins(); + ArrangingCoins arrange = new ArrangingCoins(); System.out.println("No of stairs:" - + arrange.arrangeCoins(5)); + + arrange.arrangeCoins(5)); } private int arrangeCoins(int n) { int begin = 0; int end = n; while (begin <= end) { - int mid = (begin + end)/2; + int mid = (begin + end) / 2; int coinsUsed = (mid * (mid + 1)) / 2; - if (coinsUsed == n) return mid; + if (coinsUsed == n) + return mid; if (coinsUsed < n) { begin = mid + 1; } else { diff --git a/src/in/knowledgegate/dsa/binarysearch/problems/FirstBadVersion.java b/6 Binary Search/problems/FirstBadVersion.java similarity index 83% rename from src/in/knowledgegate/dsa/binarysearch/problems/FirstBadVersion.java rename to 6 Binary Search/problems/FirstBadVersion.java index d057418..5a77365 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/FirstBadVersion.java +++ b/6 Binary Search/problems/FirstBadVersion.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarysearch.problems; /** * You are a product manager and currently leading @@ -34,18 +33,17 @@ * Constraints: * 1 <= bad <= n <= 231 - 1 */ -public class FirstBadVersion { +class FirstBadVersion { static int badVersion; static int TOTAL_VERSION = 500; public static void main(String[] args) { - FirstBadVersion versionChecker = - new FirstBadVersion(); + FirstBadVersion versionChecker = new FirstBadVersion(); badVersion = 412; System.out.println("\nbad version is:" - + versionChecker.firstBadVersionLinearSearch(TOTAL_VERSION)); + + versionChecker.firstBadVersionLinearSearch(TOTAL_VERSION)); System.out.println("\nbad version is:" - + versionChecker.firstBadVersion(TOTAL_VERSION)); + + versionChecker.firstBadVersion(TOTAL_VERSION)); } public int firstBadVersion(int n) { @@ -63,7 +61,8 @@ public int firstBadVersion(int n) { public int firstBadVersionLinearSearch(int n) { for (int i = 1; i < n; i++) { - if (isBadVersion(i)) return i; + if (isBadVersion(i)) + return i; } return -1; } diff --git a/src/in/knowledgegate/dsa/binarysearch/problems/GuessNumberHigherOrLower.java b/6 Binary Search/problems/GuessNumberHigherOrLower.java similarity index 77% rename from src/in/knowledgegate/dsa/binarysearch/problems/GuessNumberHigherOrLower.java rename to 6 Binary Search/problems/GuessNumberHigherOrLower.java index 2f0a5c2..f02138b 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/GuessNumberHigherOrLower.java +++ b/6 Binary Search/problems/GuessNumberHigherOrLower.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarysearch.problems; /** * We are playing the Guess Game. The game is as follows: @@ -35,12 +34,11 @@ * 1 <= n <= 231 - 1 * 1 <= pick <= n */ -public class GuessNumberHigherOrLower { +class GuessNumberHigherOrLower { static int numberToGuess; public static void main(String[] args) { - GuessNumberHigherOrLower guesser = - new GuessNumberHigherOrLower(); + GuessNumberHigherOrLower guesser = new GuessNumberHigherOrLower(); numberToGuess = 99; System.out.println("\nnumber is:" + guesser.guessNumberNormalSearch(100)); System.out.println(); @@ -52,24 +50,30 @@ public int guessNumber(int n) { while (beg <= end) { int mid = (beg + end) / 2; int res = guess(mid); - if (res == 0) return mid; - if (res == -1) end = mid -1; - else beg = mid + 1; + if (res == 0) + return mid; + if (res == -1) + end = mid - 1; + else + beg = mid + 1; } return -1; } public int guessNumberNormalSearch(int n) { for (int i = 1; i <= n; i++) { - if (guess(i) == 0) return i; + if (guess(i) == 0) + return i; } return -1; } private int guess(int num) { System.out.print("."); - if (num == numberToGuess) return 0; - else if (num < numberToGuess) return 1; + if (num == numberToGuess) + return 0; + else if (num < numberToGuess) + return 1; return -1; } } diff --git a/src/in/knowledgegate/dsa/binarysearch/problems/SearchIn2DMatrix.java b/6 Binary Search/problems/SearchIn2DMatrix.java similarity index 78% rename from src/in/knowledgegate/dsa/binarysearch/problems/SearchIn2DMatrix.java rename to 6 Binary Search/problems/SearchIn2DMatrix.java index d1e6521..1855494 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/SearchIn2DMatrix.java +++ b/6 Binary Search/problems/SearchIn2DMatrix.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarysearch.problems; /** * Write an efficient algorithm that searches for @@ -25,18 +24,18 @@ * 1 <= m, n <= 100 * -104 <= matrix[i][j], target <= 104 */ -public class SearchIn2DMatrix { +class SearchIn2DMatrix { public static void main(String[] args) { - SearchIn2DMatrix search = - new SearchIn2DMatrix(); - int[][] nums = new int[][]{{1,3,5,7}, - {10,11,16,20},{23,30,34,60}}; + SearchIn2DMatrix search = new SearchIn2DMatrix(); + int[][] nums = new int[][] { { 1, 3, 5, 7 }, + { 10, 11, 16, 20 }, { 23, 30, 34, 60 } }; System.out.println("Element status: " - + search.searchMatrix(nums, 24)); + + search.searchMatrix(nums, 24)); } public boolean searchMatrix(int[][] matrix, int target) { - if (matrix == null || matrix.length == 0) return false; + if (matrix == null || matrix.length == 0) + return false; int m = matrix.length; int n = matrix[0].length; int tot = m * n; diff --git a/src/in/knowledgegate/dsa/binarysearch/problems/SearchInRotatedSortedArray.java b/6 Binary Search/problems/SearchInRotatedSortedArray.java similarity index 81% rename from src/in/knowledgegate/dsa/binarysearch/problems/SearchInRotatedSortedArray.java rename to 6 Binary Search/problems/SearchInRotatedSortedArray.java index 3219113..277aa2f 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/SearchInRotatedSortedArray.java +++ b/6 Binary Search/problems/SearchInRotatedSortedArray.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarysearch.problems; /** * There is an integer array nums sorted in ascending @@ -21,7 +20,7 @@ * complexity. * * - * Example 1: 0,1,2,3,4,5,6 + * Example 1: 0,1,2,3,4,5,6 * Input: nums = [4,5,6,7,0,1,2], target = 0 * Output: 4 * @@ -41,13 +40,12 @@ * nums is an ascending array that is possibly rotated. * -104 <= target <= 104 */ -public class SearchInRotatedSortedArray { +class SearchInRotatedSortedArray { public static void main(String[] args) { - SearchInRotatedSortedArray search = - new SearchInRotatedSortedArray(); - int[] nums = new int[]{4,5,6,7,0,1,2}; + SearchInRotatedSortedArray search = new SearchInRotatedSortedArray(); + int[] nums = new int[] { 4, 5, 6, 7, 0, 1, 2 }; System.out.println("Found at:" - + search.search(nums, 3)); + + search.search(nums, 3)); } int search(int[] nums, int target) { @@ -63,10 +61,9 @@ int search(int[] nums, int target) { beg = 0; end = nums.length - 1; - while(beg <= end) { + while (beg <= end) { int mid = (beg + end) / 2; - int realMid = - (mid + shift) % nums.length; + int realMid = (mid + shift) % nums.length; if (nums[realMid] == target) return realMid; else if (nums[realMid] < target) diff --git a/src/in/knowledgegate/dsa/binarysearch/problems/SearchInsertPosition.java b/6 Binary Search/problems/SearchInsertPosition.java similarity index 92% rename from src/in/knowledgegate/dsa/binarysearch/problems/SearchInsertPosition.java rename to 6 Binary Search/problems/SearchInsertPosition.java index 29f432b..178e440 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/SearchInsertPosition.java +++ b/6 Binary Search/problems/SearchInsertPosition.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarysearch.problems; /** * Given a sorted array of distinct integers and a target value, return the @@ -17,7 +16,7 @@ * Constraints: 1 <= nums.length <= 104 -104 <= nums[i] <= 104 nums contains * distinct values sorted in ascending order. -104 <= target <= 104 */ -public class SearchInsertPosition { +class SearchInsertPosition { public int searchInsert(int[] nums, int target) { int beg = 0, end = nums.length - 1; while (beg <= end) { diff --git a/src/in/knowledgegate/dsa/binarysearch/problems/SingleElementInASortedArray.java b/6 Binary Search/problems/SingleElementInASortedArray.java similarity index 66% rename from src/in/knowledgegate/dsa/binarysearch/problems/SingleElementInASortedArray.java rename to 6 Binary Search/problems/SingleElementInASortedArray.java index d6e18c8..82323a9 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/SingleElementInASortedArray.java +++ b/6 Binary Search/problems/SingleElementInASortedArray.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarysearch.problems; /** * You are given a sorted array consisting of only @@ -12,7 +11,7 @@ * Input: nums = [1,1,2,3,3,4,4,8,8] * Output: 2 * - * Example 2: 0,1,2,3,4 ,5 ,6 + * Example 2: 0,1,2,3,4 ,5 ,6 * Input: nums = [3,3,7,7,10,11,11] * Output: 10 * @@ -20,21 +19,20 @@ * 1 <= nums.length <= 105 * 0 <= nums[i] <= 105 */ -public class SingleElementInASortedArray { +class SingleElementInASortedArray { public static void main(String[] args) { - SingleElementInASortedArray finder = - new SingleElementInASortedArray(); - int[] nums = new int[]{3,3,7,7,10,11,11}; + SingleElementInASortedArray finder = new SingleElementInASortedArray(); + int[] nums = new int[] { 3, 3, 7, 7, 10, 11, 11 }; System.out.println("Duplicate is:" - + finder.singleNonDuplicate(nums)); + + finder.singleNonDuplicate(nums)); } public int singleNonDuplicate(int[] nums) { int left = 0, right = nums.length - 1; while (left < right) { int mid = left + (right - left) / 2; - if ((mid % 2 == 0 && nums[mid] == nums[mid+1]) || - (mid % 2 == 1 && nums[mid] == nums[mid -1])) { + if ((mid % 2 == 0 && nums[mid] == nums[mid + 1]) || + (mid % 2 == 1 && nums[mid] == nums[mid - 1])) { left = mid + 1; } else { right = mid - 1; @@ -43,6 +41,3 @@ public int singleNonDuplicate(int[] nums) { return nums[left]; } } - - - diff --git a/src/in/knowledgegate/dsa/binarysearch/problems/SquareRoot.java b/6 Binary Search/problems/SquareRoot.java similarity index 88% rename from src/in/knowledgegate/dsa/binarysearch/problems/SquareRoot.java rename to 6 Binary Search/problems/SquareRoot.java index 8843182..c098759 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/SquareRoot.java +++ b/6 Binary Search/problems/SquareRoot.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarysearch.problems; /** * Given a non-negative integer x, compute and @@ -27,12 +26,12 @@ * Constraints: * 0 <= x <= 231 - 1 */ -public class SquareRoot { +class SquareRoot { public int mySqrt(int x) { int beg = 0, end = x; while (beg <= end) { int mid = beg + (end - beg) / 2; - long square = ((long)mid) * mid; + long square = ((long) mid) * mid; if (square == x) { return mid; } else if (square > x) { diff --git a/src/in/knowledgegate/dsa/bitmanipulation/ConvertNumberToHexadecimal.java b/7 Bit Manipulation/ConvertNumberToHexadecimal.java similarity index 70% rename from src/in/knowledgegate/dsa/bitmanipulation/ConvertNumberToHexadecimal.java rename to 7 Bit Manipulation/ConvertNumberToHexadecimal.java index 0e8cc62..391e032 100644 --- a/src/in/knowledgegate/dsa/bitmanipulation/ConvertNumberToHexadecimal.java +++ b/7 Bit Manipulation/ConvertNumberToHexadecimal.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.bitmanipulation; /** * Given an integer num, return a string @@ -26,19 +25,18 @@ * Constraints: * -231 <= num <= 231 - 1 */ -public class ConvertNumberToHexadecimal { +class ConvertNumberToHexadecimal { public static void main(String[] args) { - ConvertNumberToHexadecimal converter = - new ConvertNumberToHexadecimal(); + ConvertNumberToHexadecimal converter = new ConvertNumberToHexadecimal(); System.out.println("Hex num is: " - + converter.toHex(26)); + + converter.toHex(26)); } public String toHex(int num) { - char[] mapping = new char[]{'0', '1', '2' - , '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f'}; - if (num == 0) return "0"; + char[] mapping = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'a', 'b', 'c', 'd', 'e', 'f' }; + if (num == 0) + return "0"; StringBuilder result = new StringBuilder(); while (num > 0) { int endBits = num & 15; diff --git a/src/in/knowledgegate/dsa/bitmanipulation/FindTheDifference.java b/7 Bit Manipulation/FindTheDifference.java similarity index 85% rename from src/in/knowledgegate/dsa/bitmanipulation/FindTheDifference.java rename to 7 Bit Manipulation/FindTheDifference.java index 2abac86..95aff04 100644 --- a/src/in/knowledgegate/dsa/bitmanipulation/FindTheDifference.java +++ b/7 Bit Manipulation/FindTheDifference.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.bitmanipulation; /** * You are given two strings s and t. @@ -22,10 +21,9 @@ * t.length == s.length + 1 * s and t consist of lowercase English letters. */ -public class FindTheDifference { +class FindTheDifference { public static void main(String[] args) { - FindTheDifference diff = - new FindTheDifference(); + FindTheDifference diff = new FindTheDifference(); System.out.println("Output is:" + diff.findTheDifference("abcde", "abcdee")); } @@ -38,6 +36,3 @@ public char findTheDifference(String s, String t) { return c; } } - - - diff --git a/src/in/knowledgegate/dsa/bitmanipulation/MissingNumber.java b/7 Bit Manipulation/MissingNumber.java similarity index 88% rename from src/in/knowledgegate/dsa/bitmanipulation/MissingNumber.java rename to 7 Bit Manipulation/MissingNumber.java index bd106c1..f21479f 100644 --- a/src/in/knowledgegate/dsa/bitmanipulation/MissingNumber.java +++ b/7 Bit Manipulation/MissingNumber.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.bitmanipulation; /** * Given an array nums containing n distinct numbers @@ -37,13 +36,13 @@ * 0 <= nums[i] <= n * All the numbers of nums are unique. */ -public class MissingNumber { +class MissingNumber { public int missingNumber(int[] nums) { int num1 = 0, num2 = nums.length; for (int i = 0; i < nums.length; i++) { - num1 = num1^nums[i]; - num2 = num2^i; + num1 = num1 ^ nums[i]; + num2 = num2 ^ i; } - return num1^num2; + return num1 ^ num2; } } diff --git a/src/in/knowledgegate/dsa/bitmanipulation/SingleNumber.java b/7 Bit Manipulation/SingleNumber.java similarity index 90% rename from src/in/knowledgegate/dsa/bitmanipulation/SingleNumber.java rename to 7 Bit Manipulation/SingleNumber.java index 34135a2..401f23f 100644 --- a/src/in/knowledgegate/dsa/bitmanipulation/SingleNumber.java +++ b/7 Bit Manipulation/SingleNumber.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.bitmanipulation; /** * Given a non-empty array of integers nums, @@ -27,7 +26,7 @@ * Each element in the array appears twice except * for one element which appears only once. */ -public class SingleNumber { +class SingleNumber { public int singleNumber(int[] nums) { int num = 0; for (int i = 0; i < nums.length; i++) { diff --git a/src/in/knowledgegate/dsa/linkedlist/MergeTwoSortedList.java b/8 Linked List/MergeTwoSortedList.java similarity index 90% rename from src/in/knowledgegate/dsa/linkedlist/MergeTwoSortedList.java rename to 8 Linked List/MergeTwoSortedList.java index 703ffc4..8bc427b 100644 --- a/src/in/knowledgegate/dsa/linkedlist/MergeTwoSortedList.java +++ b/8 Linked List/MergeTwoSortedList.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.linkedlist; /** * You are given the heads of two sorted linked @@ -29,14 +28,14 @@ * Both list1 and list2 are sorted in * non-decreasing order. */ -public class MergeTwoSortedList { +class MergeTwoSortedList { private class ListNode { int val; ListNode next; } public ListNode mergeTwoLists(ListNode list1, - ListNode list2) { + ListNode list2) { ListNode temp = new ListNode(); ListNode dummy = temp; @@ -55,4 +54,3 @@ public ListNode mergeTwoLists(ListNode list1, return dummy.next; } } - diff --git a/src/in/knowledgegate/dsa/linkedlist/PalindromeLinkedList.java b/8 Linked List/PalindromeLinkedList.java similarity index 81% rename from src/in/knowledgegate/dsa/linkedlist/PalindromeLinkedList.java rename to 8 Linked List/PalindromeLinkedList.java index 5316eab..35beed3 100644 --- a/src/in/knowledgegate/dsa/linkedlist/PalindromeLinkedList.java +++ b/8 Linked List/PalindromeLinkedList.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.linkedlist; import in.knowledgegate.dsa.ListNode; @@ -20,16 +19,15 @@ * * Follow up: Could you do it in O(n) time and O(1) space? */ -public class PalindromeLinkedList { +class PalindromeLinkedList { public static void main(String[] args) { - PalindromeLinkedList checker = - new PalindromeLinkedList(); + PalindromeLinkedList checker = new PalindromeLinkedList(); ListNode fourth = new ListNode(1); ListNode third = new ListNode(2, fourth); ListNode second = new ListNode(3, third); ListNode first = new ListNode(1, second); System.out.println("Palindrome status: " - + checker.isPalindrome(first)); + + checker.isPalindrome(first)); } public boolean isPalindrome(ListNode head) { @@ -40,8 +38,9 @@ public boolean isPalindrome(ListNode head) { } ListNode reversed = reverse(slow); - while(head != null && reversed != null) { - if (head.val != reversed.val) return false; + while (head != null && reversed != null) { + if (head.val != reversed.val) + return false; head = head.next; reversed = reversed.next; } diff --git a/src/in/knowledgegate/dsa/linkedlist/PascalTriangle.java b/8 Linked List/PascalTriangle.java similarity index 93% rename from src/in/knowledgegate/dsa/linkedlist/PascalTriangle.java rename to 8 Linked List/PascalTriangle.java index 52ee418..d9bb9bb 100644 --- a/src/in/knowledgegate/dsa/linkedlist/PascalTriangle.java +++ b/8 Linked List/PascalTriangle.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.linkedlist; import java.util.ArrayList; import java.util.List; @@ -24,7 +23,7 @@ *

* Constraints: 1 <= numRows <= 30 */ -public class PascalTriangle { +class PascalTriangle { public List> generate(int numRows) { List> result = new ArrayList<>(); List prev = new ArrayList<>(); diff --git a/src/in/knowledgegate/dsa/twopointer/ContainerWithMostWater.java b/9 Two Pointers/ContainerWithMostWater.java similarity index 82% rename from src/in/knowledgegate/dsa/twopointer/ContainerWithMostWater.java rename to 9 Two Pointers/ContainerWithMostWater.java index bafd76b..7fa1fd9 100644 --- a/src/in/knowledgegate/dsa/twopointer/ContainerWithMostWater.java +++ b/9 Two Pointers/ContainerWithMostWater.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.twopointer; /** * You are given an integer array height of length n. @@ -32,11 +31,10 @@ * 2 <= n <= 105 * 0 <= height[i] <= 104 */ -public class ContainerWithMostWater { +class ContainerWithMostWater { public static void main(String[] args) { - ContainerWithMostWater water = - new ContainerWithMostWater(); - int[] height = new int[]{1,8,6,2,5,4,8,3,7}; + ContainerWithMostWater water = new ContainerWithMostWater(); + int[] height = new int[] { 1, 8, 6, 2, 5, 4, 8, 3, 7 }; System.out.println("Output is:" + water.maxArea(height)); } @@ -46,8 +44,7 @@ public int maxArea(int[] height) { while (left < right) { int minHeight = Math.min(height[left], height[right]); - int currArea = - minHeight * (right - left); + int currArea = minHeight * (right - left); maxArea = Math.max(maxArea, currArea); if (height[left] < height[right]) { diff --git a/src/in/knowledgegate/dsa/twopointer/MoveZeros.java b/9 Two Pointers/MoveZeros.java similarity index 84% rename from src/in/knowledgegate/dsa/twopointer/MoveZeros.java rename to 9 Two Pointers/MoveZeros.java index 9ff119d..241dc3c 100644 --- a/src/in/knowledgegate/dsa/twopointer/MoveZeros.java +++ b/9 Two Pointers/MoveZeros.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.twopointer; import java.util.Arrays; @@ -22,17 +21,17 @@ * 1 <= nums.length <= 104 * -231 <= nums[i] <= 231 - 1 */ -public class MoveZeros { +class MoveZeros { public static void main(String[] args) { MoveZeros zeros = new MoveZeros(); - int[] nums = new int[]{0,1,0,3,12}; + int[] nums = new int[] { 0, 1, 0, 3, 12 }; zeros.moveZeroes(nums); System.out.println("Output is:" + Arrays.toString(nums)); } public void moveZeroes(int[] nums) { int prev = 0; - for (int i = 0 ; i < nums.length; i++) { + for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) { nums[prev++] = nums[i]; nums[i] = 0; diff --git a/src/in/knowledgegate/dsa/twopointer/RemoveElement.java b/9 Two Pointers/RemoveElement.java similarity index 93% rename from src/in/knowledgegate/dsa/twopointer/RemoveElement.java rename to 9 Two Pointers/RemoveElement.java index 2212416..7d2290f 100644 --- a/src/in/knowledgegate/dsa/twopointer/RemoveElement.java +++ b/9 Two Pointers/RemoveElement.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.twopointer; /** * Given an integer array nums and an integer val, @@ -26,7 +25,7 @@ * with the first five elements of nums containing * 0, 0, 1, 3, and 4. */ -public class RemoveElement { +class RemoveElement { public int removeElement(int[] nums, int val) { int insertLoc = 0; for (int i = 0; i < nums.length; i++) { diff --git a/src/in/knowledgegate/dsa/ListNode.java b/ListNode.java similarity index 71% rename from src/in/knowledgegate/dsa/ListNode.java rename to ListNode.java index e571e72..416378b 100644 --- a/src/in/knowledgegate/dsa/ListNode.java +++ b/ListNode.java @@ -1,14 +1,16 @@ -package in.knowledgegate.dsa; -public class ListNode { +class ListNode { public int val; public ListNode next; - public ListNode() {} + public ListNode() { + } + public ListNode(int val) { this.val = val; } + public ListNode(int val, ListNode next) { this.val = val; this.next = next; diff --git a/src/in/knowledgegate/dsa/Main.java b/src/in/knowledgegate/dsa/Main.java deleted file mode 100644 index f5a3d49..0000000 --- a/src/in/knowledgegate/dsa/Main.java +++ /dev/null @@ -1,7 +0,0 @@ -package in.knowledgegate.dsa; - -public class Main { - public static void main(String[] args) { - System.out.println("Hello Friends, this is where we Kill DSA !!!!"); - } -} \ No newline at end of file diff --git a/src/in/knowledgegate/dsa/backtracking/NQueen.java b/src/in/knowledgegate/dsa/backtracking/NQueen.java index 599190b..1565225 100644 --- a/src/in/knowledgegate/dsa/backtracking/NQueen.java +++ b/src/in/knowledgegate/dsa/backtracking/NQueen.java @@ -1,4 +1,4 @@ -package in.knowledgegate.dsa.backtracking; + import java.util.Scanner; @@ -27,7 +27,7 @@ * Constraints: * 1 <= n <= 30 */ -public class NQueen { +class NQueen { private void printBoard(int[][] board) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { @@ -39,7 +39,7 @@ private void printBoard(int[][] board) { } private boolean isMoveSafe(int[][] board, - int row, int col) { + int row, int col) { for (int j = 0; j < col; j++) { if (board[row][j] == 1) { @@ -47,7 +47,7 @@ private boolean isMoveSafe(int[][] board, } } - for (int i = row, j = col; i >= 0 && j >=0; i--, j--) { + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { if (board[i][j] == 1) { return false; } @@ -71,10 +71,11 @@ private boolean nQueen(int[][] board, int col) { return true; } - for (int i = 0;i < board.length; i++) { + for (int i = 0; i < board.length; i++) { if (isMoveSafe(board, i, col)) { board[i][col] = 1; - if (nQueen(board, col + 1)) return true; + if (nQueen(board, col + 1)) + return true; board[i][col] = 0; } } @@ -93,10 +94,11 @@ private void nQueen(int size) { } public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); - NQueen nQueen = new NQueen(); - System.out.print("Enter size of board: "); - int size = scanner.nextInt(); - nQueen.nQueen(size); + try (Scanner scanner = new Scanner(System.in)) { + NQueen nQueen = new NQueen(); + System.out.print("Enter size of board: "); + int size = scanner.nextInt(); + nQueen.nQueen(size); + } } } diff --git a/src/in/knowledgegate/dsa/complexity/ArrayCopy.java b/src/in/knowledgegate/dsa/complexity/ArrayCopy.java index 665b1e5..20de58e 100644 --- a/src/in/knowledgegate/dsa/complexity/ArrayCopy.java +++ b/src/in/knowledgegate/dsa/complexity/ArrayCopy.java @@ -1,9 +1,9 @@ -package in.knowledgegate.dsa.complexity; -public class ArrayCopy { + +class ArrayCopy { public static void main(String[] args) { - int[] newCopy = copy(new int[]{1, 2, 3, 4, 5}); + int[] newCopy = copy(new int[] { 1, 2, 3, 4, 5 }); } private static int[] copy(int[] array) { @@ -13,4 +13,4 @@ private static int[] copy(int[] array) { } return newCopy; } -} +} \ No newline at end of file diff --git a/src/in/knowledgegate/dsa/dfs/Solitaire.java b/src/in/knowledgegate/dsa/dfs/Solitaire.java deleted file mode 100644 index 8944135..0000000 --- a/src/in/knowledgegate/dsa/dfs/Solitaire.java +++ /dev/null @@ -1,136 +0,0 @@ -package in.knowledgegate.dsa.dfs; - -/** - * While your players are waiting for a game, - * you've developed a solitaire game for the - * players to pass the time with. - * The player is given an NxM board of tiles from - * 0 to 9 like this: - * 4 4 4 4 - * 5 5 5 4 - * 2 5 7 5 - * The player selects one of these tiles, and that - * tile will disappear, along with any tiles with - * the same number that are connected with that tile - * (up, down, left, or right), and any tiles with the - * same number connected with those, and so on. For - * example, if the 4 in the upper left corner is - * selected, these five tiles disappear - * >4< >4< >4< >4< - * 5 5 5 >4< - * 2 5 7 5 - * If the 5 just below it is selected, these four - * tiles disappear. Note that tiles are not - * connected diagonally. - * 4 4 4 4 - * >5< >5< >5< 4 - * 2 >5< 7 5 - * Write a function that, given a grid of tiles - * and a selected row and column of a tile, - * returns how many tiles will disappear. - * grid1 = [[4, 4, 4, 4], - * [5, 5, 5, 4], - * [2, 5, 7, 5]] - * disappear(grid1, 0, 0) => 5 - * disappear(grid1, 1, 1) => 4 - * disappear(grid1, 1, 0) => 4 - * This is the grid from above. - * - * Additional Inputs - * grid2 = [[0, 3, 3, 3, 3, 3, 3], - * [0, 1, 1, 1, 1, 1, 3], - * [0, 2, 2, 0, 2, 1, 4], - * [0, 1, 2, 2, 2, 1, 3], - * [0, 1, 1, 1, 1, 1, 3], - * [0, 0, 0, 0, 0, 0, 0]] - * - * grid3 = [[0]] - * - * grid4 = [[1, 1, 1], - * [1, 1, 1], - * [1, 1, 1]] - * - * All Test Cases - * disappear(grid1, 0, 0) => 5 - * disappear(grid1, 1, 1) => 4 - * disappear(grid1, 1, 0) => 4 - * disappear(grid2, 0, 0) => 12 - * disappear(grid2, 3, 0) => 12 - * disappear(grid2, 1, 1) => 13 - * disappear(grid2, 2, 2) => 6 - * disappear(grid2, 0, 3) => 7 - * disappear(grid3, 0, 0) => 1 - * disappear(grid4, 0, 0) => 9 - * - * N - Width of the grid - * M - Height of the grid - * - * Clarifications - * - All values are between 0 and 9 - * - The grid will not be empty - * - The input board is immutable. If the - * candidate suggests modifying the board you - * should suggest they make a deep copy of the board - * instead. This does not constitute handholding. - * - The input row and column will always be on - * the board. - */ -public class Solitaire { - public int disappear(int[][] grid, int x, - int y) { - if (grid.length <= 0) return 0; - int[][] newGrid = - new int[grid.length][grid[0].length]; - for (int i = 0; i < grid.length; i++) { - for (int j = 0; j < grid[i].length; j++) { - newGrid[i][j] = grid[i][j]; - } - } - return disappear(newGrid, x, y, newGrid[x][y]); - } - public int disappear(int[][] grid, int x, - int y, int num) { - if (x >= grid.length || y >= grid[0].length || - x < 0 || y < 0 || grid[x][y] != num || - grid[x][y] == -1) return 0; - - grid[x][y] = -1; - return 1 + disappear(grid, x, y + 1, num) - + disappear(grid, x + 1, y, num) - + disappear(grid, x - 1, y, num) - + disappear(grid, x, y - 1, num); - } - - public static void main(String[] args) { - int[][] grid1 = - {{4, 4, 4, 4}, - {5, 5, 5, 4}, - {2, 5, 7, 5}}; - int[][] grid2 = {{0, 3, 3, 3, 3, 3, 3}, - {0, 1, 1, 1, 1, 1, 3}, - {0, 2, 2, 0, 2, 1, 4}, - {0, 1, 2, 2, 2, 1, 3}, - {0, 1, 1, 1, 1, 1, 3}, - {0, 0, 0, 0, 0, 0, 0}}; - int[][] grid3 = {{0}}; - int[][] grid4 = {{1, 1, 1}, - {1, 1, 1}, - {1, 1, 1}}; - - Solitaire solitaire = new Solitaire(); - System.out.println(solitaire.disappear(grid1, 0 , 0)); - System.out.println(solitaire.disappear(grid1, 1 , 0)); - System.out.println(solitaire.disappear(grid1, 2 , 0)); - System.out.println(solitaire.disappear(grid1, 2 , 2)); - - System.out.println(solitaire.disappear(grid2, 0 , 0)); - System.out.println(solitaire.disappear(grid2, 0 , 1)); - System.out.println(solitaire.disappear(grid2, 1 , 1)); - System.out.println(solitaire.disappear(grid2, 2 , 1)); - System.out.println(solitaire.disappear(grid2, 0 , 0)); - - System.out.println(solitaire.disappear(grid3, 0 , 0)); - - System.out.println(solitaire.disappear(grid4, 0 , 0)); - } -} diff --git a/src/in/knowledgegate/dsa/strings/387 First Unique Character in a String.java b/src/in/knowledgegate/dsa/strings/387 First Unique Character in a String.java new file mode 100644 index 0000000..e8c6dc2 --- /dev/null +++ b/src/in/knowledgegate/dsa/strings/387 First Unique Character in a String.java @@ -0,0 +1,23 @@ + + +import java.util.HashMap; + +class FirstUniqueCharacter { + public int firstUniqChar(String s) { + HashMap countMap = new HashMap<>(); + // Filling characters into the map + for (int i = 0 ; i < s.length(); i++) { + char c = s.charAt(i); + countMap.put(c, countMap.getOrDefault(c, 0) + 1); + } + + // Checking count 1 + for (int i = 0 ; i < s.length(); i++) { + char c = s.charAt(i); + if (countMap.get(c) == 1) { + return i; + } + } + return -1; + } +} diff --git a/src/in/knowledgegate/dsa/strings/GenerateParentheses.java b/src/in/knowledgegate/dsa/strings/GenerateParentheses.java index f82427a..8a73379 100644 --- a/src/in/knowledgegate/dsa/strings/GenerateParentheses.java +++ b/src/in/knowledgegate/dsa/strings/GenerateParentheses.java @@ -1,4 +1,4 @@ -package in.knowledgegate.dsa.strings; + import java.util.ArrayList; import java.util.List; @@ -19,21 +19,19 @@ * Constraints: * 1 <= n <= 8 */ -public class GenerateParentheses { +class GenerateParentheses { public static void main(String[] args) { - GenerateParentheses obj = - new GenerateParentheses(); + GenerateParentheses obj = new GenerateParentheses(); System.out.println("Here is the result:"); - for (String combi : - obj.generateParenthesis(3)) { + for (String combi : obj.generateParenthesis(3)) { System.out.print(combi + ", "); } } public List generateParenthesis(int n) { List combinations = new ArrayList<>(); - generateAllCombinations(new char[n*2], 0, + generateAllCombinations(new char[n * 2], 0, combinations); return combinations; } @@ -62,7 +60,8 @@ private boolean isValid(char[] current) { } else { counter--; } - if (counter < 0) return false; + if (counter < 0) + return false; } return counter == 0; } From 68e718b0309b7aff68174f87e6324456a8f1def8 Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Thu, 18 Apr 2024 10:12:56 +0530 Subject: [PATCH 02/17] Problems 168, 171, 205, 387 Added --- 3 Strings/168 Excel Sheet Column Title.java | 13 +++++++++++ 3 Strings/171 Excel Sheet Column Number.java | 12 ++++++++++ 3 Strings/205 Isomorphic Strings.java | 24 ++++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 3 Strings/168 Excel Sheet Column Title.java create mode 100644 3 Strings/171 Excel Sheet Column Number.java create mode 100644 3 Strings/205 Isomorphic Strings.java diff --git a/3 Strings/168 Excel Sheet Column Title.java b/3 Strings/168 Excel Sheet Column Title.java new file mode 100644 index 0000000..2392cd4 --- /dev/null +++ b/3 Strings/168 Excel Sheet Column Title.java @@ -0,0 +1,13 @@ +class Solution { + public String convertToTitle(int columnNumber) { + StringBuilder result = new StringBuilder(); + while (columnNumber > 0) { + columnNumber--; + int rem = columnNumber % 26; + char c = (char) ('A' + rem); + result.insert(0, c); + columnNumber /= 26; + } + return result.toString(); + } +} \ No newline at end of file diff --git a/3 Strings/171 Excel Sheet Column Number.java b/3 Strings/171 Excel Sheet Column Number.java new file mode 100644 index 0000000..e853bc4 --- /dev/null +++ b/3 Strings/171 Excel Sheet Column Number.java @@ -0,0 +1,12 @@ +class Solution { + public int titleToNumber(String columnTitle) { + int result = 0; + int len = columnTitle.length(); + for (int i = len - 1, pow = 0; i >= 0; i--, pow++) { + char c = columnTitle.charAt(i); + int digit = c - 'A' + 1; + result += digit * Math.pow(26, pow); + } + return result; + } +} \ No newline at end of file diff --git a/3 Strings/205 Isomorphic Strings.java b/3 Strings/205 Isomorphic Strings.java new file mode 100644 index 0000000..5021775 --- /dev/null +++ b/3 Strings/205 Isomorphic Strings.java @@ -0,0 +1,24 @@ +import java.util.HashMap; + +class Solution { + public boolean isIsomorphic(String s, String t) { + if (s.length() != t.length()) { + return false; + } + HashMap sToT = new HashMap<>(); + HashMap tToS = new HashMap<>(); + for (int i = 0; i < s.length(); i++) { + char sChar = s.charAt(i); + char tChar = t.charAt(i); + + if (sToT.getOrDefault(sChar, tChar) != tChar || + tToS.getOrDefault(tChar, sChar) != sChar) { + return false; + } + + sToT.put(sChar, tChar); + tToS.put(tChar, sChar); + } + return true; + } +} \ No newline at end of file From 9d4ca3285f4b134030389c3a99b4b511a7597758 Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Thu, 18 Apr 2024 15:25:59 +0530 Subject: [PATCH 03/17] removing extra --- 17 DFS and BFS/InvertBinaryTree.java | 1 - .../dsa/backtracking/NQueen.java | 104 ------------------ .../dsa/complexity/ArrayCopy.java | 16 --- ...87 First Unique Character in a String.java | 23 ---- .../dsa/strings/GenerateParentheses.java | 68 ------------ 5 files changed, 212 deletions(-) delete mode 100644 src/in/knowledgegate/dsa/backtracking/NQueen.java delete mode 100644 src/in/knowledgegate/dsa/complexity/ArrayCopy.java delete mode 100644 src/in/knowledgegate/dsa/strings/387 First Unique Character in a String.java delete mode 100644 src/in/knowledgegate/dsa/strings/GenerateParentheses.java diff --git a/17 DFS and BFS/InvertBinaryTree.java b/17 DFS and BFS/InvertBinaryTree.java index 01cc796..0186db3 100644 --- a/17 DFS and BFS/InvertBinaryTree.java +++ b/17 DFS and BFS/InvertBinaryTree.java @@ -1,5 +1,4 @@ -import in.knowledgegate.dsa.binarytree.model.TreeNode; /** * Given the root of a binary tree, invert the diff --git a/src/in/knowledgegate/dsa/backtracking/NQueen.java b/src/in/knowledgegate/dsa/backtracking/NQueen.java deleted file mode 100644 index 1565225..0000000 --- a/src/in/knowledgegate/dsa/backtracking/NQueen.java +++ /dev/null @@ -1,104 +0,0 @@ - - -import java.util.Scanner; - -/** - * The n-queens puzzle is the problem of placing - * n queens on an n x n chessboard such that no - * two queens attack each other. - * - * Given an integer n, return any one solution - * to the n-queens puzzle. You may - * return the answer in any order. - * - * Each solution contains a distinct board - * configuration of the n-queens' placement, - * where 'Q' and '.' both indicate a queen and - * an empty space, respectively. - * - * Example 1: - * Input: n = 4 - * Output: [["..Q.","Q...","...Q",".Q.."]] - * - * Example 2: - * Input: n = 1 - * Output: [["Q"]] - * - * Constraints: - * 1 <= n <= 30 - */ -class NQueen { - private void printBoard(int[][] board) { - for (int i = 0; i < board.length; i++) { - for (int j = 0; j < board[i].length; j++) { - char out = board[i][j] == 1 ? 'Q' : '.'; - System.out.print(" " + out + " "); - } - System.out.println(); - } - } - - private boolean isMoveSafe(int[][] board, - int row, int col) { - - for (int j = 0; j < col; j++) { - if (board[row][j] == 1) { - return false; - } - } - - for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { - if (board[i][j] == 1) { - return false; - } - } - - for (int i = row, j = col; j >= 0 && i < board.length; j--, i++) { - if (board[i][j] == 1) { - return false; - } - } - - return true; - } - - /** - * This method is only responsible to put queen - * in a specific column. - */ - private boolean nQueen(int[][] board, int col) { - if (col >= board.length) { - return true; - } - - for (int i = 0; i < board.length; i++) { - if (isMoveSafe(board, i, col)) { - board[i][col] = 1; - if (nQueen(board, col + 1)) - return true; - board[i][col] = 0; - } - } - - return false; - } - - private void nQueen(int size) { - int[][] board = new int[size][size]; - if (!nQueen(board, 0)) { - System.out.println("Solution does not " + - "exist"); - } else { - printBoard(board); - } - } - - public static void main(String[] args) { - try (Scanner scanner = new Scanner(System.in)) { - NQueen nQueen = new NQueen(); - System.out.print("Enter size of board: "); - int size = scanner.nextInt(); - nQueen.nQueen(size); - } - } -} diff --git a/src/in/knowledgegate/dsa/complexity/ArrayCopy.java b/src/in/knowledgegate/dsa/complexity/ArrayCopy.java deleted file mode 100644 index 20de58e..0000000 --- a/src/in/knowledgegate/dsa/complexity/ArrayCopy.java +++ /dev/null @@ -1,16 +0,0 @@ - - -class ArrayCopy { - - public static void main(String[] args) { - int[] newCopy = copy(new int[] { 1, 2, 3, 4, 5 }); - } - - private static int[] copy(int[] array) { - int[] newCopy = new int[array.length]; - for (int i = 0; i < array.length; i++) { - newCopy[i] = array[i]; - } - return newCopy; - } -} \ No newline at end of file diff --git a/src/in/knowledgegate/dsa/strings/387 First Unique Character in a String.java b/src/in/knowledgegate/dsa/strings/387 First Unique Character in a String.java deleted file mode 100644 index e8c6dc2..0000000 --- a/src/in/knowledgegate/dsa/strings/387 First Unique Character in a String.java +++ /dev/null @@ -1,23 +0,0 @@ - - -import java.util.HashMap; - -class FirstUniqueCharacter { - public int firstUniqChar(String s) { - HashMap countMap = new HashMap<>(); - // Filling characters into the map - for (int i = 0 ; i < s.length(); i++) { - char c = s.charAt(i); - countMap.put(c, countMap.getOrDefault(c, 0) + 1); - } - - // Checking count 1 - for (int i = 0 ; i < s.length(); i++) { - char c = s.charAt(i); - if (countMap.get(c) == 1) { - return i; - } - } - return -1; - } -} diff --git a/src/in/knowledgegate/dsa/strings/GenerateParentheses.java b/src/in/knowledgegate/dsa/strings/GenerateParentheses.java deleted file mode 100644 index 8a73379..0000000 --- a/src/in/knowledgegate/dsa/strings/GenerateParentheses.java +++ /dev/null @@ -1,68 +0,0 @@ - - -import java.util.ArrayList; -import java.util.List; - -/** - * Given n pairs of parentheses, write a function - * to generate all combinations of well-formed - * parentheses. - * - * Example 1: - * Input: n = 3 - * Output: ["((()))","(()())","(())()","()(())","()()()"] - * - * Example 2: - * Input: n = 1 - * Output: ["()"] - * - * Constraints: - * 1 <= n <= 8 - */ -class GenerateParentheses { - - public static void main(String[] args) { - GenerateParentheses obj = new GenerateParentheses(); - System.out.println("Here is the result:"); - for (String combi : obj.generateParenthesis(3)) { - System.out.print(combi + ", "); - } - } - - public List generateParenthesis(int n) { - List combinations = new ArrayList<>(); - generateAllCombinations(new char[n * 2], 0, - combinations); - return combinations; - } - - private void generateAllCombinations(char[] current, - int pos, List combinations) { - if (pos == current.length) { - if (isValid(current)) { - combinations.add(new String(current)); - } - } else { - current[pos] = '('; - generateAllCombinations(current, pos + 1, - combinations); - current[pos] = ')'; - generateAllCombinations(current, pos + 1, - combinations); - } - } - - private boolean isValid(char[] current) { - int counter = 0; - for (int i = 0; i < current.length; i++) { - if (current[i] == '(') { - counter++; - } else { - counter--; - } - if (counter < 0) - return false; - } - return counter == 0; - } -} From 31864d000ef08f68eb6a15b35b100259c87ca22f Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Thu, 18 Apr 2024 15:30:34 +0530 Subject: [PATCH 04/17] Fixing Errors after moving --- 17 DFS and BFS/InvertBinaryTree.java | 2 -- 22 Sliding Window/ContainsDuplicate2.java | 1 - 8 Linked List/PalindromeLinkedList.java | 3 --- ListNode.java | 1 - TreeNode.java | 13 +++++++++++++ 5 files changed, 13 insertions(+), 7 deletions(-) create mode 100644 TreeNode.java diff --git a/17 DFS and BFS/InvertBinaryTree.java b/17 DFS and BFS/InvertBinaryTree.java index 0186db3..d7b810b 100644 --- a/17 DFS and BFS/InvertBinaryTree.java +++ b/17 DFS and BFS/InvertBinaryTree.java @@ -1,5 +1,3 @@ - - /** * Given the root of a binary tree, invert the * tree, and return its root. diff --git a/22 Sliding Window/ContainsDuplicate2.java b/22 Sliding Window/ContainsDuplicate2.java index bcc3c46..fd8dc3d 100644 --- a/22 Sliding Window/ContainsDuplicate2.java +++ b/22 Sliding Window/ContainsDuplicate2.java @@ -1,4 +1,3 @@ - import java.util.HashSet; import java.util.Set; diff --git a/8 Linked List/PalindromeLinkedList.java b/8 Linked List/PalindromeLinkedList.java index 35beed3..5e8da10 100644 --- a/8 Linked List/PalindromeLinkedList.java +++ b/8 Linked List/PalindromeLinkedList.java @@ -1,6 +1,3 @@ - -import in.knowledgegate.dsa.ListNode; - /** * Given the head of a singly linked list, * return true if it is a palindrome. diff --git a/ListNode.java b/ListNode.java index 416378b..a531a80 100644 --- a/ListNode.java +++ b/ListNode.java @@ -1,4 +1,3 @@ - class ListNode { public int val; diff --git a/TreeNode.java b/TreeNode.java new file mode 100644 index 0000000..32d99ea --- /dev/null +++ b/TreeNode.java @@ -0,0 +1,13 @@ +public class TreeNode { + + public int val; + public TreeNode left; + public TreeNode right; + + public TreeNode() { + } + + public TreeNode(int val) { + this.val = val; + } +} \ No newline at end of file From a0a466caaede334eda20e51678a1e29596d689fe Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Fri, 19 Apr 2024 11:33:50 +0530 Subject: [PATCH 05/17] Leetcode Problems 242, 290, 345, 383 Done. --- 3 Strings/242 Valid Anagram.java | 24 ++++++++++++++ 3 Strings/290 Word Pattern.java | 33 +++++++++++++++++++ 3 Strings/345 Reverse Vowels of a String.java | 28 ++++++++++++++++ 3 Strings/383 Ransom Note.java | 19 +++++++++++ 4 files changed, 104 insertions(+) create mode 100644 3 Strings/242 Valid Anagram.java create mode 100644 3 Strings/290 Word Pattern.java create mode 100644 3 Strings/345 Reverse Vowels of a String.java create mode 100644 3 Strings/383 Ransom Note.java diff --git a/3 Strings/242 Valid Anagram.java b/3 Strings/242 Valid Anagram.java new file mode 100644 index 0000000..0eaeda8 --- /dev/null +++ b/3 Strings/242 Valid Anagram.java @@ -0,0 +1,24 @@ +import java.util.HashMap; + +class Solution { + public boolean isAnagram(String s, String t) { + if (s.length() != t.length()) { + return false; + } + HashMap countMap = new HashMap<>(); + for (int i = 0 ; i < s.length(); i++) { + char sChar = s.charAt(i); + char tChar = t.charAt(i); + + countMap.put(sChar, countMap.getOrDefault(sChar, 0) + 1); + countMap.put(tChar, countMap.getOrDefault(tChar, 0) - 1); + } + + for (int value : countMap.values()) { + if (value != 0) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/3 Strings/290 Word Pattern.java b/3 Strings/290 Word Pattern.java new file mode 100644 index 0000000..78f115e --- /dev/null +++ b/3 Strings/290 Word Pattern.java @@ -0,0 +1,33 @@ +import java.util.HashMap; + +class Solution { + public boolean wordPattern(String pattern, String s) { + String[] words = s.split(" "); + if (pattern.length() != words.length) { + return false; + } + HashMap lToW = new HashMap<>(); + HashMap wToL = new HashMap<>(); + for (int i = 0 ; i < pattern.length(); i++) { + char letter = pattern.charAt(i); + String word = words[i]; + + if (lToW.containsKey(letter)) { + if (!lToW.get(letter).equals(word)) { + return false; + } + } else { + lToW.put(letter, word); + } + + if (wToL.containsKey(word)) { + if (wToL.get(word) != letter) { + return false; + } + } else { + wToL.put(word, letter); + } + } + return true; + } +} \ No newline at end of file diff --git a/3 Strings/345 Reverse Vowels of a String.java b/3 Strings/345 Reverse Vowels of a String.java new file mode 100644 index 0000000..f496632 --- /dev/null +++ b/3 Strings/345 Reverse Vowels of a String.java @@ -0,0 +1,28 @@ +class Solution { + public String reverseVowels(String s) { + char[] letters = s.toCharArray(); + int i = 0, j = s.length() - 1; + + while (i < j) { + // increment till i reaches a vowel + while (i < j && !isVowel(letters[i])) i++; + + // decrement till j reaches a vowel + while (i < j && !isVowel(letters[j])) j--; + + if (i < j) { + char temp = letters[i]; + letters[i] = letters[j]; + letters[j] = temp; + i++; + j--; + } + } + return new String(letters); + } + + private boolean isVowel(char c) { + final String VOWELS = "aeiouAEIOU"; + return VOWELS.indexOf(c) != -1; + } +} \ No newline at end of file diff --git a/3 Strings/383 Ransom Note.java b/3 Strings/383 Ransom Note.java new file mode 100644 index 0000000..1b47d23 --- /dev/null +++ b/3 Strings/383 Ransom Note.java @@ -0,0 +1,19 @@ +class Solution { + public boolean canConstruct(String ransomNote, String magazine) { + int[] counts = new int[26]; + for (char c : magazine.toCharArray()) { + int index = c - 'a'; + counts[index]++; + } + for (char c : ransomNote.toCharArray()) { + int index = c - 'a'; + counts[index]--; + } + for (int count: counts) { + if (count < 0) { + return false; + } + } + return true; + } +} \ No newline at end of file From 68f7c2e5d8b3a499b1f630b53f610c685e267d3a Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Thu, 25 Apr 2024 17:54:12 +0530 Subject: [PATCH 06/17] Update README.md --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index dd26188..7c23f85 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,5 @@ -# DSA +# DSA using Java + Data Structures and Algorithms + +![DSA Thumbnail](https://github.com/KG-Coding-with-Prashant-Sir/DSA_using_Java/assets/102736197/1cda942b-d878-40bd-9b09-59f7d673c917) From d507472bc1902feefc4b4d02ec706948cfd8b0d3 Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Thu, 25 Apr 2024 18:53:02 +0530 Subject: [PATCH 07/17] Array Problems Fixed --- .../Leetcode 1 TwoSum.java | 0 .../Leetcode 118 Pascals Triangle.java | 25 +++++++++++++++++++ ...e 121 Best Time to Buy and Sell Stock.java | 19 ++++++++++++++ .../Leetcode 169 Majority Element.java | 22 ++++++++++++++++ .../Leetcode 217 Contains Duplicate.java | 13 ++++++++++ ...6 Remove Duplicates from Sorted Array.java | 0 .../Leetcode 27 Remove Element.java | 12 +++++++++ .../Leetcode 35 Search Insert Position.java | 12 +++++++++ .../Leetcode 66 Plus One.java | 16 ++++++++++++ .../Leetcode 88 Merge Sorted Array.java | 20 +++++++++++++++ ...eetcode 892 Surface Area of 3D Shapes.java | 0 .../Leetcode 36 Valid Sudoku.java | 0 .../Leetcode 53 Maximum Subarray.java | 0 13 files changed, 139 insertions(+) rename 1 Arrays/TwoSum.java => 1 Leetcode Easy Problems/Leetcode 1 TwoSum.java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle.java create mode 100644 1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock.java create mode 100644 1 Leetcode Easy Problems/Leetcode 169 Majority Element.java create mode 100644 1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate.java rename 1 Arrays/RemoveDuplicatesSortedArray.java => 1 Leetcode Easy Problems/Leetcode 26 Remove Duplicates from Sorted Array.java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 27 Remove Element.java create mode 100644 1 Leetcode Easy Problems/Leetcode 35 Search Insert Position.java create mode 100644 1 Leetcode Easy Problems/Leetcode 66 Plus One.java create mode 100644 1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array.java rename 1 Arrays/SurfaceAreaOf3DShapes.java => 1 Leetcode Easy Problems/Leetcode 892 Surface Area of 3D Shapes.java (100%) rename 1 Arrays/ValidSudoku.java => 2 Leetcode Medium Problems/Leetcode 36 Valid Sudoku.java (100%) rename 1 Arrays/MaximumSubArray.java => 2 Leetcode Medium Problems/Leetcode 53 Maximum Subarray.java (100%) diff --git a/1 Arrays/TwoSum.java b/1 Leetcode Easy Problems/Leetcode 1 TwoSum.java similarity index 100% rename from 1 Arrays/TwoSum.java rename to 1 Leetcode Easy Problems/Leetcode 1 TwoSum.java diff --git a/1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle.java b/1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle.java new file mode 100644 index 0000000..b823282 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle.java @@ -0,0 +1,25 @@ +import java.util.*; + +class Solution { + public List> generate(int numRows) { + if (numRows == 1) { + List> result = new ArrayList<>(); + List firstRow = new ArrayList<>(); + firstRow.add(1); + result.add(firstRow); + return result; + } + + List> previousRows = generate(numRows - 1); + List lastRow = previousRows.get(numRows - 2); + List newRow = new ArrayList<>(); + newRow.add(1); + + for(int i = 1; i < numRows - 1; i++) { + newRow.add(lastRow.get(i-1) + lastRow.get(i)); + } + newRow.add(1); + previousRows.add(newRow); + return previousRows; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock.java b/1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock.java new file mode 100644 index 0000000..fc79274 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock.java @@ -0,0 +1,19 @@ +class Solution { + public int maxProfit(int[] prices) { + int maxProfit = 0; + int minPrice = Integer.MAX_VALUE; + + for (int i = 0; i < prices.length; i++) { + if (minPrice > prices[i]) { + minPrice = prices[i]; + } else { + int profit = prices[i] - minPrice; + if (profit > maxProfit) { + maxProfit = profit; + } + } + } + + return maxProfit; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 169 Majority Element.java b/1 Leetcode Easy Problems/Leetcode 169 Majority Element.java new file mode 100644 index 0000000..7e044d0 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 169 Majority Element.java @@ -0,0 +1,22 @@ +class Solution { + public int majorityElement(int[] nums) { + int majority = 0; + + for (int i = 0; i < 32; i++) { + int bit = 1 << i; + + int count = 0; + for (int num: nums) { + if ((num & bit) != 0) { + count++; + } + } + + if (count > nums.length / 2) { + majority |= bit; + } + } + + return majority; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate.java b/1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate.java new file mode 100644 index 0000000..55f8e35 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate.java @@ -0,0 +1,13 @@ +import java.util.*; + +class Solution { + public boolean containsDuplicate(int[] nums) { + Set numSet = new HashSet<>(); + for (int num: nums) { + if (numSet.add(num) == false) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/1 Arrays/RemoveDuplicatesSortedArray.java b/1 Leetcode Easy Problems/Leetcode 26 Remove Duplicates from Sorted Array.java similarity index 100% rename from 1 Arrays/RemoveDuplicatesSortedArray.java rename to 1 Leetcode Easy Problems/Leetcode 26 Remove Duplicates from Sorted Array.java diff --git a/1 Leetcode Easy Problems/Leetcode 27 Remove Element.java b/1 Leetcode Easy Problems/Leetcode 27 Remove Element.java new file mode 100644 index 0000000..a487bc0 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 27 Remove Element.java @@ -0,0 +1,12 @@ +class Solution { + public int removeElement(int[] nums, int val) { + int j = 0; + for (int i = 0; i < nums.length; i++) { + if (nums[i] != val) { + nums[j] = nums[i]; + j++; + } + } + return j; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 35 Search Insert Position.java b/1 Leetcode Easy Problems/Leetcode 35 Search Insert Position.java new file mode 100644 index 0000000..01fd287 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 35 Search Insert Position.java @@ -0,0 +1,12 @@ +class Solution { + public int searchInsert(int[] nums, int target) { + int i = 0; + while (i < nums.length) { + if (nums[i] >= target) { + break; + } + i++; + } + return i; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 66 Plus One.java b/1 Leetcode Easy Problems/Leetcode 66 Plus One.java new file mode 100644 index 0000000..bcec9c6 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 66 Plus One.java @@ -0,0 +1,16 @@ +class Solution { + public int[] plusOne(int[] digits) { + for (int i = digits.length - 1; i >= 0; i--) { + if (digits[i] != 9) { + digits[i]++; + return digits; + } else { + digits[i] = 0; + } + } + + int[] newDigits = new int[digits.length + 1]; + newDigits[0] = 1; + return newDigits; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array.java b/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array.java new file mode 100644 index 0000000..36460a2 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array.java @@ -0,0 +1,20 @@ +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int i = m-1; + int j = n-1; + int k = nums1.length - 1; + + // O(m+n) + while (j >= 0) { + if (i >= 0 && nums1[i] > nums2[j]) { + nums1[k] = nums1[i]; + i--; + k--; + } else { + nums1[k] = nums2[j]; + j--; + k--; + } + } + } +} \ No newline at end of file diff --git a/1 Arrays/SurfaceAreaOf3DShapes.java b/1 Leetcode Easy Problems/Leetcode 892 Surface Area of 3D Shapes.java similarity index 100% rename from 1 Arrays/SurfaceAreaOf3DShapes.java rename to 1 Leetcode Easy Problems/Leetcode 892 Surface Area of 3D Shapes.java diff --git a/1 Arrays/ValidSudoku.java b/2 Leetcode Medium Problems/Leetcode 36 Valid Sudoku.java similarity index 100% rename from 1 Arrays/ValidSudoku.java rename to 2 Leetcode Medium Problems/Leetcode 36 Valid Sudoku.java diff --git a/1 Arrays/MaximumSubArray.java b/2 Leetcode Medium Problems/Leetcode 53 Maximum Subarray.java similarity index 100% rename from 1 Arrays/MaximumSubArray.java rename to 2 Leetcode Medium Problems/Leetcode 53 Maximum Subarray.java From b0536cad7c05cc072d5f38165c935cc701132765 Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Thu, 25 Apr 2024 19:06:12 +0530 Subject: [PATCH 08/17] time and strings --- .../Leetcode 125 Valid Palindrome.java | 0 ...rateParentheses.java => Leetcode 22 Generate Parentheses.java} | 0 {2 Time Complexity => 4 Other Problems}/ArrayCopy.java | 0 {2 Time Complexity => 4 Other Problems}/ArraySum.java | 0 {2 Time Complexity => 4 Other Problems}/Sum.java | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename 3 Strings/ValidPalindrome.java => 1 Leetcode Easy Problems/Leetcode 125 Valid Palindrome.java (100%) rename 3 Strings/{GenerateParentheses.java => Leetcode 22 Generate Parentheses.java} (100%) rename {2 Time Complexity => 4 Other Problems}/ArrayCopy.java (100%) rename {2 Time Complexity => 4 Other Problems}/ArraySum.java (100%) rename {2 Time Complexity => 4 Other Problems}/Sum.java (100%) diff --git a/3 Strings/ValidPalindrome.java b/1 Leetcode Easy Problems/Leetcode 125 Valid Palindrome.java similarity index 100% rename from 3 Strings/ValidPalindrome.java rename to 1 Leetcode Easy Problems/Leetcode 125 Valid Palindrome.java diff --git a/3 Strings/GenerateParentheses.java b/3 Strings/Leetcode 22 Generate Parentheses.java similarity index 100% rename from 3 Strings/GenerateParentheses.java rename to 3 Strings/Leetcode 22 Generate Parentheses.java diff --git a/2 Time Complexity/ArrayCopy.java b/4 Other Problems/ArrayCopy.java similarity index 100% rename from 2 Time Complexity/ArrayCopy.java rename to 4 Other Problems/ArrayCopy.java diff --git a/2 Time Complexity/ArraySum.java b/4 Other Problems/ArraySum.java similarity index 100% rename from 2 Time Complexity/ArraySum.java rename to 4 Other Problems/ArraySum.java diff --git a/2 Time Complexity/Sum.java b/4 Other Problems/Sum.java similarity index 100% rename from 2 Time Complexity/Sum.java rename to 4 Other Problems/Sum.java From 9fa1591ac9ca5e1c24436c217f475640b13f9472 Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Fri, 26 Apr 2024 11:00:04 +0530 Subject: [PATCH 09/17] String and Math Done --- ...etcode 13 Roman to Integer using Math.java | 0 .../Leetcode 13 Roman to Integer.java | 36 +++++++++++++++++++ .../Leetcode 14 Longest Common Prefix.java | 0 ...Leetcode 168 Excel Sheet Column Title.java | 0 ... Excel Sheet Column Number using Math.java | 0 ...eetcode 171 Excel Sheet Column Number.java | 0 .../Leetcode 205 Isomorphic Strings.java | 0 .../Leetcode 242 Valid Anagram.java | 0 .../Leetcode 290 Word Pattern.java | 0 .../Leetcode 344 Reverse String.java | 0 ...etcode 345 Reverse Vowels of a String.java | 0 .../Leetcode 383 Ransom Note.java | 0 ...87 First Unique Character in a String.java | 0 ...e 405 Convert a Number to Hexadecimal.java | 0 .../Leetcode 415 Add Strings.java | 0 .../Leetcode 58 Length of Last Word.java | 11 ++++++ .../Leetcode 66 Plus One using Math.java | 0 .../Leetcode 67 Add Binary.java | 27 ++++++++++++++ .../Leetcode 9 Palindrome Number.java | 0 .../Leetcode 189 Rotate Array.java | 0 .../Leetcode 204 Count Primes.java | 0 .../Leetcode 22 Generate Parentheses.java | 0 .../BubbleSort.java | 0 .../InsertionSort.java | 0 .../algos => 4 Other Problems}/MergeSort.java | 0 .../algos => 4 Other Problems}/QuickSort.java | 0 .../SelectionSort.java | 0 .../SortingAlgo.java | 0 28 files changed, 74 insertions(+) rename 4 Math/RomanToInteger.java => 1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Math.java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 13 Roman to Integer.java rename 3 Strings/LongestCommonPrefix.java => 1 Leetcode Easy Problems/Leetcode 14 Longest Common Prefix.java (100%) rename 3 Strings/168 Excel Sheet Column Title.java => 1 Leetcode Easy Problems/Leetcode 168 Excel Sheet Column Title.java (100%) rename 4 Math/ExcelSheetColumnNumber.java => 1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number using Math.java (100%) rename 3 Strings/171 Excel Sheet Column Number.java => 1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number.java (100%) rename 3 Strings/205 Isomorphic Strings.java => 1 Leetcode Easy Problems/Leetcode 205 Isomorphic Strings.java (100%) rename 3 Strings/242 Valid Anagram.java => 1 Leetcode Easy Problems/Leetcode 242 Valid Anagram.java (100%) rename 3 Strings/290 Word Pattern.java => 1 Leetcode Easy Problems/Leetcode 290 Word Pattern.java (100%) rename 3 Strings/ReverseString.java => 1 Leetcode Easy Problems/Leetcode 344 Reverse String.java (100%) rename 3 Strings/345 Reverse Vowels of a String.java => 1 Leetcode Easy Problems/Leetcode 345 Reverse Vowels of a String.java (100%) rename 3 Strings/383 Ransom Note.java => 1 Leetcode Easy Problems/Leetcode 383 Ransom Note.java (100%) rename 3 Strings/387 First Unique Character in a String.java => 1 Leetcode Easy Problems/Leetcode 387 First Unique Character in a String.java (100%) rename 4 Math/ConvertNumberToHexadecimal.java => 1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal.java (100%) rename 4 Math/AddStrings.java => 1 Leetcode Easy Problems/Leetcode 415 Add Strings.java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 58 Length of Last Word.java rename 4 Math/PlusOne.java => 1 Leetcode Easy Problems/Leetcode 66 Plus One using Math.java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 67 Add Binary.java rename 4 Math/PalindromeNumber.java => 1 Leetcode Easy Problems/Leetcode 9 Palindrome Number.java (100%) rename 4 Math/RotateArray.java => 2 Leetcode Medium Problems/Leetcode 189 Rotate Array.java (100%) rename 4 Math/CountPrimes.java => 2 Leetcode Medium Problems/Leetcode 204 Count Primes.java (100%) rename {3 Strings => 2 Leetcode Medium Problems}/Leetcode 22 Generate Parentheses.java (100%) rename {5 Sorting/algos => 4 Other Problems}/BubbleSort.java (100%) rename {5 Sorting/algos => 4 Other Problems}/InsertionSort.java (100%) rename {5 Sorting/algos => 4 Other Problems}/MergeSort.java (100%) rename {5 Sorting/algos => 4 Other Problems}/QuickSort.java (100%) rename {5 Sorting/algos => 4 Other Problems}/SelectionSort.java (100%) rename {5 Sorting/algos => 4 Other Problems}/SortingAlgo.java (100%) diff --git a/4 Math/RomanToInteger.java b/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Math.java similarity index 100% rename from 4 Math/RomanToInteger.java rename to 1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Math.java diff --git a/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer.java b/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer.java new file mode 100644 index 0000000..c2a4140 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer.java @@ -0,0 +1,36 @@ +import java.util.*; + +class Solution { + private final Map SYMBOLS = new HashMap<>(); + { + SYMBOLS.put('I', 1); + SYMBOLS.put('V', 5); + SYMBOLS.put('X', 10); + SYMBOLS.put('L', 50); + SYMBOLS.put('C', 100); + SYMBOLS.put('D', 500); + SYMBOLS.put('M', 1000); + } + + public int romanToInt(String roman) { + int result = 0; + for (int i = 0; i < roman.length(); i++) { + char current = roman.charAt(i); + int currValue = SYMBOLS.get(current); + int nextValue = 0; + + if (i + 1 < roman.length()) { + char nextChar = roman.charAt(i+1); + nextValue = SYMBOLS.get(nextChar); + } + + if (nextValue > currValue) { + result += (nextValue - currValue); + i++; + } else { + result += currValue; + } + } + return result; + } +} \ No newline at end of file diff --git a/3 Strings/LongestCommonPrefix.java b/1 Leetcode Easy Problems/Leetcode 14 Longest Common Prefix.java similarity index 100% rename from 3 Strings/LongestCommonPrefix.java rename to 1 Leetcode Easy Problems/Leetcode 14 Longest Common Prefix.java diff --git a/3 Strings/168 Excel Sheet Column Title.java b/1 Leetcode Easy Problems/Leetcode 168 Excel Sheet Column Title.java similarity index 100% rename from 3 Strings/168 Excel Sheet Column Title.java rename to 1 Leetcode Easy Problems/Leetcode 168 Excel Sheet Column Title.java diff --git a/4 Math/ExcelSheetColumnNumber.java b/1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number using Math.java similarity index 100% rename from 4 Math/ExcelSheetColumnNumber.java rename to 1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number using Math.java diff --git a/3 Strings/171 Excel Sheet Column Number.java b/1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number.java similarity index 100% rename from 3 Strings/171 Excel Sheet Column Number.java rename to 1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number.java diff --git a/3 Strings/205 Isomorphic Strings.java b/1 Leetcode Easy Problems/Leetcode 205 Isomorphic Strings.java similarity index 100% rename from 3 Strings/205 Isomorphic Strings.java rename to 1 Leetcode Easy Problems/Leetcode 205 Isomorphic Strings.java diff --git a/3 Strings/242 Valid Anagram.java b/1 Leetcode Easy Problems/Leetcode 242 Valid Anagram.java similarity index 100% rename from 3 Strings/242 Valid Anagram.java rename to 1 Leetcode Easy Problems/Leetcode 242 Valid Anagram.java diff --git a/3 Strings/290 Word Pattern.java b/1 Leetcode Easy Problems/Leetcode 290 Word Pattern.java similarity index 100% rename from 3 Strings/290 Word Pattern.java rename to 1 Leetcode Easy Problems/Leetcode 290 Word Pattern.java diff --git a/3 Strings/ReverseString.java b/1 Leetcode Easy Problems/Leetcode 344 Reverse String.java similarity index 100% rename from 3 Strings/ReverseString.java rename to 1 Leetcode Easy Problems/Leetcode 344 Reverse String.java diff --git a/3 Strings/345 Reverse Vowels of a String.java b/1 Leetcode Easy Problems/Leetcode 345 Reverse Vowels of a String.java similarity index 100% rename from 3 Strings/345 Reverse Vowels of a String.java rename to 1 Leetcode Easy Problems/Leetcode 345 Reverse Vowels of a String.java diff --git a/3 Strings/383 Ransom Note.java b/1 Leetcode Easy Problems/Leetcode 383 Ransom Note.java similarity index 100% rename from 3 Strings/383 Ransom Note.java rename to 1 Leetcode Easy Problems/Leetcode 383 Ransom Note.java diff --git a/3 Strings/387 First Unique Character in a String.java b/1 Leetcode Easy Problems/Leetcode 387 First Unique Character in a String.java similarity index 100% rename from 3 Strings/387 First Unique Character in a String.java rename to 1 Leetcode Easy Problems/Leetcode 387 First Unique Character in a String.java diff --git a/4 Math/ConvertNumberToHexadecimal.java b/1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal.java similarity index 100% rename from 4 Math/ConvertNumberToHexadecimal.java rename to 1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal.java diff --git a/4 Math/AddStrings.java b/1 Leetcode Easy Problems/Leetcode 415 Add Strings.java similarity index 100% rename from 4 Math/AddStrings.java rename to 1 Leetcode Easy Problems/Leetcode 415 Add Strings.java diff --git a/1 Leetcode Easy Problems/Leetcode 58 Length of Last Word.java b/1 Leetcode Easy Problems/Leetcode 58 Length of Last Word.java new file mode 100644 index 0000000..8f42410 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 58 Length of Last Word.java @@ -0,0 +1,11 @@ +class Solution { + public int lengthOfLastWord(String s) { + s = s.trim(); + for (int i = s.length() - 1; i >= 0; i--) { + if (s.charAt(i) == ' ') { + return s.length() - (i + 1); + } + } + return s.length(); + } +} \ No newline at end of file diff --git a/4 Math/PlusOne.java b/1 Leetcode Easy Problems/Leetcode 66 Plus One using Math.java similarity index 100% rename from 4 Math/PlusOne.java rename to 1 Leetcode Easy Problems/Leetcode 66 Plus One using Math.java diff --git a/1 Leetcode Easy Problems/Leetcode 67 Add Binary.java b/1 Leetcode Easy Problems/Leetcode 67 Add Binary.java new file mode 100644 index 0000000..045f1c7 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 67 Add Binary.java @@ -0,0 +1,27 @@ +class Solution { + public String addBinary(String a, String b) { + StringBuilder sb = new StringBuilder(); + int maxLength = Math.max(a.length(), b.length()); + + int carry = 0; + for (int i = 0; i < maxLength; i++) { + int aIndex = (a.length() - 1) - i; + int bIndex = (b.length() - 1) - i; + char aChar = aIndex >= 0 ? a.charAt(aIndex) : '0'; + char bChar = bIndex >= 0 ? b.charAt(bIndex) : '0'; + int aVal = aChar - '0'; + int bVal = bChar - '0'; + + int sum = aVal + bVal + carry; + int res = sum % 2; + carry = sum / 2; + sb.append(res); + } + + if (carry == 1) { + sb.append(carry); + } + + return sb.reverse().toString(); + } +} \ No newline at end of file diff --git a/4 Math/PalindromeNumber.java b/1 Leetcode Easy Problems/Leetcode 9 Palindrome Number.java similarity index 100% rename from 4 Math/PalindromeNumber.java rename to 1 Leetcode Easy Problems/Leetcode 9 Palindrome Number.java diff --git a/4 Math/RotateArray.java b/2 Leetcode Medium Problems/Leetcode 189 Rotate Array.java similarity index 100% rename from 4 Math/RotateArray.java rename to 2 Leetcode Medium Problems/Leetcode 189 Rotate Array.java diff --git a/4 Math/CountPrimes.java b/2 Leetcode Medium Problems/Leetcode 204 Count Primes.java similarity index 100% rename from 4 Math/CountPrimes.java rename to 2 Leetcode Medium Problems/Leetcode 204 Count Primes.java diff --git a/3 Strings/Leetcode 22 Generate Parentheses.java b/2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses.java similarity index 100% rename from 3 Strings/Leetcode 22 Generate Parentheses.java rename to 2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses.java diff --git a/5 Sorting/algos/BubbleSort.java b/4 Other Problems/BubbleSort.java similarity index 100% rename from 5 Sorting/algos/BubbleSort.java rename to 4 Other Problems/BubbleSort.java diff --git a/5 Sorting/algos/InsertionSort.java b/4 Other Problems/InsertionSort.java similarity index 100% rename from 5 Sorting/algos/InsertionSort.java rename to 4 Other Problems/InsertionSort.java diff --git a/5 Sorting/algos/MergeSort.java b/4 Other Problems/MergeSort.java similarity index 100% rename from 5 Sorting/algos/MergeSort.java rename to 4 Other Problems/MergeSort.java diff --git a/5 Sorting/algos/QuickSort.java b/4 Other Problems/QuickSort.java similarity index 100% rename from 5 Sorting/algos/QuickSort.java rename to 4 Other Problems/QuickSort.java diff --git a/5 Sorting/algos/SelectionSort.java b/4 Other Problems/SelectionSort.java similarity index 100% rename from 5 Sorting/algos/SelectionSort.java rename to 4 Other Problems/SelectionSort.java diff --git a/5 Sorting/algos/SortingAlgo.java b/4 Other Problems/SortingAlgo.java similarity index 100% rename from 5 Sorting/algos/SortingAlgo.java rename to 4 Other Problems/SortingAlgo.java From d780e3aaaf6191cb7c38f1aff4a2b99589f1a75a Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Fri, 26 Apr 2024 11:40:16 +0530 Subject: [PATCH 10/17] Sorting and Binary Search Fixed --- ...tcode 169 Majority Element using Sorting.java | 8 ++++++++ ...h Strictly Smaller and Greater Elements .java | 0 ...ode 217 Contains Duplicate using sorting.java | 16 ++++++++++++++++ .../Leetcode 278 First Bad Version.java | 0 ...arch Insert Position using Binary Search.java | 0 ...eetcode 374 Guess Number Higher or Lower.java | 0 .../Leetcode 441 Arranging Coins.java | 0 .../Leetcode 69 Sqrt(x).java | 0 ...code 88 Merge Sorted Array using Sorting.java | 0 .../Leetcode 977 Squares of a Sorted Array.java | 0 .../Leetcode 15 3Sum.java | 0 ...argest Element in an Array using Sorting.java | 0 ...etcode 33 Search in Rotated Sorted Array.java | 0 ...ode 540 Single Element in a Sorted Array.java | 0 .../Leetcode 74 Search a 2D Matrix.java | 0 .../algos => 4 Other Problems}/BinarySearch.java | 0 16 files changed, 24 insertions(+) create mode 100644 1 Leetcode Easy Problems/Leetcode 169 Majority Element using Sorting.java rename 5 Sorting/problems/CountElements.java => 1 Leetcode Easy Problems/Leetcode 2148 Count Elements With Strictly Smaller and Greater Elements .java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate using sorting.java rename 6 Binary Search/problems/FirstBadVersion.java => 1 Leetcode Easy Problems/Leetcode 278 First Bad Version.java (100%) rename 6 Binary Search/problems/SearchInsertPosition.java => 1 Leetcode Easy Problems/Leetcode 35 Search Insert Position using Binary Search.java (100%) rename 6 Binary Search/problems/GuessNumberHigherOrLower.java => 1 Leetcode Easy Problems/Leetcode 374 Guess Number Higher or Lower.java (100%) rename 6 Binary Search/problems/ArrangingCoins.java => 1 Leetcode Easy Problems/Leetcode 441 Arranging Coins.java (100%) rename 6 Binary Search/problems/SquareRoot.java => 1 Leetcode Easy Problems/Leetcode 69 Sqrt(x).java (100%) rename 5 Sorting/problems/MergeSortedArray.java => 1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Sorting.java (100%) rename 5 Sorting/problems/SquaresOfSortedArray.java => 1 Leetcode Easy Problems/Leetcode 977 Squares of a Sorted Array.java (100%) rename 5 Sorting/problems/ThreeSum.java => 2 Leetcode Medium Problems/Leetcode 15 3Sum.java (100%) rename 5 Sorting/problems/KthLargestElement.java => 2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array using Sorting.java (100%) rename 6 Binary Search/problems/SearchInRotatedSortedArray.java => 2 Leetcode Medium Problems/Leetcode 33 Search in Rotated Sorted Array.java (100%) rename 6 Binary Search/problems/SingleElementInASortedArray.java => 2 Leetcode Medium Problems/Leetcode 540 Single Element in a Sorted Array.java (100%) rename 6 Binary Search/problems/SearchIn2DMatrix.java => 2 Leetcode Medium Problems/Leetcode 74 Search a 2D Matrix.java (100%) rename {6 Binary Search/algos => 4 Other Problems}/BinarySearch.java (100%) diff --git a/1 Leetcode Easy Problems/Leetcode 169 Majority Element using Sorting.java b/1 Leetcode Easy Problems/Leetcode 169 Majority Element using Sorting.java new file mode 100644 index 0000000..098c5d7 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 169 Majority Element using Sorting.java @@ -0,0 +1,8 @@ +import java.util.*; + +class Solution { + public int majorityElement(int[] nums) { + Arrays.sort(nums); + return nums[nums.length/2]; + } +} \ No newline at end of file diff --git a/5 Sorting/problems/CountElements.java b/1 Leetcode Easy Problems/Leetcode 2148 Count Elements With Strictly Smaller and Greater Elements .java similarity index 100% rename from 5 Sorting/problems/CountElements.java rename to 1 Leetcode Easy Problems/Leetcode 2148 Count Elements With Strictly Smaller and Greater Elements .java diff --git a/1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate using sorting.java b/1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate using sorting.java new file mode 100644 index 0000000..2fb57ef --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate using sorting.java @@ -0,0 +1,16 @@ +import java.util.*; + +class Solution { + public boolean containsDuplicate(int[] nums) { + // O(nlogn) + Arrays.sort(nums); + + // O(n) + for (int i = 0; i < nums.length - 1; i++) { + if (nums[i] == nums[i+1]) { + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/6 Binary Search/problems/FirstBadVersion.java b/1 Leetcode Easy Problems/Leetcode 278 First Bad Version.java similarity index 100% rename from 6 Binary Search/problems/FirstBadVersion.java rename to 1 Leetcode Easy Problems/Leetcode 278 First Bad Version.java diff --git a/6 Binary Search/problems/SearchInsertPosition.java b/1 Leetcode Easy Problems/Leetcode 35 Search Insert Position using Binary Search.java similarity index 100% rename from 6 Binary Search/problems/SearchInsertPosition.java rename to 1 Leetcode Easy Problems/Leetcode 35 Search Insert Position using Binary Search.java diff --git a/6 Binary Search/problems/GuessNumberHigherOrLower.java b/1 Leetcode Easy Problems/Leetcode 374 Guess Number Higher or Lower.java similarity index 100% rename from 6 Binary Search/problems/GuessNumberHigherOrLower.java rename to 1 Leetcode Easy Problems/Leetcode 374 Guess Number Higher or Lower.java diff --git a/6 Binary Search/problems/ArrangingCoins.java b/1 Leetcode Easy Problems/Leetcode 441 Arranging Coins.java similarity index 100% rename from 6 Binary Search/problems/ArrangingCoins.java rename to 1 Leetcode Easy Problems/Leetcode 441 Arranging Coins.java diff --git a/6 Binary Search/problems/SquareRoot.java b/1 Leetcode Easy Problems/Leetcode 69 Sqrt(x).java similarity index 100% rename from 6 Binary Search/problems/SquareRoot.java rename to 1 Leetcode Easy Problems/Leetcode 69 Sqrt(x).java diff --git a/5 Sorting/problems/MergeSortedArray.java b/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Sorting.java similarity index 100% rename from 5 Sorting/problems/MergeSortedArray.java rename to 1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Sorting.java diff --git a/5 Sorting/problems/SquaresOfSortedArray.java b/1 Leetcode Easy Problems/Leetcode 977 Squares of a Sorted Array.java similarity index 100% rename from 5 Sorting/problems/SquaresOfSortedArray.java rename to 1 Leetcode Easy Problems/Leetcode 977 Squares of a Sorted Array.java diff --git a/5 Sorting/problems/ThreeSum.java b/2 Leetcode Medium Problems/Leetcode 15 3Sum.java similarity index 100% rename from 5 Sorting/problems/ThreeSum.java rename to 2 Leetcode Medium Problems/Leetcode 15 3Sum.java diff --git a/5 Sorting/problems/KthLargestElement.java b/2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array using Sorting.java similarity index 100% rename from 5 Sorting/problems/KthLargestElement.java rename to 2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array using Sorting.java diff --git a/6 Binary Search/problems/SearchInRotatedSortedArray.java b/2 Leetcode Medium Problems/Leetcode 33 Search in Rotated Sorted Array.java similarity index 100% rename from 6 Binary Search/problems/SearchInRotatedSortedArray.java rename to 2 Leetcode Medium Problems/Leetcode 33 Search in Rotated Sorted Array.java diff --git a/6 Binary Search/problems/SingleElementInASortedArray.java b/2 Leetcode Medium Problems/Leetcode 540 Single Element in a Sorted Array.java similarity index 100% rename from 6 Binary Search/problems/SingleElementInASortedArray.java rename to 2 Leetcode Medium Problems/Leetcode 540 Single Element in a Sorted Array.java diff --git a/6 Binary Search/problems/SearchIn2DMatrix.java b/2 Leetcode Medium Problems/Leetcode 74 Search a 2D Matrix.java similarity index 100% rename from 6 Binary Search/problems/SearchIn2DMatrix.java rename to 2 Leetcode Medium Problems/Leetcode 74 Search a 2D Matrix.java diff --git a/6 Binary Search/algos/BinarySearch.java b/4 Other Problems/BinarySearch.java similarity index 100% rename from 6 Binary Search/algos/BinarySearch.java rename to 4 Other Problems/BinarySearch.java From 1984deb080c47bf3ba22c3543b49fc84777db77f Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Fri, 26 Apr 2024 12:02:09 +0530 Subject: [PATCH 11/17] Fixes. --- .../Leetcode 278 First Bad Version.java | 6 +- ...code 374 Guess Number Higher or Lower.java | 18 ++-- .../Leetcode 441 Arranging Coins.java | 24 +++--- ...ode 33 Search in Rotated Sorted Array.java | 82 +++++-------------- 4 files changed, 44 insertions(+), 86 deletions(-) diff --git a/1 Leetcode Easy Problems/Leetcode 278 First Bad Version.java b/1 Leetcode Easy Problems/Leetcode 278 First Bad Version.java index 5a77365..9fc3ba4 100644 --- a/1 Leetcode Easy Problems/Leetcode 278 First Bad Version.java +++ b/1 Leetcode Easy Problems/Leetcode 278 First Bad Version.java @@ -47,16 +47,16 @@ public static void main(String[] args) { } public int firstBadVersion(int n) { - int beg = 1, end = n; + long beg = 1, end = n; while (beg <= end) { - int mid = (beg + end) / 2; + int mid = (int) ((beg + end) / 2); if (isBadVersion(mid)) { end = mid - 1; } else { beg = mid + 1; } } - return end + 1; + return (int) end + 1; } public int firstBadVersionLinearSearch(int n) { diff --git a/1 Leetcode Easy Problems/Leetcode 374 Guess Number Higher or Lower.java b/1 Leetcode Easy Problems/Leetcode 374 Guess Number Higher or Lower.java index f02138b..17fc657 100644 --- a/1 Leetcode Easy Problems/Leetcode 374 Guess Number Higher or Lower.java +++ b/1 Leetcode Easy Problems/Leetcode 374 Guess Number Higher or Lower.java @@ -46,16 +46,16 @@ public static void main(String[] args) { } public int guessNumber(int n) { - int beg = 1, end = n; + long beg = 1, end = n; while (beg <= end) { - int mid = (beg + end) / 2; - int res = guess(mid); - if (res == 0) - return mid; - if (res == -1) - end = mid - 1; - else - beg = mid + 1; + int mid = (int) ((beg + end) / 2); + int res = guess(mid); + if (res == 0) + return mid; + if (res == -1) + end = mid - 1; + else + beg = mid + 1; } return -1; } diff --git a/1 Leetcode Easy Problems/Leetcode 441 Arranging Coins.java b/1 Leetcode Easy Problems/Leetcode 441 Arranging Coins.java index 4c1f284..e52fac6 100644 --- a/1 Leetcode Easy Problems/Leetcode 441 Arranging Coins.java +++ b/1 Leetcode Easy Problems/Leetcode 441 Arranging Coins.java @@ -31,19 +31,19 @@ public static void main(String[] args) { } private int arrangeCoins(int n) { - int begin = 0; - int end = n; + long begin = 0; + long end = (int) Math.sqrt(2 * (long) n); // Adjust the initial end value while (begin <= end) { - int mid = (begin + end) / 2; - int coinsUsed = (mid * (mid + 1)) / 2; - if (coinsUsed == n) - return mid; - if (coinsUsed < n) { - begin = mid + 1; - } else { - end = mid - 1; - } + long mid = (begin + end) / 2; + long coinsUsed = (mid * (mid + 1)) / 2; + if (coinsUsed == n) + return (int) mid; + if (coinsUsed < n) { + begin = mid + 1; + } else { + end = mid - 1; + } } - return end; + return (int) end; } } diff --git a/2 Leetcode Medium Problems/Leetcode 33 Search in Rotated Sorted Array.java b/2 Leetcode Medium Problems/Leetcode 33 Search in Rotated Sorted Array.java index 277aa2f..3f1a2a9 100644 --- a/2 Leetcode Medium Problems/Leetcode 33 Search in Rotated Sorted Array.java +++ b/2 Leetcode Medium Problems/Leetcode 33 Search in Rotated Sorted Array.java @@ -1,76 +1,34 @@ - -/** - * There is an integer array nums sorted in ascending - * order (with distinct values). - * - * Prior to being passed to your function, nums is - * possibly rotated at an unknown pivot index - * k (1 <= k < nums.length) such that the resulting - * array is [nums[k], nums[k+1], ..., nums[n-1], - * nums[0], nums[1], ..., nums[k-1]] (0-indexed). - * For example, [0,1,2,4,5,6,7] might be rotated - * at pivot index 3 and become [4,5,6,7,0,1,2]. - * - * Given the array nums after the possible rotation - * and an integer target, return the index of - * target if it is in nums, or -1 if it is not in - * nums. - * - * You must write an algorithm with O(log n) runtime - * complexity. - * - * - * Example 1: 0,1,2,3,4,5,6 - * Input: nums = [4,5,6,7,0,1,2], target = 0 - * Output: 4 - * - * Example 2: - * Input: nums = [4,5,6,7,0,1,2], target = 3 - * Output: -1 - * - * Example 3: - * Input: nums = [1], target = 0 - * Output: -1 - * - * - * Constraints: - * 1 <= nums.length <= 5000 - * -104 <= nums[i] <= 104 - * All values of nums are unique. - * nums is an ascending array that is possibly rotated. - * -104 <= target <= 104 - */ -class SearchInRotatedSortedArray { - public static void main(String[] args) { - SearchInRotatedSortedArray search = new SearchInRotatedSortedArray(); - int[] nums = new int[] { 4, 5, 6, 7, 0, 1, 2 }; - System.out.println("Found at:" - + search.search(nums, 3)); - } - - int search(int[] nums, int target) { +class Solution { + public int search(int[] nums, int target) { int beg = 0, end = nums.length - 1; - while (beg <= end) { + + // First, find the smallest element's index (pivot index) + while (beg < end) { int mid = (beg + end) / 2; - if (nums[mid] > nums[end]) - beg = mid + 1; - else - end = mid - 1; + if (nums[mid] > nums[end]) { + beg = mid + 1; // pivot must be to the right of mid + } else { + end = mid; // pivot could be at mid, or to the left of mid + } } - int shift = end + 1; + // Now, beg == end == pivot index (smallest element index) + int pivot = beg; + // Reset beg and end for standard binary search, adjusted by pivot beg = 0; end = nums.length - 1; while (beg <= end) { int mid = (beg + end) / 2; - int realMid = (mid + shift) % nums.length; - if (nums[realMid] == target) + int realMid = (mid + pivot) % nums.length; // Adjust mid to account for rotation + + if (nums[realMid] == target) { return realMid; - else if (nums[realMid] < target) + } else if (nums[realMid] < target) { beg = mid + 1; - else + } else { end = mid - 1; + } } - return -1; + return -1; } } From b18c4a53c46a130c5bd2489887145f2e25a3e0e3 Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Fri, 26 Apr 2024 17:17:26 +0530 Subject: [PATCH 12/17] Two pointer, Bit Manipulation, Stack, Tree and Binary Tree, Recursion --- ...18 Pascal's Triangle using Linkedlist.java | 0 .../Leetcode 118 Pascal's Triangle.java | 28 ++++++ ...118 Pascals Triangle using Recursion.java} | 0 .../Leetcode 136 Single Number.java | 0 ...jority Element using Bit Manipulation.java | 22 +++++ .../Leetcode 20 Valid Parentheses.java | 0 .../Leetcode 21 Merge Two Sorted Lists.java | 32 +++++++ .../Leetcode 234 Palindrome Linked List.java | 0 .../Leetcode 268 Missing Number.java | 0 ... 27 Remove Element using Two Pointers.java | 0 .../Leetcode 283 Move Zeroes.java | 13 +-- .../Leetcode 389 Find the Difference.java | 0 ...to Hexadecimal using Bit Manipulation.java | 20 +++-- .../Leetcode 509 Fibonacci Number.java | 0 ...e 88 Merge Sorted Array using Sorting.java | 82 ++--------------- ...Merge Sorted Array using Two Pointers.java | 20 +++++ .../Leetcode 88 Merge Sorted Array.java | 90 +++++++++++++++---- ...Leetcode 11 Container With Most Water.java | 0 .../Factorial.java | 0 .../InorderTraversalIterative.java | 0 .../InorderTraversalRecursive.java | 0 .../PostorderTraversalIterative.java | 0 .../PostorderTraversalRecursive.java | 0 .../PreorderTraversalIterative.java | 0 .../PreorderTraversalRecursive.java | 0 .../model => 4 Other Problems}/TreeNode.java | 0 8 Linked List/MergeTwoSortedList.java | 56 ------------ 27 files changed, 206 insertions(+), 157 deletions(-) rename 8 Linked List/PascalTriangle.java => 1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle using Linkedlist.java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle.java rename 1 Leetcode Easy Problems/{Leetcode 118 Pascals Triangle.java => Leetcode 118 Pascals Triangle using Recursion.java} (100%) rename 7 Bit Manipulation/SingleNumber.java => 1 Leetcode Easy Problems/Leetcode 136 Single Number.java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 169 Majority Element using Bit Manipulation.java rename 12 Stack/ValidParenthesis.java => 1 Leetcode Easy Problems/Leetcode 20 Valid Parentheses.java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 21 Merge Two Sorted Lists.java rename 8 Linked List/PalindromeLinkedList.java => 1 Leetcode Easy Problems/Leetcode 234 Palindrome Linked List.java (100%) rename 7 Bit Manipulation/MissingNumber.java => 1 Leetcode Easy Problems/Leetcode 268 Missing Number.java (100%) rename 9 Two Pointers/RemoveElement.java => 1 Leetcode Easy Problems/Leetcode 27 Remove Element using Two Pointers.java (100%) rename 9 Two Pointers/MoveZeros.java => 1 Leetcode Easy Problems/Leetcode 283 Move Zeroes.java (68%) rename 7 Bit Manipulation/FindTheDifference.java => 1 Leetcode Easy Problems/Leetcode 389 Find the Difference.java (100%) rename 7 Bit Manipulation/ConvertNumberToHexadecimal.java => 1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal using Bit Manipulation.java (64%) rename 10 Recursion/Fibonacci.java => 1 Leetcode Easy Problems/Leetcode 509 Fibonacci Number.java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Two Pointers.java rename 9 Two Pointers/ContainerWithMostWater.java => 2 Leetcode Medium Problems/Leetcode 11 Container With Most Water.java (100%) rename {10 Recursion => 4 Other Problems}/Factorial.java (100%) rename {11 Tree and Binary Tree => 4 Other Problems}/InorderTraversalIterative.java (100%) rename {11 Tree and Binary Tree => 4 Other Problems}/InorderTraversalRecursive.java (100%) rename {11 Tree and Binary Tree => 4 Other Problems}/PostorderTraversalIterative.java (100%) rename {11 Tree and Binary Tree => 4 Other Problems}/PostorderTraversalRecursive.java (100%) rename {11 Tree and Binary Tree => 4 Other Problems}/PreorderTraversalIterative.java (100%) rename {11 Tree and Binary Tree => 4 Other Problems}/PreorderTraversalRecursive.java (100%) rename {11 Tree and Binary Tree/model => 4 Other Problems}/TreeNode.java (100%) delete mode 100644 8 Linked List/MergeTwoSortedList.java diff --git a/8 Linked List/PascalTriangle.java b/1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle using Linkedlist.java similarity index 100% rename from 8 Linked List/PascalTriangle.java rename to 1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle using Linkedlist.java diff --git a/1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle.java b/1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle.java new file mode 100644 index 0000000..a13d3f3 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle.java @@ -0,0 +1,28 @@ +import java.util.ArrayList; +import java.util.List; + +class Solution { + public List> generate(int numRows) { + List> result = new ArrayList<>(); + List firstRow = new ArrayList<>(); + firstRow.add(1); + result.add(firstRow); + + for (int i = 1; i < numRows; i++) { + List newRow = new ArrayList<>(); + newRow.add(1); + + // generating from previous row + List previousRow = result.get(i - 1); + for (int j = 1; j < i; j++) { + int num = previousRow.get(j - 1) + previousRow.get(j); + newRow.add(num); + } + + newRow.add(1); + result.add(newRow); + } + + return result; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle.java b/1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle using Recursion.java similarity index 100% rename from 1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle.java rename to 1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle using Recursion.java diff --git a/7 Bit Manipulation/SingleNumber.java b/1 Leetcode Easy Problems/Leetcode 136 Single Number.java similarity index 100% rename from 7 Bit Manipulation/SingleNumber.java rename to 1 Leetcode Easy Problems/Leetcode 136 Single Number.java diff --git a/1 Leetcode Easy Problems/Leetcode 169 Majority Element using Bit Manipulation.java b/1 Leetcode Easy Problems/Leetcode 169 Majority Element using Bit Manipulation.java new file mode 100644 index 0000000..7e044d0 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 169 Majority Element using Bit Manipulation.java @@ -0,0 +1,22 @@ +class Solution { + public int majorityElement(int[] nums) { + int majority = 0; + + for (int i = 0; i < 32; i++) { + int bit = 1 << i; + + int count = 0; + for (int num: nums) { + if ((num & bit) != 0) { + count++; + } + } + + if (count > nums.length / 2) { + majority |= bit; + } + } + + return majority; + } +} \ No newline at end of file diff --git a/12 Stack/ValidParenthesis.java b/1 Leetcode Easy Problems/Leetcode 20 Valid Parentheses.java similarity index 100% rename from 12 Stack/ValidParenthesis.java rename to 1 Leetcode Easy Problems/Leetcode 20 Valid Parentheses.java diff --git a/1 Leetcode Easy Problems/Leetcode 21 Merge Two Sorted Lists.java b/1 Leetcode Easy Problems/Leetcode 21 Merge Two Sorted Lists.java new file mode 100644 index 0000000..09fbaed --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 21 Merge Two Sorted Lists.java @@ -0,0 +1,32 @@ +/** + * Definition for singly-linked list. + */ + +class ListNode { + int val; + ListNode next; + ListNode() {} + ListNode(int val) { this.val = val; } + ListNode(int val, ListNode next) { this.val = val; this.next = next; } +} + +class Solution { + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { + ListNode temp = new ListNode(); + ListNode dummy = temp; + + while (list1 != null && list2 != null) { + if (list1.val <= list2.val) { + temp.next = list1; + list1 = list1.next; + } else { + temp.next = list2; + list2 = list2.next; + } + temp = temp.next; + } + + temp.next = list1 != null ? list1 : list2; + return dummy.next; + } +} \ No newline at end of file diff --git a/8 Linked List/PalindromeLinkedList.java b/1 Leetcode Easy Problems/Leetcode 234 Palindrome Linked List.java similarity index 100% rename from 8 Linked List/PalindromeLinkedList.java rename to 1 Leetcode Easy Problems/Leetcode 234 Palindrome Linked List.java diff --git a/7 Bit Manipulation/MissingNumber.java b/1 Leetcode Easy Problems/Leetcode 268 Missing Number.java similarity index 100% rename from 7 Bit Manipulation/MissingNumber.java rename to 1 Leetcode Easy Problems/Leetcode 268 Missing Number.java diff --git a/9 Two Pointers/RemoveElement.java b/1 Leetcode Easy Problems/Leetcode 27 Remove Element using Two Pointers.java similarity index 100% rename from 9 Two Pointers/RemoveElement.java rename to 1 Leetcode Easy Problems/Leetcode 27 Remove Element using Two Pointers.java diff --git a/9 Two Pointers/MoveZeros.java b/1 Leetcode Easy Problems/Leetcode 283 Move Zeroes.java similarity index 68% rename from 9 Two Pointers/MoveZeros.java rename to 1 Leetcode Easy Problems/Leetcode 283 Move Zeroes.java index 241dc3c..ae45e43 100644 --- a/9 Two Pointers/MoveZeros.java +++ b/1 Leetcode Easy Problems/Leetcode 283 Move Zeroes.java @@ -30,12 +30,15 @@ public static void main(String[] args) { } public void moveZeroes(int[] nums) { - int prev = 0; + int prev = 0; // This will track the position to place the next non-zero element. for (int i = 0; i < nums.length; i++) { - if (nums[i] != 0) { - nums[prev++] = nums[i]; - nums[i] = 0; + if (nums[i] != 0) { + nums[prev] = nums[i]; // Place the non-zero element at the 'prev' position + if (i != prev) { // Only set to zero if it's actually a move + nums[i] = 0; } + prev++; // Move the 'prev' position forward + } } - } + } } diff --git a/7 Bit Manipulation/FindTheDifference.java b/1 Leetcode Easy Problems/Leetcode 389 Find the Difference.java similarity index 100% rename from 7 Bit Manipulation/FindTheDifference.java rename to 1 Leetcode Easy Problems/Leetcode 389 Find the Difference.java diff --git a/7 Bit Manipulation/ConvertNumberToHexadecimal.java b/1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal using Bit Manipulation.java similarity index 64% rename from 7 Bit Manipulation/ConvertNumberToHexadecimal.java rename to 1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal using Bit Manipulation.java index 391e032..4112a5b 100644 --- a/7 Bit Manipulation/ConvertNumberToHexadecimal.java +++ b/1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal using Bit Manipulation.java @@ -33,16 +33,24 @@ public static void main(String[] args) { } public String toHex(int num) { - char[] mapping = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f' }; if (num == 0) return "0"; + + char[] mapping = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; StringBuilder result = new StringBuilder(); - while (num > 0) { - int endBits = num & 15; - result.insert(0, mapping[endBits]); - num = num >> 4; + + // Process 32 bits, regardless of whether num is positive or negative + for (int i = 0; i < 8; i++) { + int endBits = num & 15; // Get the last 4 bits + result.insert(0, mapping[endBits]); // Convert to hex and add to the front of the result + num = num >>> 4; // Logically shift right, filling with zeros (important for negative numbers) } + + // Remove leading zeros + while (result.length() > 1 && result.charAt(0) == '0') { + result.deleteCharAt(0); + } + return result.toString(); } } diff --git a/10 Recursion/Fibonacci.java b/1 Leetcode Easy Problems/Leetcode 509 Fibonacci Number.java similarity index 100% rename from 10 Recursion/Fibonacci.java rename to 1 Leetcode Easy Problems/Leetcode 509 Fibonacci Number.java diff --git a/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Sorting.java b/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Sorting.java index 3b99839..8982d69 100644 --- a/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Sorting.java +++ b/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Sorting.java @@ -1,76 +1,12 @@ +import java.util.*; -import java.util.Arrays; - -/** - * You are given two integer arrays nums1 and - * nums2, sorted in non-decreasing order, and two - * integers m and n, representing the number of - * elements in nums1 and nums2 respectively. - * - * Merge nums1 and nums2 into a single array - * sorted in non-decreasing order. - * - * The final sorted array should not be returned - * by the function, but instead be stored inside - * the array nums1. To accommodate this, nums1 has - * a length of m + n, where the first m elements - * denote the elements that should be merged, and - * the last n elements are set to 0 and should be - * ignored. nums2 has a length of n. - * - * - * Example 1: - * Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = - * [2,5,6], n = 3 Output: [1,2,2,3,5,6] - * Explanation: The arrays we are merging are - * [1,2,3] and [2,5,6]. The result of the merge is - * [1,2,2,3,5,6] with the underlined elements - * coming from nums1. - * - * Example 2: - * Input: nums1 = [1], m = 1, nums2 = [], n = 0 - * Output: [1] Explanation: The arrays we are - * merging are [1] and []. The result of the merge - * is [1]. - * - * Example 3: - * Input: nums1 = [0], m = 0, nums2 = [1], n = 1 - * Output: [1] Explanation: The arrays we are - * merging are [] and [1]. The result of the merge - * is [1]. Note that because m = 0, there are no - * elements in nums1. The 0 is only there to - * ensure the merge result can fit in nums1. - * - * Constraints: - * nums1.length == m + n nums2.length == n 0 <= m, - * n <= 200 1 <= m + n <= 200 -109 <= nums1[i], - * nums2[j] <= 109 - */ -class MergeSortedArray { - - public static void main(String[] args) { - MergeSortedArray merge = new MergeSortedArray(); - int[] nums1 = new int[] { 1, 2, 3, 0, 0, 0, 0 }; - int[] nums2 = new int[] { 0, 2, 5, 6 }; - merge.merge(nums1, 3, nums2, 4); - System.out.println("Output is:" + Arrays.toString(nums1)); - } - - public void merge(int[] nums1, int m, - int[] nums2, int n) { - int i = m - 1; - int j = n - 1; - int k = m + n - 1; - while (i >= 0 && j >= 0) { - if (nums1[i] >= nums2[j]) { - nums1[k--] = nums1[i--]; - } else { - nums1[k--] = nums2[j--]; +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + // O(n) + for (int i = 0; i < n; i++) { + nums1[m+i] = nums2[i]; } - } - - while (j >= 0) { - nums1[k--] = nums2[j--]; - } + // O((m+n) * log(m+n)) + Arrays.sort(nums1); } -} +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Two Pointers.java b/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Two Pointers.java new file mode 100644 index 0000000..36460a2 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Two Pointers.java @@ -0,0 +1,20 @@ +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int i = m-1; + int j = n-1; + int k = nums1.length - 1; + + // O(m+n) + while (j >= 0) { + if (i >= 0 && nums1[i] > nums2[j]) { + nums1[k] = nums1[i]; + i--; + k--; + } else { + nums1[k] = nums2[j]; + j--; + k--; + } + } + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array.java b/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array.java index 36460a2..3b99839 100644 --- a/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array.java +++ b/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array.java @@ -1,20 +1,76 @@ -class Solution { - public void merge(int[] nums1, int m, int[] nums2, int n) { - int i = m-1; - int j = n-1; - int k = nums1.length - 1; - // O(m+n) - while (j >= 0) { - if (i >= 0 && nums1[i] > nums2[j]) { - nums1[k] = nums1[i]; - i--; - k--; - } else { - nums1[k] = nums2[j]; - j--; - k--; - } +import java.util.Arrays; + +/** + * You are given two integer arrays nums1 and + * nums2, sorted in non-decreasing order, and two + * integers m and n, representing the number of + * elements in nums1 and nums2 respectively. + * + * Merge nums1 and nums2 into a single array + * sorted in non-decreasing order. + * + * The final sorted array should not be returned + * by the function, but instead be stored inside + * the array nums1. To accommodate this, nums1 has + * a length of m + n, where the first m elements + * denote the elements that should be merged, and + * the last n elements are set to 0 and should be + * ignored. nums2 has a length of n. + * + * + * Example 1: + * Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = + * [2,5,6], n = 3 Output: [1,2,2,3,5,6] + * Explanation: The arrays we are merging are + * [1,2,3] and [2,5,6]. The result of the merge is + * [1,2,2,3,5,6] with the underlined elements + * coming from nums1. + * + * Example 2: + * Input: nums1 = [1], m = 1, nums2 = [], n = 0 + * Output: [1] Explanation: The arrays we are + * merging are [1] and []. The result of the merge + * is [1]. + * + * Example 3: + * Input: nums1 = [0], m = 0, nums2 = [1], n = 1 + * Output: [1] Explanation: The arrays we are + * merging are [] and [1]. The result of the merge + * is [1]. Note that because m = 0, there are no + * elements in nums1. The 0 is only there to + * ensure the merge result can fit in nums1. + * + * Constraints: + * nums1.length == m + n nums2.length == n 0 <= m, + * n <= 200 1 <= m + n <= 200 -109 <= nums1[i], + * nums2[j] <= 109 + */ +class MergeSortedArray { + + public static void main(String[] args) { + MergeSortedArray merge = new MergeSortedArray(); + int[] nums1 = new int[] { 1, 2, 3, 0, 0, 0, 0 }; + int[] nums2 = new int[] { 0, 2, 5, 6 }; + merge.merge(nums1, 3, nums2, 4); + System.out.println("Output is:" + Arrays.toString(nums1)); + } + + public void merge(int[] nums1, int m, + int[] nums2, int n) { + int i = m - 1; + int j = n - 1; + int k = m + n - 1; + while (i >= 0 && j >= 0) { + if (nums1[i] >= nums2[j]) { + nums1[k--] = nums1[i--]; + } else { + nums1[k--] = nums2[j--]; } + } + + while (j >= 0) { + nums1[k--] = nums2[j--]; + } } -} \ No newline at end of file +} diff --git a/9 Two Pointers/ContainerWithMostWater.java b/2 Leetcode Medium Problems/Leetcode 11 Container With Most Water.java similarity index 100% rename from 9 Two Pointers/ContainerWithMostWater.java rename to 2 Leetcode Medium Problems/Leetcode 11 Container With Most Water.java diff --git a/10 Recursion/Factorial.java b/4 Other Problems/Factorial.java similarity index 100% rename from 10 Recursion/Factorial.java rename to 4 Other Problems/Factorial.java diff --git a/11 Tree and Binary Tree/InorderTraversalIterative.java b/4 Other Problems/InorderTraversalIterative.java similarity index 100% rename from 11 Tree and Binary Tree/InorderTraversalIterative.java rename to 4 Other Problems/InorderTraversalIterative.java diff --git a/11 Tree and Binary Tree/InorderTraversalRecursive.java b/4 Other Problems/InorderTraversalRecursive.java similarity index 100% rename from 11 Tree and Binary Tree/InorderTraversalRecursive.java rename to 4 Other Problems/InorderTraversalRecursive.java diff --git a/11 Tree and Binary Tree/PostorderTraversalIterative.java b/4 Other Problems/PostorderTraversalIterative.java similarity index 100% rename from 11 Tree and Binary Tree/PostorderTraversalIterative.java rename to 4 Other Problems/PostorderTraversalIterative.java diff --git a/11 Tree and Binary Tree/PostorderTraversalRecursive.java b/4 Other Problems/PostorderTraversalRecursive.java similarity index 100% rename from 11 Tree and Binary Tree/PostorderTraversalRecursive.java rename to 4 Other Problems/PostorderTraversalRecursive.java diff --git a/11 Tree and Binary Tree/PreorderTraversalIterative.java b/4 Other Problems/PreorderTraversalIterative.java similarity index 100% rename from 11 Tree and Binary Tree/PreorderTraversalIterative.java rename to 4 Other Problems/PreorderTraversalIterative.java diff --git a/11 Tree and Binary Tree/PreorderTraversalRecursive.java b/4 Other Problems/PreorderTraversalRecursive.java similarity index 100% rename from 11 Tree and Binary Tree/PreorderTraversalRecursive.java rename to 4 Other Problems/PreorderTraversalRecursive.java diff --git a/11 Tree and Binary Tree/model/TreeNode.java b/4 Other Problems/TreeNode.java similarity index 100% rename from 11 Tree and Binary Tree/model/TreeNode.java rename to 4 Other Problems/TreeNode.java diff --git a/8 Linked List/MergeTwoSortedList.java b/8 Linked List/MergeTwoSortedList.java deleted file mode 100644 index 8bc427b..0000000 --- a/8 Linked List/MergeTwoSortedList.java +++ /dev/null @@ -1,56 +0,0 @@ - -/** - * You are given the heads of two sorted linked - * lists list1 and list2. - * - * Merge the two lists in a one sorted list. - * The list should be made by splicing together - * the nodes of the first two lists. - * - * Return the head of the merged linked list. - * - * Example 1: - * Input: list1 = [1,2,4], list2 = [1,3,4] - * Output: [dummy, 1,1,2,3,4,4] - * - * Example 2: - * Input: list1 = [], list2 = [] - * Output: [] - * - * Example 3: - * Input: list1 = [], list2 = [0] - * Output: [0] - * - * Constraints: - * The number of nodes in both lists is in the - * range [0, 50]. - * -100 <= Node.val <= 100 - * Both list1 and list2 are sorted in - * non-decreasing order. - */ -class MergeTwoSortedList { - private class ListNode { - int val; - ListNode next; - } - - public ListNode mergeTwoLists(ListNode list1, - ListNode list2) { - ListNode temp = new ListNode(); - ListNode dummy = temp; - - while (list1 != null && list2 != null) { - if (list1.val <= list2.val) { - temp.next = list1; - list1 = list1.next; - } else { - temp.next = list2; - list2 = list2.next; - } - temp = temp.next; - } - - temp.next = list1 != null ? list1 : list2; - return dummy.next; - } -} From b62441e4c521e159b5297a2c638003dd6df53807 Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Fri, 26 Apr 2024 18:04:41 +0530 Subject: [PATCH 13/17] All code moved and renamed. --- .../Leetcode 1 Two Sum using Hashmap.java | 0 .../Leetcode 112 Path Sum.java | 0 ...118 Pascal's Triangle using Recursion.java | 30 ++++++++++++ ...s Triangle using Dynamic Programming.java} | 0 ...me to Buy and Sell Stock using Greedy.java | 19 +++++++ ...e 121 Best Time to Buy and Sell Stock.java | 29 +++++------ ...tcode 13 Roman to Integer using Array.java | 42 ++++++++++++++++ ...de 13 Roman to Integer using Hashmap.java} | 0 ...de 169 Majority Element using Hashmap.java | 28 +++++++++++ .../Leetcode 169 Majority Element.java | 22 --------- ...217 Contains Duplicate using Hashmap.java} | 0 .../Leetcode 219 Contains Duplicate II.java | 0 .../Leetcode 226 Invert Binary Tree.java | 0 ...x of the First Occurrence in a String.java | 18 +++++++ ...etcode 349 Intersection of Two Arrays.java | 0 ...ode 350 Intersection of Two Arrays II.java | 0 .../Leetcode 70 Climbing Stairs.java | 0 ...de 700 Search in a Binary Search Tree.java | 16 ++++-- .../Leetcode 933 Number of Recent Calls.java | 0 .../Leetcode 997 Find the Town Judge.java | 0 18 Greedy/BestTimeToBuyAndSellStock.java | 49 ------------------- ...e 215 Kth Largest Element in an Array.java | 0 ...nerate Parentheses using Backtracking.java | 0 ... 78 Subsets using Dynamic Programming.java | 0 .../Leetcode 78 Subsets.java | 0 .../Leetcode 51 N-Queens.java | 0 .../ListNode.java | 0 .../MiniMahjongWinningHand.java | 0 .../MiniMahjongWinningHand2.java | 0 .../RodCutting.java | 0 .../Solitaire.java | 0 4 Other Problems/TreeNode.java | 14 ++---- TreeNode.java | 13 ----- 33 files changed, 166 insertions(+), 114 deletions(-) rename 14 Hashing and Maps/TwoSum.java => 1 Leetcode Easy Problems/Leetcode 1 Two Sum using Hashmap.java (100%) rename 17 DFS and BFS/PathSum.java => 1 Leetcode Easy Problems/Leetcode 112 Path Sum.java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle using Recursion.java rename 1 Leetcode Easy Problems/{Leetcode 118 Pascals Triangle using Recursion.java => Leetcode 118 Pascals Triangle using Dynamic Programming.java} (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock using Greedy.java create mode 100644 1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Array.java rename 1 Leetcode Easy Problems/{Leetcode 13 Roman to Integer.java => Leetcode 13 Roman to Integer using Hashmap.java} (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 169 Majority Element using Hashmap.java delete mode 100644 1 Leetcode Easy Problems/Leetcode 169 Majority Element.java rename 1 Leetcode Easy Problems/{Leetcode 217 Contains Duplicate.java => Leetcode 217 Contains Duplicate using Hashmap.java} (100%) rename 22 Sliding Window/ContainsDuplicate2.java => 1 Leetcode Easy Problems/Leetcode 219 Contains Duplicate II.java (100%) rename 17 DFS and BFS/InvertBinaryTree.java => 1 Leetcode Easy Problems/Leetcode 226 Invert Binary Tree.java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 28 Find the Index of the First Occurrence in a String.java rename 14 Hashing and Maps/IntersectionOfTwoArrays.java => 1 Leetcode Easy Problems/Leetcode 349 Intersection of Two Arrays.java (100%) rename 14 Hashing and Maps/IntersectionOfTwoArrays2.java => 1 Leetcode Easy Problems/Leetcode 350 Intersection of Two Arrays II.java (100%) rename 21 Dynamic Programming/ClimbingStairs.java => 1 Leetcode Easy Problems/Leetcode 70 Climbing Stairs.java (100%) rename 15 Binary Search Tree/SearchInBST.java => 1 Leetcode Easy Problems/Leetcode 700 Search in a Binary Search Tree.java (75%) rename 13 Queue/RecentCounter.java => 1 Leetcode Easy Problems/Leetcode 933 Number of Recent Calls.java (100%) rename 16 Graph/FindTheTownJudge.java => 1 Leetcode Easy Problems/Leetcode 997 Find the Town Judge.java (100%) delete mode 100644 18 Greedy/BestTimeToBuyAndSellStock.java rename 20 Heap/KthLargestElement.java => 2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array.java (100%) rename 19 Backtracking/GenerateParentheses.java => 2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses using Backtracking.java (100%) rename 21 Dynamic Programming/Subsets.java => 2 Leetcode Medium Problems/Leetcode 78 Subsets using Dynamic Programming.java (100%) rename 19 Backtracking/Subsets.java => 2 Leetcode Medium Problems/Leetcode 78 Subsets.java (100%) rename 19 Backtracking/NQueen.java => 3 Leetcode Hard Problems/Leetcode 51 N-Queens.java (100%) rename ListNode.java => 4 Other Problems/ListNode.java (100%) rename {14 Hashing and Maps => 4 Other Problems}/MiniMahjongWinningHand.java (100%) rename {18 Greedy => 4 Other Problems}/MiniMahjongWinningHand2.java (100%) rename {21 Dynamic Programming => 4 Other Problems}/RodCutting.java (100%) rename {17 DFS and BFS => 4 Other Problems}/Solitaire.java (100%) delete mode 100644 TreeNode.java diff --git a/14 Hashing and Maps/TwoSum.java b/1 Leetcode Easy Problems/Leetcode 1 Two Sum using Hashmap.java similarity index 100% rename from 14 Hashing and Maps/TwoSum.java rename to 1 Leetcode Easy Problems/Leetcode 1 Two Sum using Hashmap.java diff --git a/17 DFS and BFS/PathSum.java b/1 Leetcode Easy Problems/Leetcode 112 Path Sum.java similarity index 100% rename from 17 DFS and BFS/PathSum.java rename to 1 Leetcode Easy Problems/Leetcode 112 Path Sum.java diff --git a/1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle using Recursion.java b/1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle using Recursion.java new file mode 100644 index 0000000..025bed0 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle using Recursion.java @@ -0,0 +1,30 @@ +import java.util.*; + +class Solution { + public List> generate(int numRows) { + List> result = new ArrayList<>(); + for (int i = 0; i < numRows; i++) { + List genRow = generateRow(i+1); + result.add(genRow); + } + return result; + } + + private List generateRow(int rowNumber) { + if (rowNumber == 1) { + List firstRow = new ArrayList<>(); + firstRow.add(1); + return firstRow; + } + + List currRow = new ArrayList<>(); + List prevRow = generateRow(rowNumber - 1); + + currRow.add(1); + for (int i = 1; i < rowNumber - 1; i++) { + currRow.add(prevRow.get(i-1) + prevRow.get(i)); + } + currRow.add(1); + return currRow; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle using Recursion.java b/1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle using Dynamic Programming.java similarity index 100% rename from 1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle using Recursion.java rename to 1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle using Dynamic Programming.java diff --git a/1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock using Greedy.java b/1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock using Greedy.java new file mode 100644 index 0000000..11c3827 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock using Greedy.java @@ -0,0 +1,19 @@ +class Solution { + public int maxProfit(int[] prices) { + int maxProfit = 0; + int minPrice = Integer.MAX_VALUE; + + for (int i = 0; i < prices.length; i++) { + if (minPrice > prices[i]) { + minPrice = prices[i]; + } else { + int profit = prices[i] - minPrice; + if (profit > maxProfit) { + maxProfit = profit; + } + } + } + + return maxProfit; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock.java b/1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock.java index fc79274..88a081c 100644 --- a/1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock.java +++ b/1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock.java @@ -1,19 +1,14 @@ class Solution { - public int maxProfit(int[] prices) { - int maxProfit = 0; - int minPrice = Integer.MAX_VALUE; - - for (int i = 0; i < prices.length; i++) { - if (minPrice > prices[i]) { - minPrice = prices[i]; - } else { - int profit = prices[i] - minPrice; - if (profit > maxProfit) { - maxProfit = profit; - } - } - } - - return maxProfit; - } + public int maxProfit(int[] prices) { + int maxProfit = 0; + for (int i = 0; i < prices.length - 1; i++) { + for (int j = i + 1; j < prices.length; j++) { + int profit = prices[j] - prices[i]; + if (profit > maxProfit) { + maxProfit = profit; + } + } + } + return maxProfit; + } } \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Array.java b/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Array.java new file mode 100644 index 0000000..b075884 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Array.java @@ -0,0 +1,42 @@ +class Solution { + private final String[][] SYMBOLS = new String[][]{ + {"I", "1"}, + {"V", "5"}, + {"X", "10"}, + {"L", "50"}, + {"C", "100"}, + {"D", "500"}, + {"M", "1000"}, + }; + + private int getSymbolValue(char symbol) { + for (String[] row: SYMBOLS) { + if (row[0].equals(symbol + "")) { + return Integer.parseInt(row[1]); + } + } + return 0; + } + + public int romanToInt(String s) { + int result = 0; + for (int i = 0; i < s.length(); i++) { + char current = s.charAt(i); + int currValue = getSymbolValue(current); + + if (i + 1 < s.length()) { + char next = s.charAt(i+1); + int nextVal = getSymbolValue(next); + if (nextVal <= currValue) { + result += currValue; + } else { + result += (nextVal - currValue); + i++; + } + } else { + result += currValue; + } + } + return result; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer.java b/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Hashmap.java similarity index 100% rename from 1 Leetcode Easy Problems/Leetcode 13 Roman to Integer.java rename to 1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Hashmap.java diff --git a/1 Leetcode Easy Problems/Leetcode 169 Majority Element using Hashmap.java b/1 Leetcode Easy Problems/Leetcode 169 Majority Element using Hashmap.java new file mode 100644 index 0000000..fef8f5e --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 169 Majority Element using Hashmap.java @@ -0,0 +1,28 @@ +import java.util.*; + +class Solution { + public int majorityElement(int[] nums) { + Map cardi = getCardinalityMap(nums); + // Space: O(1), Time: O(n) + for (Map.Entry entry : cardi.entrySet()) { + if (entry.getValue() > nums.length / 2) { + return entry.getKey(); + } + } + return -1; + } + + // Space: O(n), Time: O(n) + private Map getCardinalityMap(int[] nums) { + Map cardi = new HashMap<>(); + for (int num: nums) { + if (!cardi.containsKey(num)) { + cardi.put(num, 1); + } else { + int currCount = cardi.get(num); + cardi.put(num, currCount + 1); + } + } + return cardi; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 169 Majority Element.java b/1 Leetcode Easy Problems/Leetcode 169 Majority Element.java deleted file mode 100644 index 7e044d0..0000000 --- a/1 Leetcode Easy Problems/Leetcode 169 Majority Element.java +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { - public int majorityElement(int[] nums) { - int majority = 0; - - for (int i = 0; i < 32; i++) { - int bit = 1 << i; - - int count = 0; - for (int num: nums) { - if ((num & bit) != 0) { - count++; - } - } - - if (count > nums.length / 2) { - majority |= bit; - } - } - - return majority; - } -} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate.java b/1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate using Hashmap.java similarity index 100% rename from 1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate.java rename to 1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate using Hashmap.java diff --git a/22 Sliding Window/ContainsDuplicate2.java b/1 Leetcode Easy Problems/Leetcode 219 Contains Duplicate II.java similarity index 100% rename from 22 Sliding Window/ContainsDuplicate2.java rename to 1 Leetcode Easy Problems/Leetcode 219 Contains Duplicate II.java diff --git a/17 DFS and BFS/InvertBinaryTree.java b/1 Leetcode Easy Problems/Leetcode 226 Invert Binary Tree.java similarity index 100% rename from 17 DFS and BFS/InvertBinaryTree.java rename to 1 Leetcode Easy Problems/Leetcode 226 Invert Binary Tree.java diff --git a/1 Leetcode Easy Problems/Leetcode 28 Find the Index of the First Occurrence in a String.java b/1 Leetcode Easy Problems/Leetcode 28 Find the Index of the First Occurrence in a String.java new file mode 100644 index 0000000..435e04b --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 28 Find the Index of the First Occurrence in a String.java @@ -0,0 +1,18 @@ +class Solution { + public int strStr(String haystack, String needle) { + for (int i = 0; i < haystack.length() - needle.length() + 1; i++) { + int j = 0; + while (j < needle.length()) { + if (haystack.charAt(i + j) != needle.charAt(j)) { + break; + } + j++; + } + + if (j == needle.length()) { + return i; + } + } + return -1; + } +} \ No newline at end of file diff --git a/14 Hashing and Maps/IntersectionOfTwoArrays.java b/1 Leetcode Easy Problems/Leetcode 349 Intersection of Two Arrays.java similarity index 100% rename from 14 Hashing and Maps/IntersectionOfTwoArrays.java rename to 1 Leetcode Easy Problems/Leetcode 349 Intersection of Two Arrays.java diff --git a/14 Hashing and Maps/IntersectionOfTwoArrays2.java b/1 Leetcode Easy Problems/Leetcode 350 Intersection of Two Arrays II.java similarity index 100% rename from 14 Hashing and Maps/IntersectionOfTwoArrays2.java rename to 1 Leetcode Easy Problems/Leetcode 350 Intersection of Two Arrays II.java diff --git a/21 Dynamic Programming/ClimbingStairs.java b/1 Leetcode Easy Problems/Leetcode 70 Climbing Stairs.java similarity index 100% rename from 21 Dynamic Programming/ClimbingStairs.java rename to 1 Leetcode Easy Problems/Leetcode 70 Climbing Stairs.java diff --git a/15 Binary Search Tree/SearchInBST.java b/1 Leetcode Easy Problems/Leetcode 700 Search in a Binary Search Tree.java similarity index 75% rename from 15 Binary Search Tree/SearchInBST.java rename to 1 Leetcode Easy Problems/Leetcode 700 Search in a Binary Search Tree.java index df68249..6d507e2 100644 --- a/15 Binary Search Tree/SearchInBST.java +++ b/1 Leetcode Easy Problems/Leetcode 700 Search in a Binary Search Tree.java @@ -1,6 +1,3 @@ - -import in.knowledgegate.dsa.binarytree.model.TreeNode; - /** * You are given the root of a binary search tree * (BST) and an integer val. @@ -45,3 +42,16 @@ public TreeNode searchBST(TreeNode root, int val) { return searchBST(root.left, val); } } + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode() {} + TreeNode(int val) { this.val = val; } + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } + } diff --git a/13 Queue/RecentCounter.java b/1 Leetcode Easy Problems/Leetcode 933 Number of Recent Calls.java similarity index 100% rename from 13 Queue/RecentCounter.java rename to 1 Leetcode Easy Problems/Leetcode 933 Number of Recent Calls.java diff --git a/16 Graph/FindTheTownJudge.java b/1 Leetcode Easy Problems/Leetcode 997 Find the Town Judge.java similarity index 100% rename from 16 Graph/FindTheTownJudge.java rename to 1 Leetcode Easy Problems/Leetcode 997 Find the Town Judge.java diff --git a/18 Greedy/BestTimeToBuyAndSellStock.java b/18 Greedy/BestTimeToBuyAndSellStock.java deleted file mode 100644 index fac1858..0000000 --- a/18 Greedy/BestTimeToBuyAndSellStock.java +++ /dev/null @@ -1,49 +0,0 @@ - -/** - * You are given an array prices where prices[i] - * is the price of a given stock on the ith day. - * - * You want to maximize your profit by choosing - * a single day to buy one stock and choosing a - * different day in the future to sell that stock. - * - * Return the maximum profit you can achieve from - * this transaction. If you cannot achieve any - * profit, return 0. - * - * Example 1: - * Input: prices = [7,1,5,3,6,4] - * Output: 5 - * Explanation: Buy on day 2 (price = 1) and sell - * on day 5 (price = 6), profit = 6-1 = 5. - * Note that buying on day 2 and selling on day 1 - * is not allowed because you must buy before you - * sell. - * - * Example 2: - * Input: prices = [7,6,4,3,1] - * Output: 0 - * Explanation: In this case, no transactions - * are done and the max profit = 0. - * - * - * Constraints: - * 1 <= prices.length <= 105 - * 0 <= prices[i] <= 104 - */ -class BestTimeToBuyAndSellStock { - public int maxProfit(int[] prices) { - int buy = prices[0], maxProfit = 0; - for (int i = 1; i < prices.length; i++) { - if (buy > prices[i]) { - buy = prices[i]; - } else { - int currProfit = prices[i] - buy; - if (currProfit > maxProfit) { - maxProfit = currProfit; - } - } - } - return maxProfit; - } -} diff --git a/20 Heap/KthLargestElement.java b/2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array.java similarity index 100% rename from 20 Heap/KthLargestElement.java rename to 2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array.java diff --git a/19 Backtracking/GenerateParentheses.java b/2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses using Backtracking.java similarity index 100% rename from 19 Backtracking/GenerateParentheses.java rename to 2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses using Backtracking.java diff --git a/21 Dynamic Programming/Subsets.java b/2 Leetcode Medium Problems/Leetcode 78 Subsets using Dynamic Programming.java similarity index 100% rename from 21 Dynamic Programming/Subsets.java rename to 2 Leetcode Medium Problems/Leetcode 78 Subsets using Dynamic Programming.java diff --git a/19 Backtracking/Subsets.java b/2 Leetcode Medium Problems/Leetcode 78 Subsets.java similarity index 100% rename from 19 Backtracking/Subsets.java rename to 2 Leetcode Medium Problems/Leetcode 78 Subsets.java diff --git a/19 Backtracking/NQueen.java b/3 Leetcode Hard Problems/Leetcode 51 N-Queens.java similarity index 100% rename from 19 Backtracking/NQueen.java rename to 3 Leetcode Hard Problems/Leetcode 51 N-Queens.java diff --git a/ListNode.java b/4 Other Problems/ListNode.java similarity index 100% rename from ListNode.java rename to 4 Other Problems/ListNode.java diff --git a/14 Hashing and Maps/MiniMahjongWinningHand.java b/4 Other Problems/MiniMahjongWinningHand.java similarity index 100% rename from 14 Hashing and Maps/MiniMahjongWinningHand.java rename to 4 Other Problems/MiniMahjongWinningHand.java diff --git a/18 Greedy/MiniMahjongWinningHand2.java b/4 Other Problems/MiniMahjongWinningHand2.java similarity index 100% rename from 18 Greedy/MiniMahjongWinningHand2.java rename to 4 Other Problems/MiniMahjongWinningHand2.java diff --git a/21 Dynamic Programming/RodCutting.java b/4 Other Problems/RodCutting.java similarity index 100% rename from 21 Dynamic Programming/RodCutting.java rename to 4 Other Problems/RodCutting.java diff --git a/17 DFS and BFS/Solitaire.java b/4 Other Problems/Solitaire.java similarity index 100% rename from 17 DFS and BFS/Solitaire.java rename to 4 Other Problems/Solitaire.java diff --git a/4 Other Problems/TreeNode.java b/4 Other Problems/TreeNode.java index 9c2fa7e..32d99ea 100644 --- a/4 Other Problems/TreeNode.java +++ b/4 Other Problems/TreeNode.java @@ -1,19 +1,13 @@ +public class TreeNode { -class TreeNode { public int val; public TreeNode left; public TreeNode right; - TreeNode() { + public TreeNode() { } - TreeNode(int val) { + public TreeNode(int val) { this.val = val; } - - TreeNode(int val, TreeNode left, TreeNode right) { - this.val = val; - this.left = left; - this.right = right; - } -} +} \ No newline at end of file diff --git a/TreeNode.java b/TreeNode.java deleted file mode 100644 index 32d99ea..0000000 --- a/TreeNode.java +++ /dev/null @@ -1,13 +0,0 @@ -public class TreeNode { - - public int val; - public TreeNode left; - public TreeNode right; - - public TreeNode() { - } - - public TreeNode(int val) { - this.val = val; - } -} \ No newline at end of file From e4b551c1c2bc72b322f824b49b969c962d2d04da Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Fri, 26 Apr 2024 18:05:18 +0530 Subject: [PATCH 14/17] fix --- 1 Leetcode Easy Problems/Leetcode 112 Path Sum.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/1 Leetcode Easy Problems/Leetcode 112 Path Sum.java b/1 Leetcode Easy Problems/Leetcode 112 Path Sum.java index 300678b..03b8ea5 100644 --- a/1 Leetcode Easy Problems/Leetcode 112 Path Sum.java +++ b/1 Leetcode Easy Problems/Leetcode 112 Path Sum.java @@ -1,6 +1,3 @@ - -import in.knowledgegate.dsa.binarytree.model.TreeNode; - /** * Given the root of a binary tree and an integer * targetSum, return true if the tree has a From 85c902edbb03ff90ed2020ed387e684c22fa1d45 Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Sat, 27 Apr 2024 18:54:39 +0530 Subject: [PATCH 15/17] update --- ...ree Inorder Traversal using Iteration.java | 0 ...ree Inorder Traversal using Recursion.java | 0 ...using Iterative - Java Video Solution.java | 0 ...using Recursion - Java Video Solution.java | 0 ...e Postorder Traversal using Iteration.java | 0 ...e Postorder Traversal using Recursion.java | 0 ...83 Remove Duplicates from Sorted List.java | 23 +++++++++++++++++++ 7 files changed, 23 insertions(+) rename 4 Other Problems/InorderTraversalIterative.java => 1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Iteration.java (100%) rename 4 Other Problems/InorderTraversalRecursive.java => 1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Recursion.java (100%) rename 4 Other Problems/PreorderTraversalIterative.java => 1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Iterative - Java Video Solution.java (100%) rename 4 Other Problems/PreorderTraversalRecursive.java => 1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Recursion - Java Video Solution.java (100%) rename 4 Other Problems/PostorderTraversalIterative.java => 1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Iteration.java (100%) rename 4 Other Problems/PostorderTraversalRecursive.java => 1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Recursion.java (100%) create mode 100644 1 Leetcode Easy Problems/Leetcode 83 Remove Duplicates from Sorted List.java diff --git a/4 Other Problems/InorderTraversalIterative.java b/1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Iteration.java similarity index 100% rename from 4 Other Problems/InorderTraversalIterative.java rename to 1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Iteration.java diff --git a/4 Other Problems/InorderTraversalRecursive.java b/1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Recursion.java similarity index 100% rename from 4 Other Problems/InorderTraversalRecursive.java rename to 1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Recursion.java diff --git a/4 Other Problems/PreorderTraversalIterative.java b/1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Iterative - Java Video Solution.java similarity index 100% rename from 4 Other Problems/PreorderTraversalIterative.java rename to 1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Iterative - Java Video Solution.java diff --git a/4 Other Problems/PreorderTraversalRecursive.java b/1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Recursion - Java Video Solution.java similarity index 100% rename from 4 Other Problems/PreorderTraversalRecursive.java rename to 1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Recursion - Java Video Solution.java diff --git a/4 Other Problems/PostorderTraversalIterative.java b/1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Iteration.java similarity index 100% rename from 4 Other Problems/PostorderTraversalIterative.java rename to 1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Iteration.java diff --git a/4 Other Problems/PostorderTraversalRecursive.java b/1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Recursion.java similarity index 100% rename from 4 Other Problems/PostorderTraversalRecursive.java rename to 1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Recursion.java diff --git a/1 Leetcode Easy Problems/Leetcode 83 Remove Duplicates from Sorted List.java b/1 Leetcode Easy Problems/Leetcode 83 Remove Duplicates from Sorted List.java new file mode 100644 index 0000000..5a229bb --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 83 Remove Duplicates from Sorted List.java @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode current = head; + while (current != null && current.next != null) { + if (current.val == current.next.val) { + current.next = current.next.next; + } else { + current = current.next; + } + } + return head; + } +} \ No newline at end of file From 8ad0a0a19b84059e434fcfd5b47185259ccafcb7 Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Sat, 27 Apr 2024 19:07:33 +0530 Subject: [PATCH 16/17] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7c23f85..4c0bbcf 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # DSA using Java -Data Structures and Algorithms +Course Link: https://www.kgcoding.in/courses/DSA-using-Java ![DSA Thumbnail](https://github.com/KG-Coding-with-Prashant-Sir/DSA_using_Java/assets/102736197/1cda942b-d878-40bd-9b09-59f7d673c917) From db15f3cb073af6c344accafc09ef7eae34ca64d4 Mon Sep 17 00:00:00 2001 From: Prashant Jain Date: Sun, 28 Apr 2024 11:48:54 +0530 Subject: [PATCH 17/17] More solutions --- .../Leetcode 141 Linked List Cycle.java | 33 ++++++++++++++++ ... 160 Intersection of Two Linked Lists.java | 27 +++++++++++++ .../Leetcode 190 Reverse Bits.java | 12 ++++++ .../Leetcode 191 Number of 1 Bits.java | 12 ++++++ .../Leetcode 202 Happy Number.java | 25 ++++++++++++ ...tcode 203 Remove Linked List Elements.java | 38 +++++++++++++++++++ .../Leetcode 206 Reverse Linked List.java | 25 ++++++++++++ ...eetcode 222 Count Complete Tree Nodes.java | 22 +++++++++++ 8 files changed, 194 insertions(+) create mode 100644 1 Leetcode Easy Problems/Leetcode 141 Linked List Cycle.java create mode 100644 1 Leetcode Easy Problems/Leetcode 160 Intersection of Two Linked Lists.java create mode 100644 1 Leetcode Easy Problems/Leetcode 190 Reverse Bits.java create mode 100644 1 Leetcode Easy Problems/Leetcode 191 Number of 1 Bits.java create mode 100644 1 Leetcode Easy Problems/Leetcode 202 Happy Number.java create mode 100644 1 Leetcode Easy Problems/Leetcode 203 Remove Linked List Elements.java create mode 100644 1 Leetcode Easy Problems/Leetcode 206 Reverse Linked List.java create mode 100644 1 Leetcode Easy Problems/Leetcode 222 Count Complete Tree Nodes.java diff --git a/1 Leetcode Easy Problems/Leetcode 141 Linked List Cycle.java b/1 Leetcode Easy Problems/Leetcode 141 Linked List Cycle.java new file mode 100644 index 0000000..52027dc --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 141 Linked List Cycle.java @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +class Solution { + public boolean hasCycle(ListNode head) { + if (head == null || head.next == null) { + return false; + } + ListNode first = head; + ListNode second = first.next; + while (second != null && first != null) { + if (first == second) { + return true; + } + second = second.next != null ? second.next.next : null; + first = first.next; + } + return false; + } +} + + + + + diff --git a/1 Leetcode Easy Problems/Leetcode 160 Intersection of Two Linked Lists.java b/1 Leetcode Easy Problems/Leetcode 160 Intersection of Two Linked Lists.java new file mode 100644 index 0000000..7af0dc9 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 160 Intersection of Two Linked Lists.java @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +class Solution { + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { + if (headA == headB) + return headA; + if (headA == null || headB == null) + return null; + + ListNode first = headA; + ListNode second = headB; + while (first != second) { + first = first != null ? first.next : headB; + second = second != null ? second.next : headA; + } + return first; + } +} diff --git a/1 Leetcode Easy Problems/Leetcode 190 Reverse Bits.java b/1 Leetcode Easy Problems/Leetcode 190 Reverse Bits.java new file mode 100644 index 0000000..5fe080e --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 190 Reverse Bits.java @@ -0,0 +1,12 @@ +class Solution { + // you need treat n as an unsigned value + public int reverseBits(int n) { + int result = 0; + for (int i = 0 ; i < 32; i++) { + result = result << 1; + result = result | (n & 1); + n = n >>> 1; + } + return result; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 191 Number of 1 Bits.java b/1 Leetcode Easy Problems/Leetcode 191 Number of 1 Bits.java new file mode 100644 index 0000000..248271c --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 191 Number of 1 Bits.java @@ -0,0 +1,12 @@ +class Solution { + public int hammingWeight(int n) { + int count = 0; + while (n > 0) { + if ((n & 1) == 1) { + count++; + } + n >>= 1; + } + return count; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 202 Happy Number.java b/1 Leetcode Easy Problems/Leetcode 202 Happy Number.java new file mode 100644 index 0000000..30aa661 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 202 Happy Number.java @@ -0,0 +1,25 @@ +import java.util.*; + +class Solution { + public boolean isHappy(int n) { + Set set = new HashSet<>(); + while (n != 1) { + if (set.contains(n)) { + return false; + } + set.add(n); + n = sumOfSquareOfDigits(n); + } + return true; + } + + private int sumOfSquareOfDigits(int num) { + int result = 0; + while (num > 0) { + int rem = num % 10; + result += rem * rem; + num /= 10; + } + return result; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 203 Remove Linked List Elements.java b/1 Leetcode Easy Problems/Leetcode 203 Remove Linked List Elements.java new file mode 100644 index 0000000..822f63b --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 203 Remove Linked List Elements.java @@ -0,0 +1,38 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode removeElements(ListNode head, int val) { + ListNode dummy = new ListNode(); + dummy.next = head; + + ListNode temp = dummy; + while (temp.next != null) { + if (temp.next.val == val) { + temp.next = temp.next.next; + } else { + temp = temp.next; + } + } + return dummy.next; + } +} + + + + + + + + + + + + diff --git a/1 Leetcode Easy Problems/Leetcode 206 Reverse Linked List.java b/1 Leetcode Easy Problems/Leetcode 206 Reverse Linked List.java new file mode 100644 index 0000000..1f567c7 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 206 Reverse Linked List.java @@ -0,0 +1,25 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + ListNode prev = null; + ListNode current = head; + + while (current != null) { + ListNode temp = current.next; + current.next = prev; + prev = current; + current = temp; + } + + return prev; + } +} \ No newline at end of file diff --git a/1 Leetcode Easy Problems/Leetcode 222 Count Complete Tree Nodes.java b/1 Leetcode Easy Problems/Leetcode 222 Count Complete Tree Nodes.java new file mode 100644 index 0000000..49541fc --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 222 Count Complete Tree Nodes.java @@ -0,0 +1,22 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int countNodes(TreeNode root) { + if (root == null) return 0; + return 1 + countNodes(root.left) + + countNodes(root.right); + } +} \ No newline at end of file