diff --git a/src/in/knowledgegate/dsa/binarytree/InorderTraversalIterative.java b/1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Iteration.java similarity index 88% rename from src/in/knowledgegate/dsa/binarytree/InorderTraversalIterative.java rename to 1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Iteration.java index c39fec2..c192afd 100644 --- a/src/in/knowledgegate/dsa/binarytree/InorderTraversalIterative.java +++ b/1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Iteration.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/1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Recursion.java similarity index 82% rename from src/in/knowledgegate/dsa/binarytree/InorderTraversalRecursive.java rename to 1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Recursion.java index f8e8681..46a7c11 100644 --- a/src/in/knowledgegate/dsa/binarytree/InorderTraversalRecursive.java +++ b/1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Recursion.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/hashingAndMaps/TwoSum.java b/1 Leetcode Easy Problems/Leetcode 1 Two Sum using Hashmap.java similarity index 91% rename from src/in/knowledgegate/dsa/hashingAndMaps/TwoSum.java rename to 1 Leetcode Easy Problems/Leetcode 1 Two Sum using Hashmap.java index 1acbce1..1de0147 100644 --- a/src/in/knowledgegate/dsa/hashingAndMaps/TwoSum.java +++ b/1 Leetcode Easy Problems/Leetcode 1 Two Sum using Hashmap.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/array/TwoSum.java b/1 Leetcode Easy Problems/Leetcode 1 TwoSum.java similarity index 90% rename from src/in/knowledgegate/dsa/array/TwoSum.java rename to 1 Leetcode Easy Problems/Leetcode 1 TwoSum.java index 0a63e23..75d98ea 100644 --- a/src/in/knowledgegate/dsa/array/TwoSum.java +++ b/1 Leetcode Easy Problems/Leetcode 1 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/dfs/PathSum.java b/1 Leetcode Easy Problems/Leetcode 112 Path Sum.java similarity index 83% rename from src/in/knowledgegate/dsa/dfs/PathSum.java rename to 1 Leetcode Easy Problems/Leetcode 112 Path Sum.java index 1dc61f4..03b8ea5 100644 --- a/src/in/knowledgegate/dsa/dfs/PathSum.java +++ b/1 Leetcode Easy Problems/Leetcode 112 Path Sum.java @@ -1,7 +1,3 @@ -package in.knowledgegate.dsa.dfs; - -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 @@ -11,8 +7,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 +33,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/src/in/knowledgegate/dsa/linkedlist/PascalTriangle.java b/1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle using Linkedlist.java similarity index 93% rename from src/in/knowledgegate/dsa/linkedlist/PascalTriangle.java rename to 1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle using Linkedlist.java index 52ee418..d9bb9bb 100644 --- a/src/in/knowledgegate/dsa/linkedlist/PascalTriangle.java +++ b/1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle using Linkedlist.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/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 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 using Dynamic Programming.java b/1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle using Dynamic Programming.java new file mode 100644 index 0000000..b823282 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle using Dynamic Programming.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 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 new file mode 100644 index 0000000..88a081c --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock.java @@ -0,0 +1,14 @@ +class Solution { + 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/src/in/knowledgegate/dsa/strings/ValidPalindrome.java b/1 Leetcode Easy Problems/Leetcode 125 Valid Palindrome.java similarity index 87% rename from src/in/knowledgegate/dsa/strings/ValidPalindrome.java rename to 1 Leetcode Easy Problems/Leetcode 125 Valid Palindrome.java index 07edef4..937fc79 100644 --- a/src/in/knowledgegate/dsa/strings/ValidPalindrome.java +++ b/1 Leetcode Easy Problems/Leetcode 125 Valid Palindrome.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/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 using Hashmap.java b/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Hashmap.java new file mode 100644 index 0000000..c2a4140 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Hashmap.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/src/in/knowledgegate/dsa/math/RomanToInteger.java b/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Math.java similarity index 90% rename from src/in/knowledgegate/dsa/math/RomanToInteger.java rename to 1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Math.java index 9b76a01..f3c2636 100644 --- a/src/in/knowledgegate/dsa/math/RomanToInteger.java +++ b/1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Math.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/bitmanipulation/SingleNumber.java b/1 Leetcode Easy Problems/Leetcode 136 Single Number.java similarity index 90% rename from src/in/knowledgegate/dsa/bitmanipulation/SingleNumber.java rename to 1 Leetcode Easy Problems/Leetcode 136 Single Number.java index 34135a2..401f23f 100644 --- a/src/in/knowledgegate/dsa/bitmanipulation/SingleNumber.java +++ b/1 Leetcode Easy Problems/Leetcode 136 Single Number.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/strings/LongestCommonPrefix.java b/1 Leetcode Easy Problems/Leetcode 14 Longest Common Prefix.java similarity index 85% rename from src/in/knowledgegate/dsa/strings/LongestCommonPrefix.java rename to 1 Leetcode Easy Problems/Leetcode 14 Longest Common Prefix.java index 7d941f1..41b2503 100644 --- a/src/in/knowledgegate/dsa/strings/LongestCommonPrefix.java +++ b/1 Leetcode Easy Problems/Leetcode 14 Longest Common Prefix.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/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/src/in/knowledgegate/dsa/binarytree/PreorderTraversalIterative.java b/1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Iterative - Java Video Solution.java similarity index 89% rename from src/in/knowledgegate/dsa/binarytree/PreorderTraversalIterative.java rename to 1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Iterative - Java Video Solution.java index f006515..28b00b2 100644 --- a/src/in/knowledgegate/dsa/binarytree/PreorderTraversalIterative.java +++ b/1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Iterative - Java Video Solution.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/1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Recursion - Java Video Solution.java similarity index 75% rename from src/in/knowledgegate/dsa/binarytree/PreorderTraversalRecursive.java rename to 1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Recursion - Java Video Solution.java index 2c0a0db..2bfc788 100644 --- a/src/in/knowledgegate/dsa/binarytree/PreorderTraversalRecursive.java +++ b/1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Recursion - Java Video Solution.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/PostorderTraversalIterative.java b/1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Iteration.java similarity index 90% rename from src/in/knowledgegate/dsa/binarytree/PostorderTraversalIterative.java rename to 1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Iteration.java index 879211f..09197ee 100644 --- a/src/in/knowledgegate/dsa/binarytree/PostorderTraversalIterative.java +++ b/1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Iteration.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/1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Recursion.java similarity index 82% rename from src/in/knowledgegate/dsa/binarytree/PostorderTraversalRecursive.java rename to 1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Recursion.java index 10a1fee..b23ba85 100644 --- a/src/in/knowledgegate/dsa/binarytree/PostorderTraversalRecursive.java +++ b/1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Recursion.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/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 168 Excel Sheet Column Title.java b/1 Leetcode Easy Problems/Leetcode 168 Excel Sheet Column Title.java new file mode 100644 index 0000000..2392cd4 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 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/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/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 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/src/in/knowledgegate/dsa/math/ExcelSheetColumnNumber.java b/1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number using Math.java similarity index 78% rename from src/in/knowledgegate/dsa/math/ExcelSheetColumnNumber.java rename to 1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number using Math.java index 53c67ef..468883e 100644 --- a/src/in/knowledgegate/dsa/math/ExcelSheetColumnNumber.java +++ b/1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number using Math.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/1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number.java b/1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number.java new file mode 100644 index 0000000..e853bc4 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 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/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/src/in/knowledgegate/dsa/stack/ValidParenthesis.java b/1 Leetcode Easy Problems/Leetcode 20 Valid Parentheses.java similarity index 95% rename from src/in/knowledgegate/dsa/stack/ValidParenthesis.java rename to 1 Leetcode Easy Problems/Leetcode 20 Valid Parentheses.java index abdf5fb..44d34aa 100644 --- a/src/in/knowledgegate/dsa/stack/ValidParenthesis.java +++ b/1 Leetcode Easy Problems/Leetcode 20 Valid Parentheses.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/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 205 Isomorphic Strings.java b/1 Leetcode Easy Problems/Leetcode 205 Isomorphic Strings.java new file mode 100644 index 0000000..5021775 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 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 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 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/src/in/knowledgegate/dsa/sorting/problems/CountElements.java b/1 Leetcode Easy Problems/Leetcode 2148 Count Elements With Strictly Smaller and Greater Elements .java similarity index 90% rename from src/in/knowledgegate/dsa/sorting/problems/CountElements.java rename to 1 Leetcode Easy Problems/Leetcode 2148 Count Elements With Strictly Smaller and Greater Elements .java index 1af9b2e..27131ed 100644 --- a/src/in/knowledgegate/dsa/sorting/problems/CountElements.java +++ b/1 Leetcode Easy Problems/Leetcode 2148 Count Elements With Strictly Smaller and Greater Elements .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/1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate using Hashmap.java b/1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate using Hashmap.java new file mode 100644 index 0000000..55f8e35 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate using Hashmap.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 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/src/in/knowledgegate/dsa/slidingwindow/ContainsDuplicate2.java b/1 Leetcode Easy Problems/Leetcode 219 Contains Duplicate II.java similarity index 86% rename from src/in/knowledgegate/dsa/slidingwindow/ContainsDuplicate2.java rename to 1 Leetcode Easy Problems/Leetcode 219 Contains Duplicate II.java index bc49eac..fd8dc3d 100644 --- a/src/in/knowledgegate/dsa/slidingwindow/ContainsDuplicate2.java +++ b/1 Leetcode Easy Problems/Leetcode 219 Contains Duplicate II.java @@ -1,5 +1,3 @@ -package in.knowledgegate.dsa.slidingwindow; - import java.util.HashSet; import java.util.Set; @@ -26,14 +24,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/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 diff --git a/src/in/knowledgegate/dsa/bfs/InvertBinaryTree.java b/1 Leetcode Easy Problems/Leetcode 226 Invert Binary Tree.java similarity index 69% rename from src/in/knowledgegate/dsa/bfs/InvertBinaryTree.java rename to 1 Leetcode Easy Problems/Leetcode 226 Invert Binary Tree.java index 2d1aed5..d7b810b 100644 --- a/src/in/knowledgegate/dsa/bfs/InvertBinaryTree.java +++ b/1 Leetcode Easy Problems/Leetcode 226 Invert Binary Tree.java @@ -1,15 +1,11 @@ -package in.knowledgegate.dsa.bfs; - -import in.knowledgegate.dsa.binarytree.model.TreeNode; - /** * Given the root of a binary tree, invert the * 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 +19,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/linkedlist/PalindromeLinkedList.java b/1 Leetcode Easy Problems/Leetcode 234 Palindrome Linked List.java similarity index 79% rename from src/in/knowledgegate/dsa/linkedlist/PalindromeLinkedList.java rename to 1 Leetcode Easy Problems/Leetcode 234 Palindrome Linked List.java index 5316eab..5e8da10 100644 --- a/src/in/knowledgegate/dsa/linkedlist/PalindromeLinkedList.java +++ b/1 Leetcode Easy Problems/Leetcode 234 Palindrome Linked List.java @@ -1,7 +1,3 @@ -package in.knowledgegate.dsa.linkedlist; - -import in.knowledgegate.dsa.ListNode; - /** * Given the head of a singly linked list, * return true if it is a palindrome. @@ -20,16 +16,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 +35,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/1 Leetcode Easy Problems/Leetcode 242 Valid Anagram.java b/1 Leetcode Easy Problems/Leetcode 242 Valid Anagram.java new file mode 100644 index 0000000..0eaeda8 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 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/src/in/knowledgegate/dsa/array/RemoveDuplicatesSortedArray.java b/1 Leetcode Easy Problems/Leetcode 26 Remove Duplicates from Sorted Array.java similarity index 93% rename from src/in/knowledgegate/dsa/array/RemoveDuplicatesSortedArray.java rename to 1 Leetcode Easy Problems/Leetcode 26 Remove Duplicates from Sorted Array.java index 391b501..2277f1b 100644 --- a/src/in/knowledgegate/dsa/array/RemoveDuplicatesSortedArray.java +++ b/1 Leetcode Easy Problems/Leetcode 26 Remove Duplicates from Sorted Array.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/bitmanipulation/MissingNumber.java b/1 Leetcode Easy Problems/Leetcode 268 Missing Number.java similarity index 88% rename from src/in/knowledgegate/dsa/bitmanipulation/MissingNumber.java rename to 1 Leetcode Easy Problems/Leetcode 268 Missing Number.java index bd106c1..f21479f 100644 --- a/src/in/knowledgegate/dsa/bitmanipulation/MissingNumber.java +++ b/1 Leetcode Easy Problems/Leetcode 268 Missing Number.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/twopointer/RemoveElement.java b/1 Leetcode Easy Problems/Leetcode 27 Remove Element using Two Pointers.java similarity index 93% rename from src/in/knowledgegate/dsa/twopointer/RemoveElement.java rename to 1 Leetcode Easy Problems/Leetcode 27 Remove Element using Two Pointers.java index 2212416..7d2290f 100644 --- a/src/in/knowledgegate/dsa/twopointer/RemoveElement.java +++ b/1 Leetcode Easy Problems/Leetcode 27 Remove Element using Two Pointers.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/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/src/in/knowledgegate/dsa/binarysearch/problems/FirstBadVersion.java b/1 Leetcode Easy Problems/Leetcode 278 First Bad Version.java similarity index 79% rename from src/in/knowledgegate/dsa/binarysearch/problems/FirstBadVersion.java rename to 1 Leetcode Easy Problems/Leetcode 278 First Bad Version.java index d057418..9fc3ba4 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/FirstBadVersion.java +++ b/1 Leetcode Easy Problems/Leetcode 278 First Bad Version.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarysearch.problems; /** * You are a product manager and currently leading @@ -34,36 +33,36 @@ * 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) { - 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) { for (int i = 1; i < n; i++) { - if (isBadVersion(i)) return i; + if (isBadVersion(i)) + return i; } return -1; } 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/src/in/knowledgegate/dsa/twopointer/MoveZeros.java b/1 Leetcode Easy Problems/Leetcode 283 Move Zeroes.java similarity index 58% rename from src/in/knowledgegate/dsa/twopointer/MoveZeros.java rename to 1 Leetcode Easy Problems/Leetcode 283 Move Zeroes.java index 9ff119d..ae45e43 100644 --- a/src/in/knowledgegate/dsa/twopointer/MoveZeros.java +++ b/1 Leetcode Easy Problems/Leetcode 283 Move Zeroes.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.twopointer; import java.util.Arrays; @@ -22,21 +21,24 @@ * 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++) { - if (nums[i] != 0) { - nums[prev++] = nums[i]; - nums[i] = 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]; // 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/1 Leetcode Easy Problems/Leetcode 290 Word Pattern.java b/1 Leetcode Easy Problems/Leetcode 290 Word Pattern.java new file mode 100644 index 0000000..78f115e --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 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/src/in/knowledgegate/dsa/strings/ReverseString.java b/1 Leetcode Easy Problems/Leetcode 344 Reverse String.java similarity index 90% rename from src/in/knowledgegate/dsa/strings/ReverseString.java rename to 1 Leetcode Easy Problems/Leetcode 344 Reverse String.java index 47db6aa..8433b35 100644 --- a/src/in/knowledgegate/dsa/strings/ReverseString.java +++ b/1 Leetcode Easy Problems/Leetcode 344 Reverse String.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/1 Leetcode Easy Problems/Leetcode 345 Reverse Vowels of a String.java b/1 Leetcode Easy Problems/Leetcode 345 Reverse Vowels of a String.java new file mode 100644 index 0000000..f496632 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 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/src/in/knowledgegate/dsa/hashingAndMaps/IntersectionOfTwoArrays.java b/1 Leetcode Easy Problems/Leetcode 349 Intersection of Two Arrays.java similarity index 91% rename from src/in/knowledgegate/dsa/hashingAndMaps/IntersectionOfTwoArrays.java rename to 1 Leetcode Easy Problems/Leetcode 349 Intersection of Two Arrays.java index 51844d1..346e46c 100644 --- a/src/in/knowledgegate/dsa/hashingAndMaps/IntersectionOfTwoArrays.java +++ b/1 Leetcode Easy Problems/Leetcode 349 Intersection of Two Arrays.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/binarysearch/problems/SearchInsertPosition.java b/1 Leetcode Easy Problems/Leetcode 35 Search Insert Position using Binary Search.java similarity index 92% rename from src/in/knowledgegate/dsa/binarysearch/problems/SearchInsertPosition.java rename to 1 Leetcode Easy Problems/Leetcode 35 Search Insert Position using Binary Search.java index 29f432b..178e440 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/SearchInsertPosition.java +++ b/1 Leetcode Easy Problems/Leetcode 35 Search Insert Position using Binary Search.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/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/src/in/knowledgegate/dsa/hashingAndMaps/IntersectionOfTwoArrays2.java b/1 Leetcode Easy Problems/Leetcode 350 Intersection of Two Arrays II.java similarity index 93% rename from src/in/knowledgegate/dsa/hashingAndMaps/IntersectionOfTwoArrays2.java rename to 1 Leetcode Easy Problems/Leetcode 350 Intersection of Two Arrays II.java index 2c56386..2ab9dd2 100644 --- a/src/in/knowledgegate/dsa/hashingAndMaps/IntersectionOfTwoArrays2.java +++ b/1 Leetcode Easy Problems/Leetcode 350 Intersection of Two Arrays II.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/binarysearch/problems/GuessNumberHigherOrLower.java b/1 Leetcode Easy Problems/Leetcode 374 Guess Number Higher or Lower.java similarity index 73% rename from src/in/knowledgegate/dsa/binarysearch/problems/GuessNumberHigherOrLower.java rename to 1 Leetcode Easy Problems/Leetcode 374 Guess Number Higher or Lower.java index 2f0a5c2..17fc657 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/GuessNumberHigherOrLower.java +++ b/1 Leetcode Easy Problems/Leetcode 374 Guess Number Higher or Lower.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(); @@ -48,28 +46,34 @@ 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; } 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/1 Leetcode Easy Problems/Leetcode 383 Ransom Note.java b/1 Leetcode Easy Problems/Leetcode 383 Ransom Note.java new file mode 100644 index 0000000..1b47d23 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 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 diff --git a/1 Leetcode Easy Problems/Leetcode 387 First Unique Character in a String.java b/1 Leetcode Easy Problems/Leetcode 387 First Unique Character in a String.java new file mode 100644 index 0000000..cdc5942 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 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/src/in/knowledgegate/dsa/bitmanipulation/FindTheDifference.java b/1 Leetcode Easy Problems/Leetcode 389 Find the Difference.java similarity index 85% rename from src/in/knowledgegate/dsa/bitmanipulation/FindTheDifference.java rename to 1 Leetcode Easy Problems/Leetcode 389 Find the Difference.java index 2abac86..95aff04 100644 --- a/src/in/knowledgegate/dsa/bitmanipulation/FindTheDifference.java +++ b/1 Leetcode Easy Problems/Leetcode 389 Find the Difference.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/1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal using Bit Manipulation.java b/1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal using Bit Manipulation.java new file mode 100644 index 0000000..4112a5b --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal using Bit Manipulation.java @@ -0,0 +1,56 @@ + +/** + * Given an integer num, return a string + * representing its hexadecimal representation. + * For negative integers, two’s complement method + * is used. + * + * All the letters in the answer string should be + * lowercase characters, and there should not be + * any leading zeros in the answer except for the + * zero itself. + * + * Note: You are not allowed to use any built-in + * library method to directly solve this problem. + * + * + * Example 1: + * Input: num = 26 + * Output: "1a" + * + * Example 2: + * Input: num = -1 + * Output: "ffffffff" + * + * Constraints: + * -231 <= num <= 231 - 1 + */ +class ConvertNumberToHexadecimal { + public static void main(String[] args) { + ConvertNumberToHexadecimal converter = new ConvertNumberToHexadecimal(); + System.out.println("Hex num is: " + + converter.toHex(26)); + } + + public String toHex(int num) { + 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(); + + // 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/src/in/knowledgegate/dsa/math/ConvertNumberToHexadecimal.java b/1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal.java similarity index 72% rename from src/in/knowledgegate/dsa/math/ConvertNumberToHexadecimal.java rename to 1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal.java index d0d3d6d..21c8136 100644 --- a/src/in/knowledgegate/dsa/math/ConvertNumberToHexadecimal.java +++ b/1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal.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/AddStrings.java b/1 Leetcode Easy Problems/Leetcode 415 Add Strings.java similarity index 83% rename from src/in/knowledgegate/dsa/math/AddStrings.java rename to 1 Leetcode Easy Problems/Leetcode 415 Add Strings.java index f1c3092..db2afe7 100644 --- a/src/in/knowledgegate/dsa/math/AddStrings.java +++ b/1 Leetcode Easy Problems/Leetcode 415 Add Strings.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/binarysearch/problems/ArrangingCoins.java b/1 Leetcode Easy Problems/Leetcode 441 Arranging Coins.java similarity index 59% rename from src/in/knowledgegate/dsa/binarysearch/problems/ArrangingCoins.java rename to 1 Leetcode Easy Problems/Leetcode 441 Arranging Coins.java index dcf92d7..e52fac6 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/ArrangingCoins.java +++ b/1 Leetcode Easy Problems/Leetcode 441 Arranging Coins.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.binarysearch.problems; /** * You have n coins and you want to build a staircase @@ -24,27 +23,27 @@ * 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; + 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/src/in/knowledgegate/dsa/recursion/Fibonacci.java b/1 Leetcode Easy Problems/Leetcode 509 Fibonacci Number.java similarity index 84% rename from src/in/knowledgegate/dsa/recursion/Fibonacci.java rename to 1 Leetcode Easy Problems/Leetcode 509 Fibonacci Number.java index 2c66979..7bf1b80 100644 --- a/src/in/knowledgegate/dsa/recursion/Fibonacci.java +++ b/1 Leetcode Easy Problems/Leetcode 509 Fibonacci Number.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/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/src/in/knowledgegate/dsa/math/PlusOne.java b/1 Leetcode Easy Problems/Leetcode 66 Plus One using Math.java similarity index 91% rename from src/in/knowledgegate/dsa/math/PlusOne.java rename to 1 Leetcode Easy Problems/Leetcode 66 Plus One using Math.java index f43a4ff..dac75a2 100644 --- a/src/in/knowledgegate/dsa/math/PlusOne.java +++ b/1 Leetcode Easy Problems/Leetcode 66 Plus One using Math.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/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 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/src/in/knowledgegate/dsa/binarysearch/problems/SquareRoot.java b/1 Leetcode Easy Problems/Leetcode 69 Sqrt(x).java similarity index 88% rename from src/in/knowledgegate/dsa/binarysearch/problems/SquareRoot.java rename to 1 Leetcode Easy Problems/Leetcode 69 Sqrt(x).java index 8843182..c098759 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/SquareRoot.java +++ b/1 Leetcode Easy Problems/Leetcode 69 Sqrt(x).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/dynamicprogramming/ClimbingStairs.java b/1 Leetcode Easy Problems/Leetcode 70 Climbing Stairs.java similarity index 86% rename from src/in/knowledgegate/dsa/dynamicprogramming/ClimbingStairs.java rename to 1 Leetcode Easy Problems/Leetcode 70 Climbing Stairs.java index b602386..6b66de7 100644 --- a/src/in/knowledgegate/dsa/dynamicprogramming/ClimbingStairs.java +++ b/1 Leetcode Easy Problems/Leetcode 70 Climbing Stairs.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/binarysearchtree/SearchInBST.java b/1 Leetcode Easy Problems/Leetcode 700 Search in a Binary Search Tree.java similarity index 62% rename from src/in/knowledgegate/dsa/binarysearchtree/SearchInBST.java rename to 1 Leetcode Easy Problems/Leetcode 700 Search in a Binary Search Tree.java index 1fbf246..6d507e2 100644 --- a/src/in/knowledgegate/dsa/binarysearchtree/SearchInBST.java +++ b/1 Leetcode Easy Problems/Leetcode 700 Search in a Binary Search Tree.java @@ -1,7 +1,3 @@ -package in.knowledgegate.dsa.binarysearchtree; - -import in.knowledgegate.dsa.binarytree.model.TreeNode; - /** * You are given the root of a binary search tree * (BST) and an integer val. @@ -12,16 +8,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,13 +30,28 @@ * 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); } 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/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 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 new file mode 100644 index 0000000..8982d69 --- /dev/null +++ b/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Sorting.java @@ -0,0 +1,12 @@ +import java.util.*; + +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]; + } + // 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/src/in/knowledgegate/dsa/sorting/problems/MergeSortedArray.java b/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array.java similarity index 88% rename from src/in/knowledgegate/dsa/sorting/problems/MergeSortedArray.java rename to 1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array.java index 5e44f9c..3b99839 100644 --- a/src/in/knowledgegate/dsa/sorting/problems/MergeSortedArray.java +++ b/1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array.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/array/SurfaceAreaOf3DShapes.java b/1 Leetcode Easy Problems/Leetcode 892 Surface Area of 3D Shapes.java similarity index 65% rename from src/in/knowledgegate/dsa/array/SurfaceAreaOf3DShapes.java rename to 1 Leetcode Easy Problems/Leetcode 892 Surface Area of 3D Shapes.java index b49d58a..04f6385 100644 --- a/src/in/knowledgegate/dsa/array/SurfaceAreaOf3DShapes.java +++ b/1 Leetcode Easy Problems/Leetcode 892 Surface Area of 3D Shapes.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/math/PalindromeNumber.java b/1 Leetcode Easy Problems/Leetcode 9 Palindrome Number.java similarity index 90% rename from src/in/knowledgegate/dsa/math/PalindromeNumber.java rename to 1 Leetcode Easy Problems/Leetcode 9 Palindrome Number.java index 623c82f..a3688d2 100644 --- a/src/in/knowledgegate/dsa/math/PalindromeNumber.java +++ b/1 Leetcode Easy Problems/Leetcode 9 Palindrome Number.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/queue/RecentCounter.java b/1 Leetcode Easy Problems/Leetcode 933 Number of Recent Calls.java similarity index 76% rename from src/in/knowledgegate/dsa/queue/RecentCounter.java rename to 1 Leetcode Easy Problems/Leetcode 933 Number of Recent Calls.java index fca9037..97943b0 100644 --- a/src/in/knowledgegate/dsa/queue/RecentCounter.java +++ b/1 Leetcode Easy Problems/Leetcode 933 Number of Recent Calls.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/sorting/problems/SquaresOfSortedArray.java b/1 Leetcode Easy Problems/Leetcode 977 Squares of a Sorted Array.java similarity index 92% rename from src/in/knowledgegate/dsa/sorting/problems/SquaresOfSortedArray.java rename to 1 Leetcode Easy Problems/Leetcode 977 Squares of a Sorted Array.java index fa55627..ff66f8d 100644 --- a/src/in/knowledgegate/dsa/sorting/problems/SquaresOfSortedArray.java +++ b/1 Leetcode Easy Problems/Leetcode 977 Squares of a Sorted Array.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/graph/FindTheTownJudge.java b/1 Leetcode Easy Problems/Leetcode 997 Find the Town Judge.java similarity index 90% rename from src/in/knowledgegate/dsa/graph/FindTheTownJudge.java rename to 1 Leetcode Easy Problems/Leetcode 997 Find the Town Judge.java index ac11819..790b15e 100644 --- a/src/in/knowledgegate/dsa/graph/FindTheTownJudge.java +++ b/1 Leetcode Easy Problems/Leetcode 997 Find the Town Judge.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/twopointer/ContainerWithMostWater.java b/2 Leetcode Medium Problems/Leetcode 11 Container With Most Water.java similarity index 82% rename from src/in/knowledgegate/dsa/twopointer/ContainerWithMostWater.java rename to 2 Leetcode Medium Problems/Leetcode 11 Container With Most Water.java index bafd76b..7fa1fd9 100644 --- a/src/in/knowledgegate/dsa/twopointer/ContainerWithMostWater.java +++ b/2 Leetcode Medium Problems/Leetcode 11 Container With Most Water.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/sorting/problems/ThreeSum.java b/2 Leetcode Medium Problems/Leetcode 15 3Sum.java similarity index 91% rename from src/in/knowledgegate/dsa/sorting/problems/ThreeSum.java rename to 2 Leetcode Medium Problems/Leetcode 15 3Sum.java index 2a4c82b..45bd344 100644 --- a/src/in/knowledgegate/dsa/sorting/problems/ThreeSum.java +++ b/2 Leetcode Medium Problems/Leetcode 15 3Sum.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/math/RotateArray.java b/2 Leetcode Medium Problems/Leetcode 189 Rotate Array.java similarity index 88% rename from src/in/knowledgegate/dsa/math/RotateArray.java rename to 2 Leetcode Medium Problems/Leetcode 189 Rotate Array.java index c4d4626..cada5fd 100644 --- a/src/in/knowledgegate/dsa/math/RotateArray.java +++ b/2 Leetcode Medium Problems/Leetcode 189 Rotate Array.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/math/CountPrimes.java b/2 Leetcode Medium Problems/Leetcode 204 Count Primes.java similarity index 80% rename from src/in/knowledgegate/dsa/math/CountPrimes.java rename to 2 Leetcode Medium Problems/Leetcode 204 Count Primes.java index 0f37983..9695090 100644 --- a/src/in/knowledgegate/dsa/math/CountPrimes.java +++ b/2 Leetcode Medium Problems/Leetcode 204 Count Primes.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/sorting/problems/KthLargestElement.java b/2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array using Sorting.java similarity index 77% rename from src/in/knowledgegate/dsa/sorting/problems/KthLargestElement.java rename to 2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array using Sorting.java index 285eaf5..04b4a00 100644 --- a/src/in/knowledgegate/dsa/sorting/problems/KthLargestElement.java +++ b/2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array using Sorting.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/heap/KthLargestElement.java b/2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array.java similarity index 76% rename from src/in/knowledgegate/dsa/heap/KthLargestElement.java rename to 2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array.java index 90f4495..ad9eca6 100644 --- a/src/in/knowledgegate/dsa/heap/KthLargestElement.java +++ b/2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array.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/backtracking/GenerateParentheses.java b/2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses using Backtracking.java similarity index 75% rename from src/in/knowledgegate/dsa/backtracking/GenerateParentheses.java rename to 2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses using Backtracking.java index cff5f82..3ff3637 100644 --- a/src/in/knowledgegate/dsa/backtracking/GenerateParentheses.java +++ b/2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses using Backtracking.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/src/in/knowledgegate/dsa/strings/GenerateParentheses.java b/2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses.java similarity index 82% rename from src/in/knowledgegate/dsa/strings/GenerateParentheses.java rename to 2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses.java index f82427a..2542cc1 100644 --- a/src/in/knowledgegate/dsa/strings/GenerateParentheses.java +++ b/2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.strings; import java.util.ArrayList; import java.util.List; @@ -19,21 +18,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 +59,8 @@ private boolean isValid(char[] current) { } else { counter--; } - if (counter < 0) return false; + if (counter < 0) + return false; } return counter == 0; } 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 new file mode 100644 index 0000000..3f1a2a9 --- /dev/null +++ b/2 Leetcode Medium Problems/Leetcode 33 Search in Rotated Sorted Array.java @@ -0,0 +1,34 @@ +class Solution { + public int search(int[] nums, int target) { + int beg = 0, end = nums.length - 1; + + // 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; // pivot must be to the right of mid + } else { + end = mid; // pivot could be at mid, or to the left of mid + } + } + // 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 + pivot) % nums.length; // Adjust mid to account for rotation + + if (nums[realMid] == target) { + return realMid; + } else if (nums[realMid] < target) { + beg = mid + 1; + } else { + end = mid - 1; + } + } + return -1; + } +} diff --git a/src/in/knowledgegate/dsa/array/ValidSudoku.java b/2 Leetcode Medium Problems/Leetcode 36 Valid Sudoku.java similarity index 60% rename from src/in/knowledgegate/dsa/array/ValidSudoku.java rename to 2 Leetcode Medium Problems/Leetcode 36 Valid Sudoku.java index 9846228..bcb316b 100644 --- a/src/in/knowledgegate/dsa/array/ValidSudoku.java +++ b/2 Leetcode Medium Problems/Leetcode 36 Valid Sudoku.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/array/MaximumSubArray.java b/2 Leetcode Medium Problems/Leetcode 53 Maximum Subarray.java similarity index 92% rename from src/in/knowledgegate/dsa/array/MaximumSubArray.java rename to 2 Leetcode Medium Problems/Leetcode 53 Maximum Subarray.java index 3a9e195..6211ac9 100644 --- a/src/in/knowledgegate/dsa/array/MaximumSubArray.java +++ b/2 Leetcode Medium Problems/Leetcode 53 Maximum Subarray.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/binarysearch/problems/SingleElementInASortedArray.java b/2 Leetcode Medium Problems/Leetcode 540 Single Element in a Sorted Array.java similarity index 66% rename from src/in/knowledgegate/dsa/binarysearch/problems/SingleElementInASortedArray.java rename to 2 Leetcode Medium Problems/Leetcode 540 Single Element in a Sorted Array.java index d6e18c8..82323a9 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/SingleElementInASortedArray.java +++ b/2 Leetcode Medium Problems/Leetcode 540 Single Element in a Sorted Array.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/SearchIn2DMatrix.java b/2 Leetcode Medium Problems/Leetcode 74 Search a 2D Matrix.java similarity index 78% rename from src/in/knowledgegate/dsa/binarysearch/problems/SearchIn2DMatrix.java rename to 2 Leetcode Medium Problems/Leetcode 74 Search a 2D Matrix.java index d1e6521..1855494 100644 --- a/src/in/knowledgegate/dsa/binarysearch/problems/SearchIn2DMatrix.java +++ b/2 Leetcode Medium Problems/Leetcode 74 Search a 2D Matrix.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/dynamicprogramming/Subsets.java b/2 Leetcode Medium Problems/Leetcode 78 Subsets using Dynamic Programming.java similarity index 85% rename from src/in/knowledgegate/dsa/dynamicprogramming/Subsets.java rename to 2 Leetcode Medium Problems/Leetcode 78 Subsets using Dynamic Programming.java index b913b90..4386069 100644 --- a/src/in/knowledgegate/dsa/dynamicprogramming/Subsets.java +++ b/2 Leetcode Medium Problems/Leetcode 78 Subsets using Dynamic Programming.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/backtracking/Subsets.java b/2 Leetcode Medium Problems/Leetcode 78 Subsets.java similarity index 89% rename from src/in/knowledgegate/dsa/backtracking/Subsets.java rename to 2 Leetcode Medium Problems/Leetcode 78 Subsets.java index c87f0f8..f29ca3c 100644 --- a/src/in/knowledgegate/dsa/backtracking/Subsets.java +++ b/2 Leetcode Medium Problems/Leetcode 78 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/src/in/knowledgegate/dsa/backtracking/NQueen.java b/3 Leetcode Hard Problems/Leetcode 51 N-Queens.java similarity index 81% rename from src/in/knowledgegate/dsa/backtracking/NQueen.java rename to 3 Leetcode Hard Problems/Leetcode 51 N-Queens.java index 599190b..f79ea99 100644 --- a/src/in/knowledgegate/dsa/backtracking/NQueen.java +++ b/3 Leetcode Hard Problems/Leetcode 51 N-Queens.java @@ -1,4 +1,3 @@ -package in.knowledgegate.dsa.backtracking; import java.util.Scanner; @@ -27,7 +26,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 +38,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 +46,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 +70,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 +93,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/4 Other Problems/ArrayCopy.java similarity index 68% rename from src/in/knowledgegate/dsa/complexity/ArrayCopy.java rename to 4 Other Problems/ArrayCopy.java index 665b1e5..1c2c518 100644 --- a/src/in/knowledgegate/dsa/complexity/ArrayCopy.java +++ b/4 Other Problems/ArrayCopy.java @@ -1,9 +1,8 @@ -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 +12,4 @@ private static int[] copy(int[] array) { } return newCopy; } -} +} \ No newline at end of file diff --git a/src/in/knowledgegate/dsa/complexity/ArraySum.java b/4 Other Problems/ArraySum.java similarity index 55% rename from src/in/knowledgegate/dsa/complexity/ArraySum.java rename to 4 Other Problems/ArraySum.java index 27a6931..378bd5d 100644 --- a/src/in/knowledgegate/dsa/complexity/ArraySum.java +++ b/4 Other Problems/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/binarysearch/algos/BinarySearch.java b/4 Other Problems/BinarySearch.java similarity index 86% rename from src/in/knowledgegate/dsa/binarysearch/algos/BinarySearch.java rename to 4 Other Problems/BinarySearch.java index da813d3..bad1216 100644 --- a/src/in/knowledgegate/dsa/binarysearch/algos/BinarySearch.java +++ b/4 Other Problems/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/sorting/algos/BubbleSort.java b/4 Other Problems/BubbleSort.java similarity index 76% rename from src/in/knowledgegate/dsa/sorting/algos/BubbleSort.java rename to 4 Other Problems/BubbleSort.java index 74fdd5c..925c45c 100644 --- a/src/in/knowledgegate/dsa/sorting/algos/BubbleSort.java +++ b/4 Other Problems/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/recursion/Factorial.java b/4 Other Problems/Factorial.java similarity index 57% rename from src/in/knowledgegate/dsa/recursion/Factorial.java rename to 4 Other Problems/Factorial.java index 86b3265..1ced49e 100644 --- a/src/in/knowledgegate/dsa/recursion/Factorial.java +++ b/4 Other Problems/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/sorting/algos/InsertionSort.java b/4 Other Problems/InsertionSort.java similarity index 64% rename from src/in/knowledgegate/dsa/sorting/algos/InsertionSort.java rename to 4 Other Problems/InsertionSort.java index 8cd6597..360ace8 100644 --- a/src/in/knowledgegate/dsa/sorting/algos/InsertionSort.java +++ b/4 Other Problems/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/ListNode.java b/4 Other Problems/ListNode.java similarity index 71% rename from src/in/knowledgegate/dsa/ListNode.java rename to 4 Other Problems/ListNode.java index e571e72..a531a80 100644 --- a/src/in/knowledgegate/dsa/ListNode.java +++ b/4 Other Problems/ListNode.java @@ -1,14 +1,15 @@ -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/sorting/algos/MergeSort.java b/4 Other Problems/MergeSort.java similarity index 88% rename from src/in/knowledgegate/dsa/sorting/algos/MergeSort.java rename to 4 Other Problems/MergeSort.java index dd29ec0..fd0fe51 100644 --- a/src/in/knowledgegate/dsa/sorting/algos/MergeSort.java +++ b/4 Other Problems/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/hashingAndMaps/MiniMahjongWinningHand.java b/4 Other Problems/MiniMahjongWinningHand.java similarity index 65% rename from src/in/knowledgegate/dsa/hashingAndMaps/MiniMahjongWinningHand.java rename to 4 Other Problems/MiniMahjongWinningHand.java index 11f0d4b..61ced0b 100644 --- a/src/in/knowledgegate/dsa/hashingAndMaps/MiniMahjongWinningHand.java +++ b/4 Other Problems/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/greedy/MiniMahjongWinningHand2.java b/4 Other Problems/MiniMahjongWinningHand2.java similarity index 52% rename from src/in/knowledgegate/dsa/greedy/MiniMahjongWinningHand2.java rename to 4 Other Problems/MiniMahjongWinningHand2.java index 784501b..14c0ee4 100644 --- a/src/in/knowledgegate/dsa/greedy/MiniMahjongWinningHand2.java +++ b/4 Other Problems/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/sorting/algos/QuickSort.java b/4 Other Problems/QuickSort.java similarity index 83% rename from src/in/knowledgegate/dsa/sorting/algos/QuickSort.java rename to 4 Other Problems/QuickSort.java index 6dc761f..d68902d 100644 --- a/src/in/knowledgegate/dsa/sorting/algos/QuickSort.java +++ b/4 Other Problems/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/dynamicprogramming/RodCutting.java b/4 Other Problems/RodCutting.java similarity index 81% rename from src/in/knowledgegate/dsa/dynamicprogramming/RodCutting.java rename to 4 Other Problems/RodCutting.java index 8e43f66..41800a5 100644 --- a/src/in/knowledgegate/dsa/dynamicprogramming/RodCutting.java +++ b/4 Other Problems/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/sorting/algos/SelectionSort.java b/4 Other Problems/SelectionSort.java similarity index 84% rename from src/in/knowledgegate/dsa/sorting/algos/SelectionSort.java rename to 4 Other Problems/SelectionSort.java index c1f2099..6944483 100644 --- a/src/in/knowledgegate/dsa/sorting/algos/SelectionSort.java +++ b/4 Other Problems/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/4 Other Problems/Solitaire.java b/4 Other Problems/Solitaire.java new file mode 100644 index 0000000..ddbdb80 --- /dev/null +++ b/4 Other Problems/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/sorting/algos/SortingAlgo.java b/4 Other Problems/SortingAlgo.java similarity index 57% rename from src/in/knowledgegate/dsa/sorting/algos/SortingAlgo.java rename to 4 Other Problems/SortingAlgo.java index 561e42e..4651408 100644 --- a/src/in/knowledgegate/dsa/sorting/algos/SortingAlgo.java +++ b/4 Other Problems/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/complexity/Sum.java b/4 Other Problems/Sum.java similarity index 78% rename from src/in/knowledgegate/dsa/complexity/Sum.java rename to 4 Other Problems/Sum.java index 2d89ac1..11d7e73 100644 --- a/src/in/knowledgegate/dsa/complexity/Sum.java +++ b/4 Other Problems/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/4 Other Problems/TreeNode.java b/4 Other Problems/TreeNode.java new file mode 100644 index 0000000..32d99ea --- /dev/null +++ b/4 Other Problems/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 diff --git a/README.md b/README.md index dd26188..4c0bbcf 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,5 @@ -# DSA -Data Structures and Algorithms +# DSA using Java + +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) 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/binarysearch/problems/SearchInRotatedSortedArray.java b/src/in/knowledgegate/dsa/binarysearch/problems/SearchInRotatedSortedArray.java deleted file mode 100644 index 3219113..0000000 --- a/src/in/knowledgegate/dsa/binarysearch/problems/SearchInRotatedSortedArray.java +++ /dev/null @@ -1,79 +0,0 @@ -package in.knowledgegate.dsa.binarysearch.problems; - -/** - * 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 - */ -public 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) { - int beg = 0, end = nums.length - 1; - while (beg <= end) { - int mid = (beg + end) / 2; - if (nums[mid] > nums[end]) - beg = mid + 1; - else - end = mid - 1; - } - int shift = end + 1; - - beg = 0; - end = nums.length - 1; - while(beg <= end) { - int mid = (beg + end) / 2; - int realMid = - (mid + shift) % nums.length; - if (nums[realMid] == target) - return realMid; - else if (nums[realMid] < target) - beg = mid + 1; - else - end = mid - 1; - } - return -1; - } -} diff --git a/src/in/knowledgegate/dsa/binarytree/model/TreeNode.java b/src/in/knowledgegate/dsa/binarytree/model/TreeNode.java deleted file mode 100644 index c2d7235..0000000 --- a/src/in/knowledgegate/dsa/binarytree/model/TreeNode.java +++ /dev/null @@ -1,14 +0,0 @@ -package in.knowledgegate.dsa.binarytree.model; - -public class TreeNode { - public int val; - public TreeNode left; - public 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/src/in/knowledgegate/dsa/bitmanipulation/ConvertNumberToHexadecimal.java b/src/in/knowledgegate/dsa/bitmanipulation/ConvertNumberToHexadecimal.java deleted file mode 100644 index 0e8cc62..0000000 --- a/src/in/knowledgegate/dsa/bitmanipulation/ConvertNumberToHexadecimal.java +++ /dev/null @@ -1,50 +0,0 @@ -package in.knowledgegate.dsa.bitmanipulation; - -/** - * Given an integer num, return a string - * representing its hexadecimal representation. - * For negative integers, two’s complement method - * is used. - * - * All the letters in the answer string should be - * lowercase characters, and there should not be - * any leading zeros in the answer except for the - * zero itself. - * - * Note: You are not allowed to use any built-in - * library method to directly solve this problem. - * - * - * Example 1: - * Input: num = 26 - * Output: "1a" - * - * Example 2: - * Input: num = -1 - * Output: "ffffffff" - * - * Constraints: - * -231 <= num <= 231 - 1 - */ -public class ConvertNumberToHexadecimal { - public static void main(String[] args) { - ConvertNumberToHexadecimal converter = - new ConvertNumberToHexadecimal(); - System.out.println("Hex num is: " - + 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"; - StringBuilder result = new StringBuilder(); - while (num > 0) { - int endBits = num & 15; - result.insert(0, mapping[endBits]); - num = num >> 4; - } - return result.toString(); - } -} 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/greedy/BestTimeToBuyAndSellStock.java b/src/in/knowledgegate/dsa/greedy/BestTimeToBuyAndSellStock.java deleted file mode 100644 index 6bfe166..0000000 --- a/src/in/knowledgegate/dsa/greedy/BestTimeToBuyAndSellStock.java +++ /dev/null @@ -1,50 +0,0 @@ -package in.knowledgegate.dsa.greedy; - -/** - * 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 - */ -public 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/src/in/knowledgegate/dsa/linkedlist/MergeTwoSortedList.java b/src/in/knowledgegate/dsa/linkedlist/MergeTwoSortedList.java deleted file mode 100644 index 703ffc4..0000000 --- a/src/in/knowledgegate/dsa/linkedlist/MergeTwoSortedList.java +++ /dev/null @@ -1,58 +0,0 @@ -package in.knowledgegate.dsa.linkedlist; - -/** - * 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. - */ -public 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; - } -} -