├── .gitignore ├── 1 Leetcode Easy Problems ├── LeetCode 94 Binary Tree Inorder Traversal using Iteration.java ├── LeetCode 94 Binary Tree Inorder Traversal using Recursion.java ├── Leetcode 1 Two Sum using Hashmap.java ├── Leetcode 1 TwoSum.java ├── Leetcode 112 Path Sum.java ├── Leetcode 118 Pascal's Triangle using Linkedlist.java ├── Leetcode 118 Pascal's Triangle using Recursion.java ├── Leetcode 118 Pascal's Triangle.java ├── Leetcode 118 Pascals Triangle using Dynamic Programming.java ├── Leetcode 121 Best Time to Buy and Sell Stock using Greedy.java ├── Leetcode 121 Best Time to Buy and Sell Stock.java ├── Leetcode 125 Valid Palindrome.java ├── Leetcode 13 Roman to Integer using Array.java ├── Leetcode 13 Roman to Integer using Hashmap.java ├── Leetcode 13 Roman to Integer using Math.java ├── Leetcode 136 Single Number.java ├── Leetcode 14 Longest Common Prefix.java ├── Leetcode 141 Linked List Cycle.java ├── Leetcode 144 Binary Tree Preorder Traversal using Iterative - Java Video Solution.java ├── Leetcode 144 Binary Tree Preorder Traversal using Recursion - Java Video Solution.java ├── Leetcode 145 Binary Tree Postorder Traversal using Iteration.java ├── Leetcode 145 Binary Tree Postorder Traversal using Recursion.java ├── Leetcode 160 Intersection of Two Linked Lists.java ├── Leetcode 168 Excel Sheet Column Title.java ├── Leetcode 169 Majority Element using Bit Manipulation.java ├── Leetcode 169 Majority Element using Hashmap.java ├── Leetcode 169 Majority Element using Sorting.java ├── Leetcode 171 Excel Sheet Column Number using Math.java ├── Leetcode 171 Excel Sheet Column Number.java ├── Leetcode 190 Reverse Bits.java ├── Leetcode 191 Number of 1 Bits.java ├── Leetcode 20 Valid Parentheses.java ├── Leetcode 202 Happy Number.java ├── Leetcode 203 Remove Linked List Elements.java ├── Leetcode 205 Isomorphic Strings.java ├── Leetcode 206 Reverse Linked List.java ├── Leetcode 21 Merge Two Sorted Lists.java ├── Leetcode 2148 Count Elements With Strictly Smaller and Greater Elements .java ├── Leetcode 217 Contains Duplicate using Hashmap.java ├── Leetcode 217 Contains Duplicate using sorting.java ├── Leetcode 219 Contains Duplicate II.java ├── Leetcode 222 Count Complete Tree Nodes.java ├── Leetcode 226 Invert Binary Tree.java ├── Leetcode 234 Palindrome Linked List.java ├── Leetcode 242 Valid Anagram.java ├── Leetcode 26 Remove Duplicates from Sorted Array.java ├── Leetcode 268 Missing Number.java ├── Leetcode 27 Remove Element using Two Pointers.java ├── Leetcode 27 Remove Element.java ├── Leetcode 278 First Bad Version.java ├── Leetcode 28 Find the Index of the First Occurrence in a String.java ├── Leetcode 283 Move Zeroes.java ├── Leetcode 290 Word Pattern.java ├── Leetcode 344 Reverse String.java ├── Leetcode 345 Reverse Vowels of a String.java ├── Leetcode 349 Intersection of Two Arrays.java ├── Leetcode 35 Search Insert Position using Binary Search.java ├── Leetcode 35 Search Insert Position.java ├── Leetcode 350 Intersection of Two Arrays II.java ├── Leetcode 374 Guess Number Higher or Lower.java ├── Leetcode 383 Ransom Note.java ├── Leetcode 387 First Unique Character in a String.java ├── Leetcode 389 Find the Difference.java ├── Leetcode 405 Convert a Number to Hexadecimal using Bit Manipulation.java ├── Leetcode 405 Convert a Number to Hexadecimal.java ├── Leetcode 415 Add Strings.java ├── Leetcode 441 Arranging Coins.java ├── Leetcode 509 Fibonacci Number.java ├── Leetcode 58 Length of Last Word.java ├── Leetcode 66 Plus One using Math.java ├── Leetcode 66 Plus One.java ├── Leetcode 67 Add Binary.java ├── Leetcode 69 Sqrt(x).java ├── Leetcode 70 Climbing Stairs.java ├── Leetcode 700 Search in a Binary Search Tree.java ├── Leetcode 83 Remove Duplicates from Sorted List.java ├── Leetcode 88 Merge Sorted Array using Sorting.java ├── Leetcode 88 Merge Sorted Array using Two Pointers.java ├── Leetcode 88 Merge Sorted Array.java ├── Leetcode 892 Surface Area of 3D Shapes.java ├── Leetcode 9 Palindrome Number.java ├── Leetcode 933 Number of Recent Calls.java ├── Leetcode 977 Squares of a Sorted Array.java └── Leetcode 997 Find the Town Judge.java ├── 2 Leetcode Medium Problems ├── Leetcode 11 Container With Most Water.java ├── Leetcode 15 3Sum.java ├── Leetcode 189 Rotate Array.java ├── Leetcode 204 Count Primes.java ├── Leetcode 215 Kth Largest Element in an Array using Sorting.java ├── Leetcode 215 Kth Largest Element in an Array.java ├── Leetcode 22 Generate Parentheses using Backtracking.java ├── Leetcode 22 Generate Parentheses.java ├── Leetcode 33 Search in Rotated Sorted Array.java ├── Leetcode 36 Valid Sudoku.java ├── Leetcode 53 Maximum Subarray.java ├── Leetcode 540 Single Element in a Sorted Array.java ├── Leetcode 74 Search a 2D Matrix.java ├── Leetcode 78 Subsets using Dynamic Programming.java └── Leetcode 78 Subsets.java ├── 3 Leetcode Hard Problems └── Leetcode 51 N-Queens.java ├── 4 Other Problems ├── ArrayCopy.java ├── ArraySum.java ├── BinarySearch.java ├── BubbleSort.java ├── Factorial.java ├── InsertionSort.java ├── ListNode.java ├── MergeSort.java ├── MiniMahjongWinningHand.java ├── MiniMahjongWinningHand2.java ├── QuickSort.java ├── RodCutting.java ├── SelectionSort.java ├── Solitaire.java ├── SortingAlgo.java ├── Sum.java └── TreeNode.java └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | .idea/ 26 | *.iml 27 | build/ 28 | out/ 29 | .DS_Store 30 | 31 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Iteration.java: -------------------------------------------------------------------------------- 1 | 2 | import in.knowledgegate.dsa.binarytree.model.TreeNode; 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.Stack; 7 | 8 | /** 9 | * Write Inorder traversal of a binary tree using 10 | * iterative approach 11 | */ 12 | class InorderTraversalIterative { 13 | public List inorderTraversal(TreeNode root) { 14 | Stack stack = new Stack<>(); 15 | List result = new ArrayList<>(); 16 | TreeNode curr = root; 17 | 18 | while (curr != null || !stack.isEmpty()) { 19 | while (curr != null) { 20 | stack.push(curr); 21 | curr = curr.left; 22 | } 23 | curr = stack.pop(); 24 | result.add(curr.val); 25 | curr = curr.right; 26 | } 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/LeetCode 94 Binary Tree Inorder Traversal using Recursion.java: -------------------------------------------------------------------------------- 1 | 2 | import in.knowledgegate.dsa.binarytree.model.TreeNode; 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | /** 8 | * Write Inorder traversal of a binary tree using 9 | * recursive approach 10 | */ 11 | class InorderTraversalRecursive { 12 | public List inorderTraversal(TreeNode root) { 13 | List result = new ArrayList<>(); 14 | inorderTraversal(root, result); 15 | return result; 16 | } 17 | 18 | private void inorderTraversal(TreeNode root, 19 | List result) { 20 | if (root == null) 21 | return; 22 | inorderTraversal(root.left, result); 23 | result.add(root.val); 24 | inorderTraversal(root.right, result); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 1 Two Sum using Hashmap.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashMap; 3 | import java.util.Map; 4 | 5 | /** 6 | * Given an array of integers nums and an integer target, return indices of the 7 | * two numbers such that they add up to target. You may assume that each input 8 | * would have exactly one solution, and you may not use the same element twice. 9 | * You can return the answer in any order. 10 | *

11 | * Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: 12 | * Because nums[0] + nums[1] == 9, we return [0, 1]. 13 | *

14 | * Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] 15 | *

16 | * Example 3: Input: nums = [3,3], target = 6 Output: [0,1] 17 | *

18 | *

19 | * Constraints: 2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= 20 | * 109 Only one valid answer exists. 21 | */ 22 | class TwoSum { 23 | public int[] twoSum(int[] nums, int target) { 24 | Map map = new HashMap<>(); 25 | for (int i = 0; i < nums.length; i++) { 26 | map.put(nums[i], i); 27 | } 28 | 29 | for (int i = 0; i < nums.length; i++) { 30 | int num = target - nums[i]; 31 | int result = map.getOrDefault(num, -1); 32 | if (result >= 0 && result != i) { 33 | return new int[] { i, result }; 34 | } 35 | } 36 | 37 | throw new IllegalArgumentException("invalid input"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 1 TwoSum.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given an array of integers nums and an integer 4 | * target, return indices of the two numbers such 5 | * that they add up to target. You may assume that 6 | * each input would have exactly one solution, and 7 | * you may not use the same element twice. You can 8 | * return the answer in any order. 9 | *

10 | * Example 1: Input: nums = [2,7,11,15], target = 11 | * 9 Output: [0,1] Explanation: Because nums[0] + 12 | * nums[1] == 9, we return [0, 1]. 13 | *

14 | * Example 2: Input: nums = [3,2,4], target = 6 15 | * Output: [1,2] 16 | *

17 | * Example 3: Input: nums = [3,3], target = 6 18 | * Output: [0,1] 19 | *

20 | *

21 | * Constraints: 2 <= nums.length <= 104 -109 <= 22 | * nums[i] <= 109 -109 <= target <= 109 Only one 23 | * valid answer exists. 24 | */ 25 | class TwoSum { 26 | public int[] twoSum(int[] nums, int target) { 27 | for (int i = 0; i < nums.length; i++) { 28 | for (int j = i + 1; j < nums.length; j++) { 29 | if (nums[i] + nums[j] == target) { 30 | return new int[] { i, j }; 31 | } 32 | } 33 | } 34 | throw new IllegalArgumentException("Invalid input"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 112 Path Sum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the root of a binary tree and an integer 3 | * targetSum, return true if the tree has a 4 | * root-to-leaf path such that adding up all 5 | * the values along the path equals targetSum. 6 | * 7 | * A leaf is a node with no children. 8 | * 9 | * Example 1: 10 | * 1 11 | * 2 3 12 | * 13 | * Input: root = [1,2,3], targetSum = 5 14 | * Output: false 15 | * Explanation: There two root-to-leaf paths in the tree: 16 | * (1 --> 2): The sum is 3. 17 | * (1 --> 3): The sum is 4. 18 | * There is no root-to-leaf path with sum = 5. 19 | * 20 | * Input: root = [1,2,3], targetSum = 3 21 | * Output: true 22 | * 23 | * Example 2: 24 | * Input: root = [], targetSum = 0 25 | * Output: false 26 | * Explanation: Since the tree is empty, there 27 | * are no root-to-leaf paths. 28 | * 29 | * 30 | * Constraints: 31 | * The number of nodes in the tree is in the 32 | * range [0, 5000]. 33 | * -1000 <= Node.val <= 1000 34 | * -1000 <= targetSum <= 1000 35 | */ 36 | class PathSum { 37 | public boolean hasPathSum(TreeNode root, int targetSum) { 38 | if (root == null) 39 | return false; 40 | if (root.val == targetSum && isLeaf(root)) 41 | return true; 42 | int newTargetSum = targetSum - root.val; 43 | return hasPathSum(root.left, newTargetSum) || 44 | hasPathSum(root.right, newTargetSum); 45 | } 46 | 47 | private boolean isLeaf(TreeNode node) { 48 | return node != null && node.left == null 49 | && node.right == null; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle using Linkedlist.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | /** 6 | * Given an integer numRows, return the first 7 | * numRows of Pascal's triangle. In Pascal's 8 | * triangle, each number is the sum of the two 9 | * numbers directly above it as shown. 10 | * 11 | * 1 12 | * 1 1 13 | * 1 2 1 14 | * 1 3 3 1 15 | * 1 4 6 4 1 16 | * 1 5 10 10 5 1 17 | * 18 | * Example 1: Input: numRows = 5 Output: 19 | * [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 20 | *

21 | * Example 2: Input: numRows = 1 Output: [[1]] 22 | *

23 | *

24 | * Constraints: 1 <= numRows <= 30 25 | */ 26 | class PascalTriangle { 27 | public List> generate(int numRows) { 28 | List> result = new ArrayList<>(); 29 | List prev = new ArrayList<>(); 30 | prev.add(1); 31 | result.add(prev); 32 | 33 | for (int i = 1; i < numRows; i++) { 34 | List curr = new ArrayList<>(); 35 | curr.add(1); 36 | for (int j = 1; j < prev.size(); j++) { 37 | int val = prev.get(j) + prev.get(j - 1); 38 | curr.add(val); 39 | } 40 | curr.add(1); 41 | result.add(curr); 42 | prev = curr; 43 | } 44 | return result; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle using Recursion.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public List> generate(int numRows) { 5 | List> result = new ArrayList<>(); 6 | for (int i = 0; i < numRows; i++) { 7 | List genRow = generateRow(i+1); 8 | result.add(genRow); 9 | } 10 | return result; 11 | } 12 | 13 | private List generateRow(int rowNumber) { 14 | if (rowNumber == 1) { 15 | List firstRow = new ArrayList<>(); 16 | firstRow.add(1); 17 | return firstRow; 18 | } 19 | 20 | List currRow = new ArrayList<>(); 21 | List prevRow = generateRow(rowNumber - 1); 22 | 23 | currRow.add(1); 24 | for (int i = 1; i < rowNumber - 1; i++) { 25 | currRow.add(prevRow.get(i-1) + prevRow.get(i)); 26 | } 27 | currRow.add(1); 28 | return currRow; 29 | } 30 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 118 Pascal's Triangle.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | class Solution { 5 | public List> generate(int numRows) { 6 | List> result = new ArrayList<>(); 7 | List firstRow = new ArrayList<>(); 8 | firstRow.add(1); 9 | result.add(firstRow); 10 | 11 | for (int i = 1; i < numRows; i++) { 12 | List newRow = new ArrayList<>(); 13 | newRow.add(1); 14 | 15 | // generating from previous row 16 | List previousRow = result.get(i - 1); 17 | for (int j = 1; j < i; j++) { 18 | int num = previousRow.get(j - 1) + previousRow.get(j); 19 | newRow.add(num); 20 | } 21 | 22 | newRow.add(1); 23 | result.add(newRow); 24 | } 25 | 26 | return result; 27 | } 28 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 118 Pascals Triangle using Dynamic Programming.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public List> generate(int numRows) { 5 | if (numRows == 1) { 6 | List> result = new ArrayList<>(); 7 | List firstRow = new ArrayList<>(); 8 | firstRow.add(1); 9 | result.add(firstRow); 10 | return result; 11 | } 12 | 13 | List> previousRows = generate(numRows - 1); 14 | List lastRow = previousRows.get(numRows - 2); 15 | List newRow = new ArrayList<>(); 16 | newRow.add(1); 17 | 18 | for(int i = 1; i < numRows - 1; i++) { 19 | newRow.add(lastRow.get(i-1) + lastRow.get(i)); 20 | } 21 | newRow.add(1); 22 | previousRows.add(newRow); 23 | return previousRows; 24 | } 25 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock using Greedy.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | int maxProfit = 0; 4 | int minPrice = Integer.MAX_VALUE; 5 | 6 | for (int i = 0; i < prices.length; i++) { 7 | if (minPrice > prices[i]) { 8 | minPrice = prices[i]; 9 | } else { 10 | int profit = prices[i] - minPrice; 11 | if (profit > maxProfit) { 12 | maxProfit = profit; 13 | } 14 | } 15 | } 16 | 17 | return maxProfit; 18 | } 19 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 121 Best Time to Buy and Sell Stock.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProfit(int[] prices) { 3 | int maxProfit = 0; 4 | for (int i = 0; i < prices.length - 1; i++) { 5 | for (int j = i + 1; j < prices.length; j++) { 6 | int profit = prices[j] - prices[i]; 7 | if (profit > maxProfit) { 8 | maxProfit = profit; 9 | } 10 | } 11 | } 12 | return maxProfit; 13 | } 14 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 125 Valid Palindrome.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * A phrase is a palindrome if, after converting all uppercase letters into 4 | * lowercase letters and removing all non-alphanumeric characters, it reads the 5 | * same forward and backward. Alphanumeric characters include letters and 6 | * numbers. Given a string s, return true if it is a palindrome, or false 7 | * otherwise. 8 | *

9 | * Example 1: Input: s = "A man, a plan, a canal: Panama" Output: true 10 | * Explanation: "amanaplanacanalpanama" is a palindrome. 11 | *

12 | * Example 2: Input: s = "race a car" Output: false Explanation: "raceacar" is 13 | * not a palindrome. 14 | *

15 | * Example 3: Input: s = " " Output: true Explanation: s is an empty string "" 16 | * after removing non-alphanumeric characters. Since an empty string reads the 17 | * same forward and backward, it is a palindrome. 18 | *

19 | *

20 | * Constraints: 1 <= s.length <= 2 * 105 s consists only of printable ASCII 21 | * characters. 22 | */ 23 | class ValidPalindrome { 24 | public boolean isPalindrome(String s) { 25 | int beg = 0, end = s.length() - 1; 26 | while (beg < end) { 27 | int left = validChar(s.charAt(beg)); 28 | int right = validChar(s.charAt(end)); 29 | if (left == -1) { 30 | beg++; 31 | } else if (right == -1) { 32 | end--; 33 | } else if (left != right) { 34 | return false; 35 | } else { 36 | beg++; 37 | end--; 38 | } 39 | 40 | } 41 | return true; 42 | } 43 | 44 | private int validChar(char c) { 45 | if (c >= '0' && c <= '9') 46 | return c; 47 | if (c >= 'a' && c <= 'z') 48 | return c; 49 | if (c >= 'A' && c <= 'Z') 50 | return c - 'A' + 'a'; 51 | return -1; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private final String[][] SYMBOLS = new String[][]{ 3 | {"I", "1"}, 4 | {"V", "5"}, 5 | {"X", "10"}, 6 | {"L", "50"}, 7 | {"C", "100"}, 8 | {"D", "500"}, 9 | {"M", "1000"}, 10 | }; 11 | 12 | private int getSymbolValue(char symbol) { 13 | for (String[] row: SYMBOLS) { 14 | if (row[0].equals(symbol + "")) { 15 | return Integer.parseInt(row[1]); 16 | } 17 | } 18 | return 0; 19 | } 20 | 21 | public int romanToInt(String s) { 22 | int result = 0; 23 | for (int i = 0; i < s.length(); i++) { 24 | char current = s.charAt(i); 25 | int currValue = getSymbolValue(current); 26 | 27 | if (i + 1 < s.length()) { 28 | char next = s.charAt(i+1); 29 | int nextVal = getSymbolValue(next); 30 | if (nextVal <= currValue) { 31 | result += currValue; 32 | } else { 33 | result += (nextVal - currValue); 34 | i++; 35 | } 36 | } else { 37 | result += currValue; 38 | } 39 | } 40 | return result; 41 | } 42 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Hashmap.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | private final Map SYMBOLS = new HashMap<>(); 5 | { 6 | SYMBOLS.put('I', 1); 7 | SYMBOLS.put('V', 5); 8 | SYMBOLS.put('X', 10); 9 | SYMBOLS.put('L', 50); 10 | SYMBOLS.put('C', 100); 11 | SYMBOLS.put('D', 500); 12 | SYMBOLS.put('M', 1000); 13 | } 14 | 15 | public int romanToInt(String roman) { 16 | int result = 0; 17 | for (int i = 0; i < roman.length(); i++) { 18 | char current = roman.charAt(i); 19 | int currValue = SYMBOLS.get(current); 20 | int nextValue = 0; 21 | 22 | if (i + 1 < roman.length()) { 23 | char nextChar = roman.charAt(i+1); 24 | nextValue = SYMBOLS.get(nextChar); 25 | } 26 | 27 | if (nextValue > currValue) { 28 | result += (nextValue - currValue); 29 | i++; 30 | } else { 31 | result += currValue; 32 | } 33 | } 34 | return result; 35 | } 36 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 13 Roman to Integer using Math.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Roman numerals are represented by seven different 4 | * symbols: I, V, X, L, C, D and M. 5 | * 6 | * Symbol Value 7 | * I 1 8 | * V 5 9 | * X 10 10 | * L 50 11 | * C 100 12 | * D 500 13 | * M 1000 14 | * For example, 2 is written as II in Roman numeral, 15 | * just two one's added together. 12 is written as 16 | * XII, which is simply X + II. The number 27 is 17 | * written as XXVII, which is XX + V + II. 18 | * 19 | * Roman numerals are usually written largest to 20 | * smallest from left to right. However, the numeral 21 | * for four is not IIII. Instead, the number four 22 | * is written as IV. Because the one is before the 23 | * five we subtract it making four. The same 24 | * principle applies to the number nine, which is 25 | * written as IX. There are six instances where 26 | * subtraction is used: 27 | * 28 | * I can be placed before V (5) and X (10) to make 4 and 9. 29 | * X can be placed before L (50) and C (100) to make 40 and 90. 30 | * C can be placed before D (500) and M (1000) to make 400 and 900. 31 | * Given a roman numeral, convert it to an integer. 32 | * 33 | * 34 | * Example 1: 35 | * Input: s = "III" 36 | * Output: 3 37 | * Explanation: III = 3. 38 | * 39 | * Example 2: 40 | * Input: s = "LVIII" 41 | * Output: 58 42 | * Explanation: L = 50, V= 5, III = 3. 43 | * 44 | * Example 3: 45 | * Input: s = "MCMXCIV" 46 | * Output: 1994 47 | * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 48 | * 49 | * 50 | * Constraints: 51 | * 1 <= s.length <= 15 52 | * s contains only the characters 53 | * ('I', 'V', 'X', 'L', 'C', 'D', 'M'). 54 | * It is guaranteed that s is a valid roman 55 | * numeral in the range [1, 3999]. 56 | */ 57 | class RomanToInteger { 58 | public static void main(String[] args) { 59 | RomanToInteger converter = new RomanToInteger(); 60 | System.out.println("III:" + converter.romanToInt("III")); 61 | System.out.println("LVIII:" + converter.romanToInt("LVIII")); 62 | System.out.println("MCMXCIV:" + converter.romanToInt("MCMXCIV")); 63 | } 64 | 65 | public int romanToInt(String s) { 66 | int result = 0; 67 | int i = 0; 68 | s = s + "00"; 69 | 70 | while (true) { 71 | char c = s.charAt(i); 72 | char next = s.charAt(i + 1); 73 | switch (c) { 74 | case 'I': 75 | if (next == 'V') { 76 | result += 4; 77 | i++; 78 | } else if (next == 'X') { 79 | result += 9; 80 | i++; 81 | } else { 82 | result += 1; 83 | } 84 | break; 85 | 86 | case 'X': 87 | if (next == 'L') { 88 | result += 40; 89 | i++; 90 | } else if (next == 'C') { 91 | result += 90; 92 | i++; 93 | } else { 94 | result += 10; 95 | } 96 | break; 97 | 98 | case 'C': 99 | if (next == 'D') { 100 | result += 400; 101 | i++; 102 | } else if (next == 'M') { 103 | result += 900; 104 | i++; 105 | } else { 106 | result += 100; 107 | } 108 | break; 109 | case 'V': 110 | result += 5; 111 | break; 112 | case 'L': 113 | result += 50; 114 | break; 115 | case 'D': 116 | result += 500; 117 | break; 118 | case 'M': 119 | result += 1000; 120 | break; 121 | case '0': 122 | default: 123 | return result; 124 | } 125 | i++; 126 | } 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 136 Single Number.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given a non-empty array of integers nums, 4 | * every element appears twice except for one. 5 | * Find that single one. 6 | * 7 | * You must implement a solution with a linear 8 | * runtime complexity and use only constant extra 9 | * space. 10 | * 11 | * Example 1: 12 | * Input: nums = [2,2,1] 13 | * Output: 1 14 | * 15 | * Example 2: 16 | * Input: nums = [4,1,2,1,2] 17 | * Output: 4 18 | * 19 | * Example 3: 20 | * Input: nums = [1] 21 | * Output: 1 22 | * 23 | * Constraints: 24 | * 1 <= nums.length <= 3 * 104 25 | * -3 * 104 <= nums[i] <= 3 * 104 26 | * Each element in the array appears twice except 27 | * for one element which appears only once. 28 | */ 29 | class SingleNumber { 30 | public int singleNumber(int[] nums) { 31 | int num = 0; 32 | for (int i = 0; i < nums.length; i++) { 33 | num ^= nums[i]; 34 | } 35 | return num; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 14 Longest Common Prefix.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Write a function to find the longest common 4 | * prefix string amongst an array of strings. If 5 | * there is no common prefix, return an empty 6 | * string "". 7 | *

8 | * Example 1: Input: strs = 9 | * ["flower","flow","flight"] Output: "fl" 10 | *

11 | * Example 2: Input: strs = 12 | * ["dogasdfasdf","racecar","car"] Output: "" 13 | * Explanation: 14 | * There is no common prefix among the input 15 | * strings. 16 | *

17 | *

18 | * Constraints: 1 <= strs.length <= 200 0 <= 19 | * strs[i].length <= 200 strs[i] consists of only 20 | * lower-case English letters. 21 | */ 22 | class LongestCommonPrefix { 23 | public String longestCommonPrefix(String[] strs) { 24 | String result = ""; 25 | for (int i = 0; i < strs[0].length(); i++) { 26 | char finding = strs[0].charAt(i); 27 | for (int j = 1; j < strs.length; j++) { 28 | if (strs[j].length() <= i || 29 | finding != strs[j].charAt(i)) { 30 | return result; 31 | } 32 | } 33 | result += finding; 34 | } 35 | 36 | return result; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 141 Linked List Cycle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | class Solution { 13 | public boolean hasCycle(ListNode head) { 14 | if (head == null || head.next == null) { 15 | return false; 16 | } 17 | ListNode first = head; 18 | ListNode second = first.next; 19 | while (second != null && first != null) { 20 | if (first == second) { 21 | return true; 22 | } 23 | second = second.next != null ? second.next.next : null; 24 | first = first.next; 25 | } 26 | return false; 27 | } 28 | } 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Iterative - Java Video Solution.java: -------------------------------------------------------------------------------- 1 | 2 | import in.knowledgegate.dsa.binarytree.model.TreeNode; 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.Stack; 7 | 8 | /** 9 | * Write Preorder traversal of a binary tree using 10 | * iterative approach 11 | */ 12 | class PreorderTraversalIterative { 13 | public List iterativePreorder(TreeNode root) { 14 | List result = new ArrayList<>(); 15 | if (root == null) { 16 | return result; 17 | } 18 | 19 | Stack stack = new Stack<>(); 20 | stack.push(root); 21 | while (!stack.isEmpty()) { 22 | TreeNode temp = stack.pop(); 23 | result.add(temp.val); 24 | 25 | if (temp.right != null) { 26 | stack.push(temp.right); 27 | } 28 | if (temp.left != null) { 29 | stack.push(temp.left); 30 | } 31 | } 32 | 33 | return result; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 144 Binary Tree Preorder Traversal using Recursion - Java Video Solution.java: -------------------------------------------------------------------------------- 1 | 2 | import in.knowledgegate.dsa.binarytree.model.TreeNode; 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | /** 8 | * Write Preorder traversal of a binary tree using 9 | * recursive approach 10 | */ 11 | class PreorderTraversalRecursive { 12 | public List preorderTraversal(TreeNode root) { 13 | List result = new ArrayList<>(); 14 | preorderTraversal(root, result); 15 | return result; 16 | } 17 | 18 | public void preorderTraversal(TreeNode root, 19 | List result) { 20 | if (root == null) 21 | return; 22 | result.add(root.val); 23 | preorderTraversal(root.left, result); 24 | preorderTraversal(root.right, result); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Iteration.java: -------------------------------------------------------------------------------- 1 | 2 | import in.knowledgegate.dsa.binarytree.model.TreeNode; 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.Stack; 7 | 8 | /** 9 | * Write Postorder traversal of a binary tree 10 | * using iterative approach 11 | */ 12 | class PostorderTraversalIterative { 13 | public List iterativePostorder(TreeNode root) { 14 | List result = new ArrayList<>(); 15 | if (root == null) { 16 | return result; 17 | } 18 | 19 | Stack s1 = new Stack<>(); 20 | Stack s2 = new Stack<>(); 21 | s1.push(root); 22 | 23 | while (!s1.isEmpty()) { 24 | TreeNode temp = s1.pop(); 25 | s2.push(temp); 26 | 27 | if (temp.left != null) { 28 | s1.push(temp.left); 29 | } 30 | if (temp.right != null) { 31 | s1.push(temp.right); 32 | } 33 | } 34 | 35 | while (!s2.isEmpty()) { 36 | result.add(s2.pop().val); 37 | } 38 | 39 | return result; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 145 Binary Tree Postorder Traversal using Recursion.java: -------------------------------------------------------------------------------- 1 | 2 | import in.knowledgegate.dsa.binarytree.model.TreeNode; 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | /** 8 | * Write Postorder traversal of a binary tree 9 | * using recursive approach 10 | */ 11 | class PostorderTraversalRecursive { 12 | public List postorderTraversal(TreeNode root) { 13 | List list = new ArrayList<>(); 14 | postorderTraversal(root, list); 15 | return list; 16 | } 17 | 18 | private void postorderTraversal(TreeNode root, 19 | List result) { 20 | if (root == null) 21 | return; 22 | postorderTraversal(root.left, result); 23 | postorderTraversal(root.right, result); 24 | result.add(root.val); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 160 Intersection of Two Linked Lists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | class Solution { 13 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 14 | if (headA == headB) 15 | return headA; 16 | if (headA == null || headB == null) 17 | return null; 18 | 19 | ListNode first = headA; 20 | ListNode second = headB; 21 | while (first != second) { 22 | first = first != null ? first.next : headB; 23 | second = second != null ? second.next : headA; 24 | } 25 | return first; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 168 Excel Sheet Column Title.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String convertToTitle(int columnNumber) { 3 | StringBuilder result = new StringBuilder(); 4 | while (columnNumber > 0) { 5 | columnNumber--; 6 | int rem = columnNumber % 26; 7 | char c = (char) ('A' + rem); 8 | result.insert(0, c); 9 | columnNumber /= 26; 10 | } 11 | return result.toString(); 12 | } 13 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 169 Majority Element using Bit Manipulation.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int majorityElement(int[] nums) { 3 | int majority = 0; 4 | 5 | for (int i = 0; i < 32; i++) { 6 | int bit = 1 << i; 7 | 8 | int count = 0; 9 | for (int num: nums) { 10 | if ((num & bit) != 0) { 11 | count++; 12 | } 13 | } 14 | 15 | if (count > nums.length / 2) { 16 | majority |= bit; 17 | } 18 | } 19 | 20 | return majority; 21 | } 22 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 169 Majority Element using Hashmap.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public int majorityElement(int[] nums) { 5 | Map cardi = getCardinalityMap(nums); 6 | // Space: O(1), Time: O(n) 7 | for (Map.Entry entry : cardi.entrySet()) { 8 | if (entry.getValue() > nums.length / 2) { 9 | return entry.getKey(); 10 | } 11 | } 12 | return -1; 13 | } 14 | 15 | // Space: O(n), Time: O(n) 16 | private Map getCardinalityMap(int[] nums) { 17 | Map cardi = new HashMap<>(); 18 | for (int num: nums) { 19 | if (!cardi.containsKey(num)) { 20 | cardi.put(num, 1); 21 | } else { 22 | int currCount = cardi.get(num); 23 | cardi.put(num, currCount + 1); 24 | } 25 | } 26 | return cardi; 27 | } 28 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 169 Majority Element using Sorting.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public int majorityElement(int[] nums) { 5 | Arrays.sort(nums); 6 | return nums[nums.length/2]; 7 | } 8 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number using Math.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given a string columnTitle that represents the 4 | * column title as appears in an Excel sheet, 5 | * return its corresponding column number. 6 | * 7 | * For example: 8 | * A -> 1 9 | * B -> 2 10 | * C -> 3 11 | * ... 12 | * Z -> 26 13 | * AA -> 27 14 | * AB -> 28 15 | * ... 16 | * 17 | * 18 | * Example 1: 19 | * Input: columnTitle = "A" 20 | * Output: 1 21 | * 22 | * Example 2: 23 | * Input: columnTitle = "AB" 24 | * Output: 28 25 | * 26 | * Example 3: 27 | * Input: columnTitle = "ZY" 28 | * Output: 701 29 | * 30 | * Constraints: 31 | * 1 <= columnTitle.length <= 7 32 | * columnTitle consists only of uppercase English letters. 33 | * columnTitle is in the range ["A", "FXSHRXW"]. 34 | */ 35 | class ExcelSheetColumnNumber { 36 | 37 | public static void main(String[] args) { 38 | ExcelSheetColumnNumber baseConversion = new ExcelSheetColumnNumber(); 39 | System.out.println("Output is:" + 40 | baseConversion.titleToNumber("AB")); 41 | } 42 | 43 | public int titleToNumber(String columnTitle) { 44 | int result = 0, pow = 0; 45 | for (int i = columnTitle.length() - 1; i >= 0; i--, pow++) { 46 | char c = columnTitle.charAt(i); 47 | int val = c - 'A' + 1; 48 | result += val * (int) Math.pow(26, pow); 49 | } 50 | return result; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 171 Excel Sheet Column Number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int titleToNumber(String columnTitle) { 3 | int result = 0; 4 | int len = columnTitle.length(); 5 | for (int i = len - 1, pow = 0; i >= 0; i--, pow++) { 6 | char c = columnTitle.charAt(i); 7 | int digit = c - 'A' + 1; 8 | result += digit * Math.pow(26, pow); 9 | } 10 | return result; 11 | } 12 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 190 Reverse Bits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // you need treat n as an unsigned value 3 | public int reverseBits(int n) { 4 | int result = 0; 5 | for (int i = 0 ; i < 32; i++) { 6 | result = result << 1; 7 | result = result | (n & 1); 8 | n = n >>> 1; 9 | } 10 | return result; 11 | } 12 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 191 Number of 1 Bits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int hammingWeight(int n) { 3 | int count = 0; 4 | while (n > 0) { 5 | if ((n & 1) == 1) { 6 | count++; 7 | } 8 | n >>= 1; 9 | } 10 | return count; 11 | } 12 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 20 Valid Parentheses.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Stack; 3 | 4 | /** 5 | * Given a string s containing just the characters '(', ')', '{', '}', '[' and 6 | * ']', determine if the input string is valid. An input string is valid if: 7 | *

8 | * Open brackets must be closed by the same type of brackets. Open brackets must 9 | * be closed in the correct order. 10 | *

11 | *

12 | * Example 1: Input: s = "()" Output: true 13 | *

14 | * Example 2: Input: s = "()[]{}" Output: true 15 | *

16 | * Example 3: Input: s = "(]" Output: false 17 | *

18 | * Constraints: 1 <= s.length <= 104 s consists of parentheses only '()[]{}'. 19 | */ 20 | class ValidParenthesis { 21 | public boolean isValid(String s) { 22 | Stack stack = new Stack<>(); 23 | for (int i = 0; i < s.length(); i++) { 24 | char c = s.charAt(i); 25 | switch (c) { 26 | case '{': 27 | case '[': 28 | case '(': 29 | stack.push(c); 30 | break; 31 | case '}': 32 | if (stack.isEmpty() || '{' != stack.pop()) { 33 | return false; 34 | } 35 | break; 36 | case ']': 37 | if (stack.isEmpty() || '[' != stack.pop()) { 38 | return false; 39 | } 40 | break; 41 | case ')': 42 | if (stack.isEmpty() || '(' != stack.pop()) { 43 | return false; 44 | } 45 | break; 46 | } 47 | } 48 | return stack.isEmpty(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 202 Happy Number.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public boolean isHappy(int n) { 5 | Set set = new HashSet<>(); 6 | while (n != 1) { 7 | if (set.contains(n)) { 8 | return false; 9 | } 10 | set.add(n); 11 | n = sumOfSquareOfDigits(n); 12 | } 13 | return true; 14 | } 15 | 16 | private int sumOfSquareOfDigits(int num) { 17 | int result = 0; 18 | while (num > 0) { 19 | int rem = num % 10; 20 | result += rem * rem; 21 | num /= 10; 22 | } 23 | return result; 24 | } 25 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 203 Remove Linked List Elements.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode removeElements(ListNode head, int val) { 13 | ListNode dummy = new ListNode(); 14 | dummy.next = head; 15 | 16 | ListNode temp = dummy; 17 | while (temp.next != null) { 18 | if (temp.next.val == val) { 19 | temp.next = temp.next.next; 20 | } else { 21 | temp = temp.next; 22 | } 23 | } 24 | return dummy.next; 25 | } 26 | } 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 205 Isomorphic Strings.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | class Solution { 4 | public boolean isIsomorphic(String s, String t) { 5 | if (s.length() != t.length()) { 6 | return false; 7 | } 8 | HashMap sToT = new HashMap<>(); 9 | HashMap tToS = new HashMap<>(); 10 | for (int i = 0; i < s.length(); i++) { 11 | char sChar = s.charAt(i); 12 | char tChar = t.charAt(i); 13 | 14 | if (sToT.getOrDefault(sChar, tChar) != tChar || 15 | tToS.getOrDefault(tChar, sChar) != sChar) { 16 | return false; 17 | } 18 | 19 | sToT.put(sChar, tChar); 20 | tToS.put(tChar, sChar); 21 | } 22 | return true; 23 | } 24 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 206 Reverse Linked List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode reverseList(ListNode head) { 13 | ListNode prev = null; 14 | ListNode current = head; 15 | 16 | while (current != null) { 17 | ListNode temp = current.next; 18 | current.next = prev; 19 | prev = current; 20 | current = temp; 21 | } 22 | 23 | return prev; 24 | } 25 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 21 Merge Two Sorted Lists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | */ 4 | 5 | class ListNode { 6 | int val; 7 | ListNode next; 8 | ListNode() {} 9 | ListNode(int val) { this.val = val; } 10 | ListNode(int val, ListNode next) { this.val = val; this.next = next; } 11 | } 12 | 13 | class Solution { 14 | public ListNode mergeTwoLists(ListNode list1, ListNode list2) { 15 | ListNode temp = new ListNode(); 16 | ListNode dummy = temp; 17 | 18 | while (list1 != null && list2 != null) { 19 | if (list1.val <= list2.val) { 20 | temp.next = list1; 21 | list1 = list1.next; 22 | } else { 23 | temp.next = list2; 24 | list2 = list2.next; 25 | } 26 | temp = temp.next; 27 | } 28 | 29 | temp.next = list1 != null ? list1 : list2; 30 | return dummy.next; 31 | } 32 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 2148 Count Elements With Strictly Smaller and Greater Elements .java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | /** 5 | * Given an integer array nums, return the number of 6 | * elements that have both a strictly smaller and 7 | * a strictly greater element appear in nums. 8 | * 9 | * Example 1: 10 | * Input: nums = [11,7,2,15] 11 | * Output: 2 12 | * Explanation: The element 7 has the element 2 strictly 13 | * smaller than it and the element 11 strictly greater than it. 14 | * Element 11 has element 7 strictly smaller than it 15 | * and element 15 strictly greater than it. 16 | * In total there are 2 elements having both a strictly 17 | * smaller and a strictly greater element appear in nums. 18 | * 19 | * Example 2: 20 | * Input: nums = [-3,3,3,90] 21 | * Output: 2 22 | * Explanation: The element 3 has the element -3 23 | * strictly smaller than it and the element 90 24 | * strictly greater than it. 25 | * Since there are two elements with the value 3, 26 | * in total there are 2 elements having both a strictly 27 | * smaller and a strictly greater element appear in nums. 28 | * 29 | * [1,1,1,2,2,3,4,5,5] 30 | * 31 | * Constraints: 32 | * 1 <= nums.length <= 100 33 | * -105 <= nums[i] <= 105 34 | */ 35 | class CountElements { 36 | 37 | public static void main(String[] args) { 38 | CountElements elements = new CountElements(); 39 | int[] nums = new int[] { 1, 1, 1, 1, 1, 1 }; 40 | System.out.println("output is:" + elements.countElements(nums)); 41 | } 42 | 43 | public int countElements(int[] nums) { 44 | Arrays.sort(nums); 45 | int beg = -1, end = -1; 46 | for (int i = 0; i < nums.length - 1; i++) { 47 | if (nums[i + 1] > nums[i]) { 48 | beg = i + 1; 49 | break; 50 | } 51 | } 52 | for (int i = nums.length - 1; i > 0; i--) { 53 | if (nums[i - 1] < nums[i]) { 54 | end = i - 1; 55 | break; 56 | } 57 | } 58 | return beg != -1 && end != -1 ? end - beg + 1 59 | : 0; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate using Hashmap.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public boolean containsDuplicate(int[] nums) { 5 | Set numSet = new HashSet<>(); 6 | for (int num: nums) { 7 | if (numSet.add(num) == false) { 8 | return true; 9 | } 10 | } 11 | return false; 12 | } 13 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 217 Contains Duplicate using sorting.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public boolean containsDuplicate(int[] nums) { 5 | // O(nlogn) 6 | Arrays.sort(nums); 7 | 8 | // O(n) 9 | for (int i = 0; i < nums.length - 1; i++) { 10 | if (nums[i] == nums[i+1]) { 11 | return true; 12 | } 13 | } 14 | return false; 15 | } 16 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 219 Contains Duplicate II.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | /** 5 | * Given an integer array nums and an integer k, 6 | * return true if there are two distinct indices 7 | * i and j in the array such that nums[i] == nums[j] 8 | * and abs(i - j) <= k. 9 | * 10 | * Example 1: 11 | * Input: nums = [1,2,3,1], k = 3 12 | * Output: true 13 | * 14 | * Example 2: 15 | * Input: nums = [1,0,1,1], k = 1 16 | * Output: true 17 | * 18 | * Example 3: 19 | * Input: nums = [1,2,3,1,2,3], k = 2 20 | * Output: false 21 | * 22 | * Constraints: 23 | * 1 <= nums.length <= 105 24 | * -109 <= nums[i] <= 109 25 | * 0 <= k <= 105 26 | */ 27 | class ContainsDuplicate2 { 28 | public boolean containsNearbyDuplicate(int[] nums, int k) { 29 | Set window = new HashSet<>(); 30 | for (int i = 0; i < nums.length; i++) { 31 | if (i > k) { 32 | window.remove(nums[i - k - 1]); 33 | } 34 | if (!window.add(nums[i])) 35 | return true; 36 | } 37 | return false; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 222 Count Complete Tree Nodes.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode() {} 8 | * TreeNode(int val) { this.val = val; } 9 | * TreeNode(int val, TreeNode left, TreeNode right) { 10 | * this.val = val; 11 | * this.left = left; 12 | * this.right = right; 13 | * } 14 | * } 15 | */ 16 | class Solution { 17 | public int countNodes(TreeNode root) { 18 | if (root == null) return 0; 19 | return 1 + countNodes(root.left) 20 | + countNodes(root.right); 21 | } 22 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 226 Invert Binary Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the root of a binary tree, invert the 3 | * tree, and return its root. 4 | * 5 | * Example 1: 6 | * 4 4 7 | * 2 7 7 2 8 | * 1 3 6 9 9 6 3 1 9 | * 10 | * Input: root = [4,2,7,1,3,6,9] 11 | * Output: [4,7,2,9,6,3,1] 12 | * 13 | * Example 2: 14 | * Input: root = [] 15 | * Output: [] 16 | * 17 | * Constraints: 18 | * The number of nodes in the tree is in the 19 | * range [0, 100]. 20 | * -100 <= Node.val <= 100 21 | */ 22 | class InvertBinaryTree { 23 | public TreeNode invertTree(TreeNode root) { 24 | if (root == null) 25 | return null; 26 | TreeNode temp = root.left; 27 | root.left = root.right; 28 | root.right = temp; 29 | invertTree(root.left); 30 | invertTree(root.right); 31 | return root; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 234 Palindrome Linked List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given the head of a singly linked list, 3 | * return true if it is a palindrome. 4 | * 5 | * Example 1: 6 | * Input: head = [1,2,2,1] 7 | * Output: true 8 | * 9 | * Example 2: 10 | * Input: head = [1,2] 11 | * Output: false 12 | * 13 | * Constraints: 14 | * The number of nodes in the list is in the range [1, 105]. 15 | * 0 <= Node.val <= 9 16 | * 17 | * Follow up: Could you do it in O(n) time and O(1) space? 18 | */ 19 | class PalindromeLinkedList { 20 | public static void main(String[] args) { 21 | PalindromeLinkedList checker = new PalindromeLinkedList(); 22 | ListNode fourth = new ListNode(1); 23 | ListNode third = new ListNode(2, fourth); 24 | ListNode second = new ListNode(3, third); 25 | ListNode first = new ListNode(1, second); 26 | System.out.println("Palindrome status: " 27 | + checker.isPalindrome(first)); 28 | } 29 | 30 | public boolean isPalindrome(ListNode head) { 31 | ListNode slow = head, fast = head; 32 | while (fast != null && fast.next != null) { 33 | slow = slow.next; 34 | fast = fast.next.next; 35 | } 36 | 37 | ListNode reversed = reverse(slow); 38 | while (head != null && reversed != null) { 39 | if (head.val != reversed.val) 40 | return false; 41 | head = head.next; 42 | reversed = reversed.next; 43 | } 44 | return true; 45 | } 46 | 47 | private ListNode reverse(ListNode node) { 48 | ListNode prev = null; 49 | while (node != null) { 50 | ListNode temp = node.next; 51 | node.next = prev; 52 | prev = node; 53 | node = temp; 54 | } 55 | return prev; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 242 Valid Anagram.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | class Solution { 4 | public boolean isAnagram(String s, String t) { 5 | if (s.length() != t.length()) { 6 | return false; 7 | } 8 | HashMap countMap = new HashMap<>(); 9 | for (int i = 0 ; i < s.length(); i++) { 10 | char sChar = s.charAt(i); 11 | char tChar = t.charAt(i); 12 | 13 | countMap.put(sChar, countMap.getOrDefault(sChar, 0) + 1); 14 | countMap.put(tChar, countMap.getOrDefault(tChar, 0) - 1); 15 | } 16 | 17 | for (int value : countMap.values()) { 18 | if (value != 0) { 19 | return false; 20 | } 21 | } 22 | return true; 23 | } 24 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 26 Remove Duplicates from Sorted Array.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given an integer array nums sorted in non-decreasing order, remove the 4 | * duplicates in-place such that each unique element appears only once. The 5 | * relative order of the elements should be kept the same. Since it is 6 | * impossible to change the length of the array in some languages, you must 7 | * instead have the result be placed in the first part of the array nums. More 8 | * formally, if there are k elements after removing the duplicates, then the 9 | * first k elements of nums should hold the final result. It does not matter 10 | * what you leave beyond the first k elements. Return k after placing the final 11 | * result in the first k slots of nums. 12 | *

13 | * Do not allocate extra space for another array. You must do this by modifying 14 | * the input array in-place with O(1) extra memory. 15 | *

16 | * Example 1: Input: nums = [1,1,2] Output: 2, nums = [1,2,_] Explanation: Your 17 | * function should return k = 2, with the first two elements of nums being 1 and 18 | * 2 respectively. It does not matter what you leave beyond the returned k 19 | * (hence they are underscores). 20 | *

21 | * Example 2: Input: nums = [0,0,1,1,1,2,2,3,3,4] Output: 5, nums = 22 | * [0,1,2,3,4,_,_,_,_,_] Explanation: Your function should return k = 5, with 23 | * the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does 24 | * not matter what you leave beyond the returned k (hence they are 25 | * underscores). 26 | *

27 | *

28 | * Constraints: 1 <= nums.length <= 3 * 104 -100 <= nums[i] <= 100 nums is 29 | * sorted in non-decreasing order. 30 | */ 31 | class RemoveDuplicatesSortedArray { 32 | public int removeDuplicates(int[] nums) { 33 | if (nums.length == 0) 34 | return 0; 35 | int prev = 0; 36 | 37 | for (int i = 1; i < nums.length; i++) { 38 | if (nums[prev] != nums[i]) { 39 | nums[++prev] = nums[i]; 40 | } 41 | } 42 | return prev + 1; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 268 Missing Number.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given an array nums containing n distinct numbers 4 | * in the range [0, n], return the only number 5 | * in the range that is missing from the array. 6 | * 7 | * 8 | * Example 1: 9 | * Input: nums = [3,0,1] 10 | * Output: 2 11 | * Explanation: n = 3 since there are 3 numbers, 12 | * so all numbers are in the range [0,3]. 2 is the 13 | * missing number in the range since it does not 14 | * appear in nums. 15 | * 16 | * Example 2: 17 | * Input: nums = [0,1] 18 | * Output: 2 19 | * Explanation: n = 2 since there are 2 numbers, 20 | * so all numbers are in the range [0,2]. 2 is the 21 | * missing number in the range since it does not 22 | * appear in nums. 23 | * 24 | * Example 3: 25 | * Input: nums = [9,6,4,2,3,5,7,0,1] 26 | * Output: 8 27 | * Explanation: n = 9 since there are 9 numbers, 28 | * so all numbers are in the range [0,9]. 8 is the 29 | * missing number in the range since it does not 30 | * appear in nums. 31 | * 32 | * 33 | * Constraints: 34 | * n == nums.length 35 | * 1 <= n <= 104 36 | * 0 <= nums[i] <= n 37 | * All the numbers of nums are unique. 38 | */ 39 | class MissingNumber { 40 | public int missingNumber(int[] nums) { 41 | int num1 = 0, num2 = nums.length; 42 | for (int i = 0; i < nums.length; i++) { 43 | num1 = num1 ^ nums[i]; 44 | num2 = num2 ^ i; 45 | } 46 | return num1 ^ num2; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 27 Remove Element using Two Pointers.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given an integer array nums and an integer val, 4 | * remove all occurrences of val in nums in-place. 5 | * The relative order of the elements may be changed. 6 | * 7 | * 8 | * Do not allocate extra space for another array. 9 | * You must do this by modifying the input array 10 | * in-place with O(1) extra memory. 11 | * 12 | * 13 | * Example 1: 14 | * Input: nums = [3,2,2,3], val = 3 15 | * Output: 2, nums = [2,2,_,_] 16 | * Explanation: Your function should return k = 2, 17 | * with the first two elements of nums being 2. 18 | * It does not matter what you leave beyond the 19 | * returned k (hence they are underscores). 20 | * 21 | * Example 2: 22 | * Input: nums = [0,1,2,2,3,0,4,2], val = 2 23 | * Output: 5, nums = [0,1,4,0,3,_,_,_] 24 | * Explanation: Your function should return k = 5, 25 | * with the first five elements of nums containing 26 | * 0, 0, 1, 3, and 4. 27 | */ 28 | class RemoveElement { 29 | public int removeElement(int[] nums, int val) { 30 | int insertLoc = 0; 31 | for (int i = 0; i < nums.length; i++) { 32 | if (val != nums[i]) { 33 | nums[insertLoc++] = nums[i]; 34 | } 35 | } 36 | return insertLoc; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 27 Remove Element.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int removeElement(int[] nums, int val) { 3 | int j = 0; 4 | for (int i = 0; i < nums.length; i++) { 5 | if (nums[i] != val) { 6 | nums[j] = nums[i]; 7 | j++; 8 | } 9 | } 10 | return j; 11 | } 12 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 278 First Bad Version.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * You are a product manager and currently leading 4 | * a team to develop a new product. Unfortunately, 5 | * the latest version of your product fails the 6 | * quality check. Since each version is developed based 7 | * on the previous version, all the versions after 8 | * a bad version are also bad. 9 | * 10 | * Suppose you have n versions [1, 2, ..., n] and 11 | * you want to find out the first bad one, which 12 | * causes all the following ones to be bad. 13 | * 14 | * You are given an API bool isBadVersion(version) 15 | * which returns whether version is bad. Implement 16 | * a function to find the first bad version. You 17 | * should minimize the number of calls to the API. 18 | * 19 | * 20 | * Example 1: 21 | * Input: n = 5, bad = 4 22 | * Output: 4 23 | * Explanation: 24 | * call isBadVersion(3) -> false 25 | * call isBadVersion(5) -> true 26 | * call isBadVersion(4) -> true 27 | * Then 4 is the first bad version. 28 | * 29 | * Example 2: 30 | * Input: n = 1, bad = 1 31 | * Output: 1 32 | * 33 | * Constraints: 34 | * 1 <= bad <= n <= 231 - 1 35 | */ 36 | class FirstBadVersion { 37 | static int badVersion; 38 | static int TOTAL_VERSION = 500; 39 | 40 | public static void main(String[] args) { 41 | FirstBadVersion versionChecker = new FirstBadVersion(); 42 | badVersion = 412; 43 | System.out.println("\nbad version is:" 44 | + versionChecker.firstBadVersionLinearSearch(TOTAL_VERSION)); 45 | System.out.println("\nbad version is:" 46 | + versionChecker.firstBadVersion(TOTAL_VERSION)); 47 | } 48 | 49 | public int firstBadVersion(int n) { 50 | long beg = 1, end = n; 51 | while (beg <= end) { 52 | int mid = (int) ((beg + end) / 2); 53 | if (isBadVersion(mid)) { 54 | end = mid - 1; 55 | } else { 56 | beg = mid + 1; 57 | } 58 | } 59 | return (int) end + 1; 60 | } 61 | 62 | public int firstBadVersionLinearSearch(int n) { 63 | for (int i = 1; i < n; i++) { 64 | if (isBadVersion(i)) 65 | return i; 66 | } 67 | return -1; 68 | } 69 | 70 | private boolean isBadVersion(int version) { 71 | System.out.print("."); 72 | return version - badVersion >= 0; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 28 Find the Index of the First Occurrence in a String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int strStr(String haystack, String needle) { 3 | for (int i = 0; i < haystack.length() - needle.length() + 1; i++) { 4 | int j = 0; 5 | while (j < needle.length()) { 6 | if (haystack.charAt(i + j) != needle.charAt(j)) { 7 | break; 8 | } 9 | j++; 10 | } 11 | 12 | if (j == needle.length()) { 13 | return i; 14 | } 15 | } 16 | return -1; 17 | } 18 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 283 Move Zeroes.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | /** 5 | * Given an integer array nums, move all 0's to the 6 | * end of it while maintaining the relative order 7 | * of the non-zero elements. 8 | * 9 | * Note that you must do this in-place without making 10 | * a copy of the array. 11 | * 12 | * Example 1: 13 | * Input: nums = [0,1,0,3,12] 14 | * Output: [1,3,12,0,0] 15 | * 16 | * Example 2: 17 | * Input: nums = [0] 18 | * Output: [0] 19 | * 20 | * Constraints: 21 | * 1 <= nums.length <= 104 22 | * -231 <= nums[i] <= 231 - 1 23 | */ 24 | class MoveZeros { 25 | public static void main(String[] args) { 26 | MoveZeros zeros = new MoveZeros(); 27 | int[] nums = new int[] { 0, 1, 0, 3, 12 }; 28 | zeros.moveZeroes(nums); 29 | System.out.println("Output is:" + Arrays.toString(nums)); 30 | } 31 | 32 | public void moveZeroes(int[] nums) { 33 | int prev = 0; // This will track the position to place the next non-zero element. 34 | for (int i = 0; i < nums.length; i++) { 35 | if (nums[i] != 0) { 36 | nums[prev] = nums[i]; // Place the non-zero element at the 'prev' position 37 | if (i != prev) { // Only set to zero if it's actually a move 38 | nums[i] = 0; 39 | } 40 | prev++; // Move the 'prev' position forward 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 290 Word Pattern.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | class Solution { 4 | public boolean wordPattern(String pattern, String s) { 5 | String[] words = s.split(" "); 6 | if (pattern.length() != words.length) { 7 | return false; 8 | } 9 | HashMap lToW = new HashMap<>(); 10 | HashMap wToL = new HashMap<>(); 11 | for (int i = 0 ; i < pattern.length(); i++) { 12 | char letter = pattern.charAt(i); 13 | String word = words[i]; 14 | 15 | if (lToW.containsKey(letter)) { 16 | if (!lToW.get(letter).equals(word)) { 17 | return false; 18 | } 19 | } else { 20 | lToW.put(letter, word); 21 | } 22 | 23 | if (wToL.containsKey(word)) { 24 | if (wToL.get(word) != letter) { 25 | return false; 26 | } 27 | } else { 28 | wToL.put(word, letter); 29 | } 30 | } 31 | return true; 32 | } 33 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 344 Reverse String.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Write a function that reverses a string. The 4 | * input string is given as an array of characters 5 | * s. 6 | * You must do this by modifying the input array 7 | * in-place with O(1) extra memory. 8 | * 9 | * Example 1: 10 | * Input: s = ["h","e","l","l","o"] 11 | * Output: ["o","l","l","e","h"] 12 | * 13 | * Example 2: 14 | * Input: s = ["H","a","n","n","a","h"] 15 | * Output: ["h","a","n","n","a","H"] 16 | * 17 | * Constraints: 18 | * 1 <= s.length <= 105 19 | * s[i] is a printable ascii character. 20 | */ 21 | class ReverseString { 22 | public void reverseString(char[] s) { 23 | for (int i = 0; i < s.length / 2; i++) { 24 | char temp = s[i]; 25 | s[i] = s[s.length - 1 - i]; 26 | s[s.length - 1 - i] = temp; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 345 Reverse Vowels of a String.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reverseVowels(String s) { 3 | char[] letters = s.toCharArray(); 4 | int i = 0, j = s.length() - 1; 5 | 6 | while (i < j) { 7 | // increment till i reaches a vowel 8 | while (i < j && !isVowel(letters[i])) i++; 9 | 10 | // decrement till j reaches a vowel 11 | while (i < j && !isVowel(letters[j])) j--; 12 | 13 | if (i < j) { 14 | char temp = letters[i]; 15 | letters[i] = letters[j]; 16 | letters[j] = temp; 17 | i++; 18 | j--; 19 | } 20 | } 21 | return new String(letters); 22 | } 23 | 24 | private boolean isVowel(char c) { 25 | final String VOWELS = "aeiouAEIOU"; 26 | return VOWELS.indexOf(c) != -1; 27 | } 28 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 349 Intersection of Two Arrays.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashSet; 3 | 4 | /** 5 | * Given two integer arrays nums1 and nums2, 6 | * return an array of their intersection. 7 | * Each element in the result must be unique 8 | * and you may return the result in any order. 9 | * 10 | * Example 1: 11 | * Input: nums1 = [1,2,2,1], nums2 = [2,2] 12 | * Output: [2] 13 | * 14 | * Example 2: 15 | * Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 16 | * Output: [9,4] 17 | * Explanation: [4,9] is also accepted. 18 | * 19 | * Constraints: 20 | * 1 <= nums1.length, nums2.length <= 1000 21 | * 0 <= nums1[i], nums2[i] <= 1000 22 | */ 23 | class IntersectionOfTwoArrays { 24 | public int[] intersection(int[] nums1, int[] nums2) { 25 | HashSet set = new HashSet<>(); 26 | for (int num : nums1) { 27 | set.add(num); 28 | } 29 | 30 | HashSet result = new HashSet<>(); 31 | for (int num : nums2) { 32 | if (set.contains(num)) { 33 | result.add(num); 34 | } 35 | } 36 | 37 | int[] resultArr = new int[result.size()]; 38 | int i = 0; 39 | for (Integer num : result) { 40 | resultArr[i++] = num; 41 | } 42 | return resultArr; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 35 Search Insert Position using Binary Search.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given a sorted array of distinct integers and a target value, return the 4 | * index if the target is found. If not, return the index where it would be if 5 | * it were inserted in order. You must write an algorithm with O(log n) runtime 6 | * complexity. 7 | *

8 | *

9 | * Example 1: Input: nums = [1,3,5,6], target = 5 Output: 2 10 | *

11 | * Example 2: Input: nums = [1,3,5,6], target = 2 Output: 1 12 | *

13 | * Example 3: Input: nums = [1,3,5,6], target = 7 Output: 4 14 | *

15 | *

16 | * Constraints: 1 <= nums.length <= 104 -104 <= nums[i] <= 104 nums contains 17 | * distinct values sorted in ascending order. -104 <= target <= 104 18 | */ 19 | class SearchInsertPosition { 20 | public int searchInsert(int[] nums, int target) { 21 | int beg = 0, end = nums.length - 1; 22 | while (beg <= end) { 23 | int mid = beg + (end - beg) / 2; 24 | if (nums[mid] == target) { 25 | return mid; 26 | } else if (nums[mid] > target) { 27 | end = mid - 1; 28 | } else { 29 | beg = mid + 1; 30 | } 31 | } 32 | return end + 1; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 35 Search Insert Position.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int searchInsert(int[] nums, int target) { 3 | int i = 0; 4 | while (i < nums.length) { 5 | if (nums[i] >= target) { 6 | break; 7 | } 8 | i++; 9 | } 10 | return i; 11 | } 12 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 350 Intersection of Two Arrays II.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | /** 8 | * Given two integer arrays nums1 and nums2,return 9 | * an array of their intersection. Each element in 10 | * the result must appear as many times as it shows 11 | * in both arrays and you may return the result in 12 | * any order. 13 | * 14 | * Example 1: 15 | * Input: nums1 = [1,2,2,1], nums2 = [2,2] 16 | * Output: [2,2] 17 | * 18 | * Example 2: 19 | * Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 20 | * Output: [4,9] 21 | * Explanation: [9,4] is also accepted. 22 | * 23 | * Constraints: 24 | * 1 <= nums1.length, nums2.length <= 1000 25 | * 0 <= nums1[i], nums2[i] <= 1000 26 | */ 27 | class IntersectionOfTwoArrays2 { 28 | public int[] intersect(int[] nums1, int[] nums2) { 29 | Map cardi = new HashMap<>(); 30 | for (int num : nums1) { 31 | cardi.put(num, cardi.getOrDefault(num, 0) + 1); 32 | } 33 | 34 | List result = new ArrayList<>(); 35 | for (int num : nums2) { 36 | int freq = cardi.getOrDefault(num, 0); 37 | if (freq > 0) { 38 | result.add(num); 39 | cardi.put(num, freq - 1); 40 | } 41 | } 42 | 43 | int[] inter = new int[result.size()]; 44 | for (int i = 0; i < result.size(); i++) { 45 | inter[i] = result.get(i); 46 | } 47 | return inter; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 374 Guess Number Higher or Lower.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * We are playing the Guess Game. The game is as follows: 4 | * 5 | * I pick a number from 1 to n. You have to guess 6 | * which number I picked. 7 | * 8 | * Every time you guess wrong, I will tell you 9 | * whether the number I picked is higher or lower than 10 | * your guess. 11 | * 12 | * You call a pre-defined API int guess(int num), 13 | * which returns three possible results: 14 | * 15 | * -1: Your guess is higher than the number I picked (i.e. num > pick). 16 | * 1: Your guess is lower than the number I picked (i.e. num < pick). 17 | * 0: your guess is equal to the number I picked (i.e. num == pick). 18 | * Return the number that I picked. 19 | * 20 | * 21 | * Example 1: 22 | * Input: n = 10, pick = 6 23 | * Output: 6 24 | * 25 | * Example 2: 26 | * Input: n = 1, pick = 1 27 | * Output: 1 28 | * 29 | * Example 3: 30 | * Input: n = 2, pick = 1 31 | * Output: 1 32 | * 33 | * Constraints: 34 | * 1 <= n <= 231 - 1 35 | * 1 <= pick <= n 36 | */ 37 | class GuessNumberHigherOrLower { 38 | static int numberToGuess; 39 | 40 | public static void main(String[] args) { 41 | GuessNumberHigherOrLower guesser = new GuessNumberHigherOrLower(); 42 | numberToGuess = 99; 43 | System.out.println("\nnumber is:" + guesser.guessNumberNormalSearch(100)); 44 | System.out.println(); 45 | System.out.println("\nnumber is:" + guesser.guessNumber(100)); 46 | } 47 | 48 | public int guessNumber(int n) { 49 | long beg = 1, end = n; 50 | while (beg <= end) { 51 | int mid = (int) ((beg + end) / 2); 52 | int res = guess(mid); 53 | if (res == 0) 54 | return mid; 55 | if (res == -1) 56 | end = mid - 1; 57 | else 58 | beg = mid + 1; 59 | } 60 | return -1; 61 | } 62 | 63 | public int guessNumberNormalSearch(int n) { 64 | for (int i = 1; i <= n; i++) { 65 | if (guess(i) == 0) 66 | return i; 67 | } 68 | return -1; 69 | } 70 | 71 | private int guess(int num) { 72 | System.out.print("."); 73 | if (num == numberToGuess) 74 | return 0; 75 | else if (num < numberToGuess) 76 | return 1; 77 | return -1; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 383 Ransom Note.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canConstruct(String ransomNote, String magazine) { 3 | int[] counts = new int[26]; 4 | for (char c : magazine.toCharArray()) { 5 | int index = c - 'a'; 6 | counts[index]++; 7 | } 8 | for (char c : ransomNote.toCharArray()) { 9 | int index = c - 'a'; 10 | counts[index]--; 11 | } 12 | for (int count: counts) { 13 | if (count < 0) { 14 | return false; 15 | } 16 | } 17 | return true; 18 | } 19 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 387 First Unique Character in a String.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashMap; 3 | 4 | class FirstUniqueCharacter { 5 | public int firstUniqChar(String s) { 6 | HashMap countMap = new HashMap<>(); 7 | // Filling characters into the map 8 | for (int i = 0; i < s.length(); i++) { 9 | char c = s.charAt(i); 10 | countMap.put(c, countMap.getOrDefault(c, 0) + 1); 11 | } 12 | 13 | // Checking count 1 14 | for (int i = 0; i < s.length(); i++) { 15 | char c = s.charAt(i); 16 | if (countMap.get(c) == 1) { 17 | return i; 18 | } 19 | } 20 | return -1; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 389 Find the Difference.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * You are given two strings s and t. 4 | * 5 | * String t is generated by random shuffling string 6 | * s and then add one more letter at a random position. 7 | * 8 | * Return the letter that was added to t. 9 | * 10 | * Example 1: 11 | * Input: s = "abcde", t = "abcdee" 12 | * Output: "e" 13 | * Explanation: 'e' is the letter that was added. 14 | * 15 | * Example 2: 16 | * Input: s = "", t = "y" 17 | * Output: "y" 18 | * 19 | * Constraints: 20 | * 0 <= s.length <= 1000 21 | * t.length == s.length + 1 22 | * s and t consist of lowercase English letters. 23 | */ 24 | class FindTheDifference { 25 | public static void main(String[] args) { 26 | FindTheDifference diff = new FindTheDifference(); 27 | System.out.println("Output is:" + 28 | diff.findTheDifference("abcde", "abcdee")); 29 | } 30 | 31 | public char findTheDifference(String s, String t) { 32 | char c = t.charAt(t.length() - 1); 33 | for (int i = 0; i < s.length(); i++) { 34 | c ^= s.charAt(i) ^ t.charAt(i); 35 | } 36 | return c; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal using Bit Manipulation.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given an integer num, return a string 4 | * representing its hexadecimal representation. 5 | * For negative integers, two’s complement method 6 | * is used. 7 | * 8 | * All the letters in the answer string should be 9 | * lowercase characters, and there should not be 10 | * any leading zeros in the answer except for the 11 | * zero itself. 12 | * 13 | * Note: You are not allowed to use any built-in 14 | * library method to directly solve this problem. 15 | * 16 | * 17 | * Example 1: 18 | * Input: num = 26 19 | * Output: "1a" 20 | * 21 | * Example 2: 22 | * Input: num = -1 23 | * Output: "ffffffff" 24 | * 25 | * Constraints: 26 | * -231 <= num <= 231 - 1 27 | */ 28 | class ConvertNumberToHexadecimal { 29 | public static void main(String[] args) { 30 | ConvertNumberToHexadecimal converter = new ConvertNumberToHexadecimal(); 31 | System.out.println("Hex num is: " 32 | + converter.toHex(26)); 33 | } 34 | 35 | public String toHex(int num) { 36 | if (num == 0) 37 | return "0"; 38 | 39 | char[] mapping = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; 40 | StringBuilder result = new StringBuilder(); 41 | 42 | // Process 32 bits, regardless of whether num is positive or negative 43 | for (int i = 0; i < 8; i++) { 44 | int endBits = num & 15; // Get the last 4 bits 45 | result.insert(0, mapping[endBits]); // Convert to hex and add to the front of the result 46 | num = num >>> 4; // Logically shift right, filling with zeros (important for negative numbers) 47 | } 48 | 49 | // Remove leading zeros 50 | while (result.length() > 1 && result.charAt(0) == '0') { 51 | result.deleteCharAt(0); 52 | } 53 | 54 | return result.toString(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 405 Convert a Number to Hexadecimal.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given an integer num, return a string representing 4 | * its hexadecimal representation. For negative 5 | * integers, two’s complement method is used. 6 | * 7 | * All the letters in the answer string should be 8 | * lowercase characters, and there should not be 9 | * any leading zeros in the answer except for the 10 | * zero itself. 11 | * 12 | * Note: You are not allowed to use any built-in 13 | * library method to directly solve this problem. 14 | * 15 | * Example 1: 16 | * Input: num = 26 17 | * Output: "1a" 18 | * 19 | * Example 2: 20 | * Input: num = -1 21 | * Output: "ffffffff" 22 | * 23 | * Constraints: 24 | * -231 <= num <= 231 - 1 25 | */ 26 | class ConvertNumberToHexadecimal { 27 | public static void main(String[] args) { 28 | ConvertNumberToHexadecimal converter = new ConvertNumberToHexadecimal(); 29 | System.out.println("Output is: " 30 | + converter.toHex(156)); 31 | } 32 | 33 | public String toHex(int num) { 34 | char[] hex = new char[] { '0', '1', '2', 35 | '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; 36 | StringBuilder sb = new StringBuilder(); 37 | while (num > 0) { 38 | int rem = num % 16; 39 | sb.insert(0, hex[rem]); 40 | num /= 16; 41 | } 42 | return sb.toString(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 415 Add Strings.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given two non-negative integers, num1 and num2 4 | * represented as string, return the sum of num1 5 | * and num2 as a string. 6 | * 7 | * You must solve the problem without using any 8 | * built-in library for handling large integers 9 | * (such as BigInteger). You must also not convert 10 | * the inputs to integers directly. 11 | * 12 | * Example 1: 13 | * 14 | * Input: num1 = "11", num2 = "123" 15 | * Output: "134" 16 | * Example 2: 17 | * 18 | * Input: num1 = "456", num2 = "77" 19 | * Output: "533" 20 | * Example 3: 21 | * 22 | * Input: num1 = "0", num2 = "0" 23 | * Output: "0" 24 | * 25 | * 26 | * Constraints: 27 | * 28 | * 1 <= num1.length, num2.length <= 104 29 | * num1 and num2 consist of only digits. 30 | * num1 and num2 don't have any leading zeros except for the zero itself. 31 | */ 32 | class AddStrings { 33 | public static void main(String[] args) { 34 | AddStrings addStrings = new AddStrings(); 35 | System.out.println("Sum is: " 36 | + addStrings.addStrings("456765765", 37 | "777868")); 38 | } 39 | 40 | public String addStrings(String num1, String num2) { 41 | int carry = 0; 42 | StringBuilder result = new StringBuilder(); 43 | int i = num1.length() - 1; 44 | int j = num2.length() - 1; 45 | while (i >= 0 || j >= 0 || carry > 0) { 46 | int x = i >= 0 ? num1.charAt(i--) - '0' : 0; 47 | int y = j >= 0 ? num2.charAt(j--) - '0' : 0; 48 | int rem = (x + y + carry) % 10; 49 | result.insert(0, rem); 50 | carry = (x + y + carry) / 10; 51 | } 52 | return result.toString(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 441 Arranging Coins.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * You have n coins and you want to build a staircase 4 | * with these coins. The staircase consists of k 5 | * rows where the ith row has exactly i coins. 6 | * The last row of the staircase may be incomplete. 7 | * 8 | * Given the integer n, return the number of 9 | * complete rows of the staircase you will build. 10 | * 11 | * Example 1: 12 | * Input: n = 5 13 | * Output: 2 14 | * Explanation: Because the 3rd row is incomplete, 15 | * we return 2. 16 | * 17 | * Example 2: 18 | * Input: n = 8 19 | * Output: 3 20 | * Explanation: Because the 4th row is incomplete, 21 | * we return 3. 22 | * 23 | * Constraints: 24 | * 1 <= n <= 231 - 1 25 | */ 26 | class ArrangingCoins { 27 | public static void main(String[] args) { 28 | ArrangingCoins arrange = new ArrangingCoins(); 29 | System.out.println("No of stairs:" 30 | + arrange.arrangeCoins(5)); 31 | } 32 | 33 | private int arrangeCoins(int n) { 34 | long begin = 0; 35 | long end = (int) Math.sqrt(2 * (long) n); // Adjust the initial end value 36 | while (begin <= end) { 37 | long mid = (begin + end) / 2; 38 | long coinsUsed = (mid * (mid + 1)) / 2; 39 | if (coinsUsed == n) 40 | return (int) mid; 41 | if (coinsUsed < n) { 42 | begin = mid + 1; 43 | } else { 44 | end = mid - 1; 45 | } 46 | } 47 | return (int) end; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 509 Fibonacci Number.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * The Fibonacci numbers, commonly denoted F(n) 4 | * form a sequence, called the Fibonacci sequence, 5 | * such that each number is the sum of the two 6 | * preceding ones, starting from 0 and 1. That is, 7 | * 8 | * F(0) = 0, F(1) = 1 9 | * F(n) = F(n - 1) + F(n - 2), for n > 1. 10 | * Given n, calculate F(n). 11 | * 12 | * 13 | * Example 1: 14 | * Input: n = 2 15 | * Output: 1 16 | * Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 17 | * 18 | * Example 2: 19 | * Input: n = 3 20 | * Output: 2 21 | * Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 22 | * 23 | * Example 3: 24 | * Input: n = 4 25 | * Output: 3 26 | * Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 27 | * 28 | * 29 | * Constraints: 30 | * 0 <= n <= 30 31 | */ 32 | class Fibonacci { 33 | public int fibRecursive(int n) { 34 | if (n == 0 || n == 1) 35 | return n; 36 | return fibRecursive(n - 1) + 37 | fibIterative(n - 2); 38 | } 39 | 40 | public int fibIterative(int n) { 41 | if (n == 0 || n == 1) 42 | return n; 43 | int first = 0, second = 1; 44 | for (int i = 1; i < n; i++) { 45 | int next = first + second; 46 | first = second; 47 | second = next; 48 | } 49 | return second; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 58 Length of Last Word.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int lengthOfLastWord(String s) { 3 | s = s.trim(); 4 | for (int i = s.length() - 1; i >= 0; i--) { 5 | if (s.charAt(i) == ' ') { 6 | return s.length() - (i + 1); 7 | } 8 | } 9 | return s.length(); 10 | } 11 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 66 Plus One using Math.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * You are given a large integer represented as an 4 | * integer array digits, where each digits[i] is 5 | * the ith digit of the integer. The digits are 6 | * ordered from most significant to least significant 7 | * in left-to-right order. The large integer does 8 | * not contain any leading 0's. 9 | * 10 | * Increment the large integer by one and return 11 | * the resulting array of digits. 12 | * 13 | * 14 | * Example 1: 15 | * Input: digits = [1,2,3] 16 | * Output: [1,2,4] 17 | * Explanation: The array represents the integer 123. 18 | * Incrementing by one gives 123 + 1 = 124. 19 | * Thus, the result should be [1,2,4]. 20 | * 21 | * Example 2: 22 | * Input: digits = [4,3,2,1] 23 | * Output: [4,3,2,2] 24 | * Explanation: The array represents the integer 4321. 25 | * Incrementing by one gives 4321 + 1 = 4322. 26 | * Thus, the result should be [4,3,2,2]. 27 | * 28 | * Example 3: 29 | * Input: digits = [9] 30 | * Output: [1,0] 31 | * Explanation: The array represents the integer 9. 32 | * Incrementing by one gives 9 + 1 = 10. 33 | * Thus, the result should be [1,0]. 34 | * 35 | * Constraints: 36 | * 1 <= digits.length <= 100 37 | * 0 <= digits[i] <= 9 38 | * digits does not contain any leading 0's. 39 | */ 40 | class PlusOne { 41 | public static void main(String[] args) { 42 | PlusOne plusOne = new PlusOne(); 43 | int[] res = plusOne.plusOne(new int[] { 9, 9, 9, 9 }); 44 | for (int item : res) { 45 | System.out.print(" " + item); 46 | } 47 | } 48 | 49 | public int[] plusOne(int[] digits) { 50 | int carry = 1; 51 | for (int i = digits.length - 1; carry > 0 && i >= 0; i--) { 52 | int temp = carry; 53 | carry = (digits[i] + carry) / 10; 54 | digits[i] = (digits[i] + temp) % 10; 55 | } 56 | if (carry != 1) { 57 | return digits; 58 | } else { 59 | int[] res = new int[digits.length + 1]; 60 | res[0] = 1; 61 | for (int i = 0; i < digits.length; i++) { 62 | res[i + 1] = digits[i]; 63 | } 64 | return res; 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 66 Plus One.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] plusOne(int[] digits) { 3 | for (int i = digits.length - 1; i >= 0; i--) { 4 | if (digits[i] != 9) { 5 | digits[i]++; 6 | return digits; 7 | } else { 8 | digits[i] = 0; 9 | } 10 | } 11 | 12 | int[] newDigits = new int[digits.length + 1]; 13 | newDigits[0] = 1; 14 | return newDigits; 15 | } 16 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 67 Add Binary.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String addBinary(String a, String b) { 3 | StringBuilder sb = new StringBuilder(); 4 | int maxLength = Math.max(a.length(), b.length()); 5 | 6 | int carry = 0; 7 | for (int i = 0; i < maxLength; i++) { 8 | int aIndex = (a.length() - 1) - i; 9 | int bIndex = (b.length() - 1) - i; 10 | char aChar = aIndex >= 0 ? a.charAt(aIndex) : '0'; 11 | char bChar = bIndex >= 0 ? b.charAt(bIndex) : '0'; 12 | int aVal = aChar - '0'; 13 | int bVal = bChar - '0'; 14 | 15 | int sum = aVal + bVal + carry; 16 | int res = sum % 2; 17 | carry = sum / 2; 18 | sb.append(res); 19 | } 20 | 21 | if (carry == 1) { 22 | sb.append(carry); 23 | } 24 | 25 | return sb.reverse().toString(); 26 | } 27 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 69 Sqrt(x).java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given a non-negative integer x, compute and 4 | * return the square root of x. 5 | * 6 | * Since the return type is an integer, the 7 | * decimal digits are truncated, and only the 8 | * integer part of the result is returned. 9 | * 10 | * Note: You are not allowed to use any built-in 11 | * exponent function or operator, such as 12 | * pow(x, 0.5) or x ** 0.5. 13 | * 14 | * Example 1: 15 | * Input: x = 4 16 | * Output: 2 17 | * 18 | * Example 2: 19 | * Input: x = 8 20 | * Output: 2 21 | * Explanation: The square root of 8 is 2.82842..., 22 | * and since the decimal part is truncated, 23 | * 2 is returned. 24 | * 25 | * 26 | * Constraints: 27 | * 0 <= x <= 231 - 1 28 | */ 29 | class SquareRoot { 30 | public int mySqrt(int x) { 31 | int beg = 0, end = x; 32 | while (beg <= end) { 33 | int mid = beg + (end - beg) / 2; 34 | long square = ((long) mid) * mid; 35 | if (square == x) { 36 | return mid; 37 | } else if (square > x) { 38 | end = mid - 1; 39 | } else { 40 | beg = mid + 1; 41 | } 42 | } 43 | return end; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 70 Climbing Stairs.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * You are climbing a staircase. It takes n steps 4 | * to reach the top. 5 | * 6 | * Each time you can either climb 1 or 2 steps. 7 | * In how many distinct ways can you climb to 8 | * the top? 9 | * 10 | * Example 1: 11 | * Input: n = 2 12 | * Output: 2 13 | * Explanation: There are two ways to climb to the top. 14 | * 1. 1 step + 1 step 15 | * 2. 2 steps 16 | * 17 | * Example 2: 18 | * Input: n = 3 19 | * Output: 3 20 | * Explanation: There are three ways to climb to the top. 21 | * 1. 1 step + 1 step + 1 step 22 | * 2. 1 step + 2 steps 23 | * 3. 2 steps + 1 step 24 | * 25 | * 26 | * Constraints: 27 | * 1 <= n <= 45 28 | */ 29 | class ClimbingStairs { 30 | /** 31 | * f(n) = f(n-1) + f(n-2) 32 | */ 33 | public int climbStairs(int n) { 34 | if (n == 1) 35 | return 1; 36 | if (n == 2) 37 | return 2; 38 | 39 | int first = 1, second = 2, current = 0; 40 | for (int i = 2; i < n; i++) { 41 | current = first + second; 42 | first = second; 43 | second = current; 44 | } 45 | return current; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 700 Search in a Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * You are given the root of a binary search tree 3 | * (BST) and an integer val. 4 | * 5 | * Find the node in the BST that the node's value 6 | * equals val and return the subtree rooted with 7 | * that node. If such a node does not exist, 8 | * return null. 9 | * 10 | * Example 1: 11 | * 4 12 | * 2 7 13 | * 1 3 X X 14 | * Input: root = [4,2,7,1,3], val = 2 15 | * Output: [2,1,3] 16 | * 17 | * Example 2: 18 | * 4 19 | * 2 7 20 | * 1 3 X X 21 | * Input: root = [4,2,7,1,3], val = 5 22 | * Output: [] 23 | * 24 | * 25 | * Constraints: 26 | * 27 | * The number of nodes in the tree is in the 28 | * range [1, 5000]. 29 | * 1 <= Node.val <= 107 30 | * root is a binary search tree. 31 | * 1 <= val <= 107 32 | */ 33 | class SearchInBST { 34 | public TreeNode searchBST(TreeNode root, int val) { 35 | if (root == null) 36 | return null; 37 | if (root.val == val) 38 | return root; 39 | if (root.val < val) { 40 | return searchBST(root.right, val); 41 | } 42 | return searchBST(root.left, val); 43 | } 44 | } 45 | 46 | class TreeNode { 47 | int val; 48 | TreeNode left; 49 | TreeNode right; 50 | TreeNode() {} 51 | TreeNode(int val) { this.val = val; } 52 | TreeNode(int val, TreeNode left, TreeNode right) { 53 | this.val = val; 54 | this.left = left; 55 | this.right = right; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 83 Remove Duplicates from Sorted List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode() {} 7 | * ListNode(int val) { this.val = val; } 8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 | * } 10 | */ 11 | class Solution { 12 | public ListNode deleteDuplicates(ListNode head) { 13 | ListNode current = head; 14 | while (current != null && current.next != null) { 15 | if (current.val == current.next.val) { 16 | current.next = current.next.next; 17 | } else { 18 | current = current.next; 19 | } 20 | } 21 | return head; 22 | } 23 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Sorting.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public void merge(int[] nums1, int m, int[] nums2, int n) { 5 | // O(n) 6 | for (int i = 0; i < n; i++) { 7 | nums1[m+i] = nums2[i]; 8 | } 9 | // O((m+n) * log(m+n)) 10 | Arrays.sort(nums1); 11 | } 12 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array using Two Pointers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void merge(int[] nums1, int m, int[] nums2, int n) { 3 | int i = m-1; 4 | int j = n-1; 5 | int k = nums1.length - 1; 6 | 7 | // O(m+n) 8 | while (j >= 0) { 9 | if (i >= 0 && nums1[i] > nums2[j]) { 10 | nums1[k] = nums1[i]; 11 | i--; 12 | k--; 13 | } else { 14 | nums1[k] = nums2[j]; 15 | j--; 16 | k--; 17 | } 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 88 Merge Sorted Array.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | /** 5 | * You are given two integer arrays nums1 and 6 | * nums2, sorted in non-decreasing order, and two 7 | * integers m and n, representing the number of 8 | * elements in nums1 and nums2 respectively. 9 | * 10 | * Merge nums1 and nums2 into a single array 11 | * sorted in non-decreasing order. 12 | * 13 | * The final sorted array should not be returned 14 | * by the function, but instead be stored inside 15 | * the array nums1. To accommodate this, nums1 has 16 | * a length of m + n, where the first m elements 17 | * denote the elements that should be merged, and 18 | * the last n elements are set to 0 and should be 19 | * ignored. nums2 has a length of n. 20 | * 21 | * 22 | * Example 1: 23 | * Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = 24 | * [2,5,6], n = 3 Output: [1,2,2,3,5,6] 25 | * Explanation: The arrays we are merging are 26 | * [1,2,3] and [2,5,6]. The result of the merge is 27 | * [1,2,2,3,5,6] with the underlined elements 28 | * coming from nums1. 29 | * 30 | * Example 2: 31 | * Input: nums1 = [1], m = 1, nums2 = [], n = 0 32 | * Output: [1] Explanation: The arrays we are 33 | * merging are [1] and []. The result of the merge 34 | * is [1]. 35 | * 36 | * Example 3: 37 | * Input: nums1 = [0], m = 0, nums2 = [1], n = 1 38 | * Output: [1] Explanation: The arrays we are 39 | * merging are [] and [1]. The result of the merge 40 | * is [1]. Note that because m = 0, there are no 41 | * elements in nums1. The 0 is only there to 42 | * ensure the merge result can fit in nums1. 43 | * 44 | * Constraints: 45 | * nums1.length == m + n nums2.length == n 0 <= m, 46 | * n <= 200 1 <= m + n <= 200 -109 <= nums1[i], 47 | * nums2[j] <= 109 48 | */ 49 | class MergeSortedArray { 50 | 51 | public static void main(String[] args) { 52 | MergeSortedArray merge = new MergeSortedArray(); 53 | int[] nums1 = new int[] { 1, 2, 3, 0, 0, 0, 0 }; 54 | int[] nums2 = new int[] { 0, 2, 5, 6 }; 55 | merge.merge(nums1, 3, nums2, 4); 56 | System.out.println("Output is:" + Arrays.toString(nums1)); 57 | } 58 | 59 | public void merge(int[] nums1, int m, 60 | int[] nums2, int n) { 61 | int i = m - 1; 62 | int j = n - 1; 63 | int k = m + n - 1; 64 | while (i >= 0 && j >= 0) { 65 | if (nums1[i] >= nums2[j]) { 66 | nums1[k--] = nums1[i--]; 67 | } else { 68 | nums1[k--] = nums2[j--]; 69 | } 70 | } 71 | 72 | while (j >= 0) { 73 | nums1[k--] = nums2[j--]; 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 892 Surface Area of 3D Shapes.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * You are given an n x n grid where you have 4 | * placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] 5 | * represents a tower of v cubes placed on top 6 | * of cell (i, j). 7 | * 8 | * After placing these cubes, you have decided to 9 | * glue any directly adjacent cubes to each other, 10 | * forming several irregular 3D shapes. 11 | * 12 | * Return the total surface area of the resulting 13 | * shapes. 14 | * 15 | * Note: The bottom face of each shape counts 16 | * toward its surface area. 17 | * 18 | * Example 1: 19 | * Input: grid = [[1,2], 20 | * [3,4]] 21 | * Output: 34 = 4 + 7 + 10 + 13 = 34 22 | * 23 | * Example 2: 24 | * Input: grid = [[1,1,1], 25 | * [1,0,1], 26 | * [1,1,1]] 27 | * Output: 32 28 | * 29 | * Example 3: 30 | * Input: grid = [[2,2,2],[2,1,2],[2,2,2]] 31 | * Output: 46 32 | * 33 | * Constraints: 34 | * n == grid.length == grid[i].length 35 | * 1 <= n <= 50 36 | * 0 <= grid[i][j] <= 50 37 | */ 38 | class SurfaceAreaOf3DShapes { 39 | public static void main(String[] args) { 40 | SurfaceAreaOf3DShapes shapes = new SurfaceAreaOf3DShapes(); 41 | int[][] grid = new int[][] { { 1, 2 }, { 3, 4 } }; 42 | System.out.println("Area is:" + shapes.surfaceArea(grid)); 43 | } 44 | 45 | public int surfaceArea(int[][] grid) { 46 | int total = 0; 47 | int size = grid.length; 48 | for (int i = 0; i < size; i++) { 49 | for (int j = 0; j < size; j++) { 50 | if (grid[i][j] == 0) 51 | continue; 52 | int areaGained = 4 * grid[i][j] + 2; 53 | int areaLost = 0; 54 | if (i - 1 >= 0) { 55 | areaLost += Math.min(grid[i][j], grid[i - 1][j]); 56 | } 57 | if (i + 1 < size) { 58 | areaLost += Math.min(grid[i][j], grid[i + 1][j]); 59 | } 60 | if (j - 1 >= 0) { 61 | areaLost += Math.min(grid[i][j], grid[i][j - 1]); 62 | } 63 | if (j + 1 < size) { 64 | areaLost += Math.min(grid[i][j], grid[i][j + 1]); 65 | } 66 | total += areaGained - areaLost; 67 | } 68 | } 69 | 70 | return total; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 9 Palindrome Number.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given an integer x, return true if x is 4 | * palindrome integer. 5 | * 6 | * An integer is a palindrome when it reads 7 | * the same backward as forward. 8 | * 9 | * For example, 121 is a palindrome while 123 10 | * is not. 11 | * 12 | * 13 | * Example 1: 14 | * Input: x = 121 15 | * Output: true 16 | * Explanation: 121 reads as 121 from left to 17 | * right and from right to left. 18 | * 19 | * Example 2: 20 | * Input: x = -121 21 | * Output: false 22 | * Explanation: From left to right, it reads 23 | * -121. From right to left, it becomes 121-. 24 | * Therefore it is not a palindrome. 25 | * 26 | * Example 3: 27 | * Input: x = 10 28 | * Output: false 29 | * Explanation: Reads 01 from right to left. 30 | * Therefore it is not a palindrome. 31 | * 32 | * 33 | * Constraints: 34 | * -231 <= x <= 231 - 1 35 | */ 36 | class PalindromeNumber { 37 | public boolean isPalindrome(int x) { 38 | if (x < 0) 39 | return false; 40 | int rev = 0; 41 | int temp = x; 42 | while (temp > 0) { 43 | int rem = temp % 10; 44 | rev = rev * 10 + rem; 45 | temp = temp / 10; 46 | } 47 | return x == rev; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 933 Number of Recent Calls.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.LinkedList; 3 | import java.util.Queue; 4 | 5 | /** 6 | * You have a RecentCounter class which counts the 7 | * number of recent requests within a certain time 8 | * frame. 9 | * 10 | * Implement the RecentCounter class: 11 | * 12 | * RecentCounter() Initializes the counter with 13 | * zero recent requests. 14 | * 15 | * int ping(int t) Adds a new request at time t, 16 | * where t represents some time in milliseconds, 17 | * and returns the number of requests that has 18 | * happened in the past 3000 milliseconds 19 | * (including the new request). Specifically, 20 | * return the number of requests that have happened 21 | * in the inclusive range [t - 3000, t]. 22 | * 23 | * It is guaranteed that every call to ping uses 24 | * a strictly larger value of t than the previous 25 | * call. 26 | * 27 | * Example 1: 28 | * Input 29 | * ["RecentCounter", "ping", "ping", "ping", "ping"] 30 | * [[], [1], [100], [3001], [3002]] 31 | * Output 32 | * [null, 1, 2, 3, 3] 33 | * 34 | * Explanation 35 | * RecentCounter recentCounter = new RecentCounter(); 36 | * recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1 37 | * recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 38 | * 2 39 | * recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], 40 | * return 3 41 | * recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is 42 | * [2,3002], return 3 43 | * 44 | * 45 | * Constraints: 46 | * 47 | * 1 <= t <= 109 48 | * Each test case will call ping with strictly 49 | * increasing values of t. 50 | * At most 104 calls will be made to ping 51 | */ 52 | class RecentCounter { 53 | 54 | private Queue queue; 55 | 56 | RecentCounter() { 57 | queue = new LinkedList<>(); 58 | } 59 | 60 | public int ping(int t) { 61 | queue.offer(t); 62 | while (queue.peek() < t - 3000) { 63 | queue.poll(); 64 | } 65 | return queue.size(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 977 Squares of a Sorted Array.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given an integer array nums sorted in 4 | * non-decreasing order, return an array of the 5 | * squares of each number sorted in non-decreasing 6 | * order. 7 | * 8 | * Example 1: 9 | * Input: nums = [-4,-1,0,3,10] 10 | * Output: [0,1,9,16,100] 11 | * Explanation: After squaring, the array becomes 12 | * [16,1,0,9,100]. 13 | * After sorting, it becomes [0,1,9,16,100]. 14 | * 15 | * Example 2: 16 | * Input: nums = [-7,-3,2,3,11] 17 | * Output: [4,9,9,49,121] 18 | * 19 | * 20 | * Constraints: 21 | * 1 <= nums.length <= 104 22 | * -104 <= nums[i] <= 104 23 | * nums is sorted in non-decreasing order. 24 | */ 25 | class SquaresOfSortedArray { 26 | public int[] sortedSquares(int[] nums) { 27 | int beg = 0, end = nums.length - 1; 28 | int[] result = new int[nums.length]; 29 | for (int i = 0; i < nums.length; i++) { 30 | int sq1 = (int) Math.pow(nums[beg], 2); 31 | int sq2 = (int) Math.pow(nums[end], 2); 32 | if (sq1 >= sq2) { 33 | result[nums.length - 1 - i] = sq1; 34 | beg++; 35 | } else { 36 | result[nums.length - 1 - i] = sq2; 37 | end--; 38 | } 39 | } 40 | return result; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /1 Leetcode Easy Problems/Leetcode 997 Find the Town Judge.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * In a town, there are n people labeled from 4 | * 1 to n. There is a rumor that one of these 5 | * people is secretly the town judge. 6 | * 7 | * If the town judge exists, then: 8 | * 9 | * The town judge trusts nobody. 10 | * Everybody (except for the town judge) trusts 11 | * the town judge. 12 | * There is exactly one person that satisfies 13 | * properties 1 and 2. 14 | * You are given an array trust where 15 | * trust[i] = [ai, bi] representing that the 16 | * person labeled ai trusts the person labeled bi. 17 | * 18 | * Return the label of the town judge if the town 19 | * judge exists and can be identified, or 20 | * return -1 otherwise. 21 | * 22 | * Example 1: 23 | * Input: n = 2, trust = [[1,2]] 24 | * Output: 2 25 | * 26 | * Example 2: 27 | * Input: n = 3, trust = [[1,3],[2,3]] 28 | * Output: 3 29 | * 30 | * Example 3: 31 | * Input: n = 3, trust = [[1,3],[2,3],[3,1]] 32 | * Output: -1 33 | * 34 | * 35 | * Constraints: 36 | * 1 <= n <= 1000 37 | * 0 <= trust.length <= 104 38 | * trust[i].length == 2 39 | * All the pairs of trust are unique. 40 | * ai != bi 41 | * 1 <= ai, bi <= n 42 | */ 43 | class FindTheTownJudge { 44 | public int findJudge(int n, int[][] trust) { 45 | int[] count = new int[n + 1]; 46 | for (int[] trustRow : trust) { 47 | count[trustRow[0]]--; 48 | count[trustRow[1]]++; 49 | } 50 | 51 | for (int i = 1; i < count.length; i++) { 52 | if (count[i] == n - 1) { 53 | return i; 54 | } 55 | } 56 | 57 | return -1; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 11 Container With Most Water.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * You are given an integer array height of length n. 4 | * There are n vertical lines drawn such that 5 | * the two endpoints of the ith line are (i, 0) 6 | * and (i, height[i]). 7 | * 8 | * Find two lines that together with the x-axis form 9 | * a container, such that the container contains 10 | * the most water. 11 | * 12 | * Return the maximum amount of water a container 13 | * can store. 14 | * 15 | * Notice that you may not slant the container. 16 | * 17 | * Example 1: 18 | * Input: height = [1,8,6,2,5,4,8,3,7] 19 | * Output: 49 20 | * Explanation: The above vertical lines are 21 | * represented by array [1,8,6,2,5,4,8,3,7]. In this case, 22 | * the max area of water the container can contain is 49. 23 | * 24 | * Example 2: 25 | * Input: height = [1,1] 26 | * Output: 1 27 | * 28 | * 29 | * Constraints: 30 | * n == height.length 31 | * 2 <= n <= 105 32 | * 0 <= height[i] <= 104 33 | */ 34 | class ContainerWithMostWater { 35 | public static void main(String[] args) { 36 | ContainerWithMostWater water = new ContainerWithMostWater(); 37 | int[] height = new int[] { 1, 8, 6, 2, 5, 4, 8, 3, 7 }; 38 | System.out.println("Output is:" + water.maxArea(height)); 39 | } 40 | 41 | public int maxArea(int[] height) { 42 | int maxArea = 0; 43 | int left = 0, right = height.length - 1; 44 | while (left < right) { 45 | int minHeight = Math.min(height[left], 46 | height[right]); 47 | int currArea = minHeight * (right - left); 48 | maxArea = Math.max(maxArea, currArea); 49 | 50 | if (height[left] < height[right]) { 51 | left++; 52 | } else { 53 | right--; 54 | } 55 | } 56 | 57 | return maxArea; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 15 3Sum.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | /** 5 | * Given an integer array nums, return all the 6 | * triplets [nums[i], nums[j], nums[k]] such that 7 | * i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 8 | * 9 | * Notice that the solution set must not contain 10 | * duplicate triplets. 11 | * 12 | * Example 1: 13 | * Input: nums = [-1,0,1,2,-1,-4] 14 | * Output: [[-1,-1,2],[-1,0,1]] 15 | * 16 | * Example 2: 17 | * Input: nums = [] 18 | * Output: [] 19 | * 20 | * Example 3: 21 | * Input: nums = [0] 22 | * Output: [] 23 | * 24 | * Constraints: 25 | * 0 <= nums.length <= 3000 26 | * -105 <= nums[i] <= 105 27 | */ 28 | class ThreeSum { 29 | public static void main(String[] args) { 30 | ThreeSum threeSum = new ThreeSum(); 31 | int[] nums = new int[] { -1, 0, 1, 2, -1, -4 }; 32 | System.out.println("Possible Triplets:" + 33 | threeSum.threeSum(nums)); 34 | } 35 | 36 | public Set> threeSum(int[] nums) { 37 | Arrays.sort(nums); 38 | Set> res = new HashSet<>(); 39 | for (int i = 0; i < nums.length - 2; i++) { 40 | int beg = i + 1; 41 | int end = nums.length - 1; 42 | while (beg < end) { 43 | int sum = nums[i] + nums[beg] + nums[end]; 44 | if (sum == 0) { 45 | res.add(Arrays.asList(nums[i], 46 | nums[beg], nums[end])); 47 | beg++; 48 | end--; 49 | } else if (sum < 0) { 50 | beg++; 51 | } else { 52 | end--; 53 | } 54 | } 55 | } 56 | 57 | return res; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 189 Rotate Array.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | /** 5 | * Given an array, rotate the array to the right 6 | * by k steps, where k is non-negative. 7 | * 8 | * Example 1: 9 | * Input: nums = [1,2,3,4,5,6,7], k = 3 10 | * Output: [5,6,7,1,2,3,4] 11 | * Explanation: 12 | * rotate 1 steps to the right: [7,1,2,3,4,5,6] 13 | * rotate 2 steps to the right: [6,7,1,2,3,4,5] 14 | * rotate 3 steps to the right: [5,6,7,1,2,3,4] 15 | * 16 | * Example 2: 17 | * Input: nums = [-1,-100,3,99], k = 2 18 | * Output: [3,99,-1,-100] 19 | * Explanation: 20 | * rotate 1 steps to the right: [99,-1,-100,3] 21 | * rotate 2 steps to the right: [3,99,-1,-100] 22 | * 23 | * 24 | * Constraints: 25 | * 1 <= nums.length <= 105 26 | * -231 <= nums[i] <= 231 - 1 27 | * 0 <= k <= 105 28 | */ 29 | class RotateArray { 30 | public static void main(String[] args) { 31 | RotateArray rotateArray = new RotateArray(); 32 | int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7 }; 33 | System.out.print("Rotating " + Arrays.toString(nums)); 34 | rotateArray.rotate(nums, 10); 35 | System.out.println(" : " + Arrays.toString(nums)); 36 | } 37 | 38 | public void rotate(int[] nums, int k) { 39 | // Another way: int[] copyArr = nums.clone(); 40 | int[] copyArr = new int[nums.length]; 41 | for (int i = 0; i < nums.length; i++) { 42 | copyArr[i] = nums[i]; 43 | } 44 | 45 | for (int i = 0; i < nums.length; i++) { 46 | nums[(i + k) % nums.length] = copyArr[i]; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 204 Count Primes.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given an integer n, return the number of prime 4 | * numbers that are strictly less than n. 5 | * 6 | * Example 1: 7 | * Input: n = 10 8 | * Output: 4 9 | * Explanation: There are 4 prime numbers less 10 | * than 10, they are 2, 3, 5, 7 11 | * 12 | * Example 2: 13 | * Input: n = 0 14 | * Output: 0 15 | * 16 | * Example 3: 17 | * Input: n = 1 18 | * Output: 0 19 | * 20 | * Constraints: 21 | * 0 <= n <= 5 * 106 22 | */ 23 | class CountPrimes { 24 | public static void main(String[] args) { 25 | CountPrimes counter = new CountPrimes(); 26 | System.out.println("No of prime are:" 27 | + counter.countPrimes(100)); 28 | } 29 | 30 | public int countPrimes(int n) { 31 | boolean[] notPrime = new boolean[n]; 32 | int countPrime = 0; 33 | for (int i = 2; i < n; i++) { 34 | if (!notPrime[i]) { 35 | countPrime++; 36 | for (int j = 2; i * j < n; j++) { 37 | notPrime[i * j] = true; 38 | } 39 | } 40 | } 41 | return countPrime; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array using Sorting.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given an integer array nums and an integer k, 4 | * return the kth largest element in the array. 5 | * 6 | * Note that it is the kth largest element in the 7 | * sorted order, not the kth distinct element. 8 | * 9 | * Example 1: 10 | * Input: nums = [3,2,1,5,6,4], k = 2 11 | * Output: 5 12 | * 13 | * Example 2: 14 | * Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 15 | * Output: 4 16 | * 17 | * Constraints: 18 | * 1 <= k <= nums.length <= 104 19 | * -104 <= nums[i] <= 104 20 | */ 21 | class KthLargestElement { 22 | public static void main(String[] args) { 23 | KthLargestElement kthLargest = new KthLargestElement(); 24 | int[] nums = new int[] { 3, 2, 3, 1, 2, 4, 5, 5, 6 }; 25 | System.out.println("Kth largest is:" + 26 | kthLargest.findKthLargest(nums, 4)); 27 | } 28 | 29 | public int findKthLargest(int[] nums, int k) { 30 | return quickSelect(nums, 0, nums.length - 1, k); 31 | } 32 | 33 | private int quickSelect(int[] nums, int beg, 34 | int end, int k) { 35 | int pivot = beg; 36 | for (int i = pivot; i < end; i++) { 37 | if (nums[i] <= nums[end]) { 38 | swap(nums, i, pivot); 39 | pivot++; 40 | } 41 | } 42 | swap(nums, pivot, end); 43 | int count = end - pivot + 1; 44 | if (count == k) 45 | return nums[pivot]; 46 | if (count > k) { 47 | return quickSelect(nums, pivot + 1, end, k); 48 | } else { 49 | return quickSelect(nums, beg, pivot - 1, 50 | k - count); 51 | } 52 | } 53 | 54 | private void swap(int[] nums, int i, int j) { 55 | int temp = nums[i]; 56 | nums[i] = nums[j]; 57 | nums[j] = temp; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 215 Kth Largest Element in an Array.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.PriorityQueue; 3 | 4 | /** 5 | * Given an integer array nums and an integer k, 6 | * return the kth largest element in the array. 7 | * 8 | * Note that it is the kth largest element in the 9 | * sorted order, not the kth distinct element. 10 | * 11 | * Example 1: 12 | * Input: nums = [3,2,1,5,6,4], k = 2 13 | * Output: 5 14 | * 15 | * Example 2: 16 | * Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 17 | * Output: 4 18 | * 19 | * Constraints: 20 | * 1 <= k <= nums.length <= 104 21 | * -104 <= nums[i] <= 104 22 | */ 23 | class KthLargestElement { 24 | public static void main(String[] args) { 25 | KthLargestElement kthLargest = new KthLargestElement(); 26 | int[] nums = new int[] { 3, 2, 3, 1, 2, 4, 5, 5, 6 }; 27 | System.out.println("Kth largest is:" + 28 | kthLargest.findKthLargest(nums, 6)); 29 | } 30 | 31 | public int findKthLargest(int[] nums, int k) { 32 | PriorityQueue kLargest = new PriorityQueue<>(); 33 | for (int num : nums) { 34 | kLargest.add(num); 35 | if (kLargest.size() > k) { 36 | kLargest.poll(); 37 | } 38 | } 39 | 40 | return kLargest.peek(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses using Backtracking.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | /** 6 | * Given n pairs of parentheses, write a function 7 | * to generate all combinations of well-formed 8 | * parentheses. 9 | * 10 | * Example 1: 11 | * Input: n = 3 12 | * Output: ["((()))","(()())","(())()","()(())","()()()"] 13 | * 14 | * Example 2: 15 | * Input: n = 1 16 | * Output: ["()"] 17 | * 18 | * Constraints: 19 | * 1 <= n <= 8 20 | */ 21 | class GenerateParentheses { 22 | public static void main(String[] args) { 23 | GenerateParentheses generator = new GenerateParentheses(); 24 | List parentheses = generator.generateParenthesis(3); 25 | System.out.println("Generate output:"); 26 | for (String parenthesis : parentheses) { 27 | System.out.print(" " + parenthesis); 28 | } 29 | } 30 | 31 | public List generateParenthesis(int n) { 32 | List result = new ArrayList<>(); 33 | backtrack(result, new StringBuilder(), 0, 0, n); 34 | return result; 35 | } 36 | 37 | private void backtrack(List result, 38 | StringBuilder cur, int open, int close, 39 | int max) { 40 | if (cur.length() == max * 2) { 41 | result.add(cur.toString()); 42 | return; 43 | } 44 | 45 | if (open < max) { 46 | cur.append('('); 47 | backtrack(result, cur, open + 1, close, 48 | max); 49 | cur.deleteCharAt(cur.length() - 1); 50 | } 51 | if (close < open) { 52 | cur.append(')'); 53 | backtrack(result, cur, open, close + 1, 54 | max); 55 | cur.deleteCharAt(cur.length() - 1); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 22 Generate Parentheses.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | /** 6 | * Given n pairs of parentheses, write a function 7 | * to generate all combinations of well-formed 8 | * parentheses. 9 | * 10 | * Example 1: 11 | * Input: n = 3 12 | * Output: ["((()))","(()())","(())()","()(())","()()()"] 13 | * 14 | * Example 2: 15 | * Input: n = 1 16 | * Output: ["()"] 17 | * 18 | * Constraints: 19 | * 1 <= n <= 8 20 | */ 21 | class GenerateParentheses { 22 | 23 | public static void main(String[] args) { 24 | GenerateParentheses obj = new GenerateParentheses(); 25 | System.out.println("Here is the result:"); 26 | for (String combi : obj.generateParenthesis(3)) { 27 | System.out.print(combi + ", "); 28 | } 29 | } 30 | 31 | public List generateParenthesis(int n) { 32 | List combinations = new ArrayList<>(); 33 | generateAllCombinations(new char[n * 2], 0, 34 | combinations); 35 | return combinations; 36 | } 37 | 38 | private void generateAllCombinations(char[] current, 39 | int pos, List combinations) { 40 | if (pos == current.length) { 41 | if (isValid(current)) { 42 | combinations.add(new String(current)); 43 | } 44 | } else { 45 | current[pos] = '('; 46 | generateAllCombinations(current, pos + 1, 47 | combinations); 48 | current[pos] = ')'; 49 | generateAllCombinations(current, pos + 1, 50 | combinations); 51 | } 52 | } 53 | 54 | private boolean isValid(char[] current) { 55 | int counter = 0; 56 | for (int i = 0; i < current.length; i++) { 57 | if (current[i] == '(') { 58 | counter++; 59 | } else { 60 | counter--; 61 | } 62 | if (counter < 0) 63 | return false; 64 | } 65 | return counter == 0; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 33 Search in Rotated Sorted Array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int search(int[] nums, int target) { 3 | int beg = 0, end = nums.length - 1; 4 | 5 | // First, find the smallest element's index (pivot index) 6 | while (beg < end) { 7 | int mid = (beg + end) / 2; 8 | if (nums[mid] > nums[end]) { 9 | beg = mid + 1; // pivot must be to the right of mid 10 | } else { 11 | end = mid; // pivot could be at mid, or to the left of mid 12 | } 13 | } 14 | // Now, beg == end == pivot index (smallest element index) 15 | int pivot = beg; 16 | 17 | // Reset beg and end for standard binary search, adjusted by pivot 18 | beg = 0; 19 | end = nums.length - 1; 20 | while (beg <= end) { 21 | int mid = (beg + end) / 2; 22 | int realMid = (mid + pivot) % nums.length; // Adjust mid to account for rotation 23 | 24 | if (nums[realMid] == target) { 25 | return realMid; 26 | } else if (nums[realMid] < target) { 27 | beg = mid + 1; 28 | } else { 29 | end = mid - 1; 30 | } 31 | } 32 | return -1; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 36 Valid Sudoku.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashSet; 3 | import java.util.Set; 4 | 5 | /** 6 | * Determine if a 9 x 9 Sudoku board is valid. Only 7 | * the filled cells need to be validated according 8 | * to the following rules: 9 | * 10 | * Each row must contain the digits 1-9 without repetition. 11 | * Each column must contain the digits 1-9 without 12 | * repetition. 13 | * Each of the nine 3 x 3 sub-boxes of the grid must 14 | * contain the digits 1-9 without repetition. 15 | * Note: 16 | * 17 | * A Sudoku board (partially filled) could be valid 18 | * but is not necessarily solvable. 19 | * Only the filled cells need to be validated 20 | * according to the mentioned rules. 21 | * 22 | * 23 | * Example 1: 24 | * Input: board = 25 | * { {'5','3','.','.','7','.','.','.','.'} 26 | * , {'6','.','.','1','9','5','.','.','.'} 27 | * , {'.','9','8','.','.','.','.','6','.'} 28 | * , {'8','.','.','.','6','.','.','.','3'} 29 | * , {'4','.','.','8','.','3','.','.','1'} 30 | * , {'7','.','.','.','2','.','.','.','6'} 31 | * , {'.','6','.','.','.','.','2','8','.'} 32 | * , {'.','.','.','4','1','9','.','.','5'} 33 | * , {'.','.','.','.','8','.','.','7','9'}} 34 | * Output: true 35 | * 36 | * Example 2: 37 | * Input: board = 38 | * [["8","3",".",".","7",".",".",".","."] 39 | * ,["6",".",".","1","9","5",".",".","."] 40 | * ,[".","9","8",".",".",".",".","6","."] 41 | * ,["8",".",".",".","6",".",".",".","3"] 42 | * ,["4",".",".","8",".","3",".",".","1"] 43 | * ,["7",".",".",".","2",".",".",".","6"] 44 | * ,[".","6",".",".",".",".","2","8","."] 45 | * ,[".",".",".","4","1","9",".",".","5"] 46 | * ,[".",".",".",".","8",".",".","7","9"]] 47 | * Output: false 48 | * 49 | * Explanation: Same as Example 1, except with the 50 | * 5 in the top left corner being modified to 8. 51 | * Since there are two 8's in the top left 3x3 52 | * sub-box, it is invalid. 53 | * 54 | * 55 | * Constraints: 56 | * board.length == 9 57 | * board[i].length == 9 58 | * board[i][j] is a digit 1-9 or '.'. 59 | */ 60 | class ValidSudoku { 61 | public static void main(String[] args) { 62 | ValidSudoku checker = new ValidSudoku(); 63 | char[][] puzzle = new char[][] { { '5', '3', '.', '.', '7', '.', '.', '.', '.' }, 64 | { '6', '.', '.', '1', '9', '5', '.', '.', '.' }, { '.', '9', '8', '.', '.', '.', '.', '6', '.' }, 65 | { '8', '.', '.', '.', '6', '.', '.', '.', '3' }, { '4', '.', '.', '8', '.', '3', '.', '.', '1' }, 66 | { '7', '.', '.', '.', '2', '.', '.', '.', '6' }, { '.', '6', '.', '.', '.', '.', '2', '8', '.' }, 67 | { '.', '.', '.', '4', '1', '9', '.', '.', '5' }, { '.', '.', '.', '.', '8', '.', '.', '7', '9' } }; 68 | System.out.println("IsValid:" + checker.isValidSudoku(puzzle)); 69 | } 70 | 71 | public boolean isValidSudoku(char[][] board) { 72 | Set visited = new HashSet<>(); 73 | for (int i = 0; i < 9; i++) { 74 | for (int j = 0; j < 9; j++) { 75 | char c = board[i][j]; 76 | if (c == '.') 77 | continue; 78 | if (!visited.add(c + "row" + i) || 79 | !visited.add(c + "col" + j) || 80 | !visited.add(c + "box" + i / 3 + "-" + j / 3)) { 81 | return false; 82 | } 83 | } 84 | } 85 | return true; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 53 Maximum Subarray.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Given an integer array nums, find the contiguous subarray (containing at 4 | * least one number) which has the largest sum and return its sum. A subarray is 5 | * a contiguous part of an array. 6 | *

7 | * Example 1 Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: 8 | * [4,-1,2,1] has the largest sum = 6. 9 | *

10 | * Example 2: Input: nums = [1] Output: 1 11 | *

12 | * Example 3: Input: nums = [5,4,-1,7,8] Output: 23 13 | *

14 | *

15 | * Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104 16 | */ 17 | class MaximumSubArray { 18 | public int maxSubArray(int[] nums) { 19 | int maxEndingHere = nums[0], maxSoFar = nums[0]; 20 | for (int i = 1; i < nums.length; i++) { 21 | maxEndingHere = Math.max(nums[i], nums[i] + maxEndingHere); 22 | maxSoFar = Math.max(maxEndingHere, maxSoFar); 23 | } 24 | return maxSoFar; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 540 Single Element in a Sorted Array.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * You are given a sorted array consisting of only 4 | * integers where every element appears exactly 5 | * twice, except for one element which appears exactly once. 6 | * 7 | * Return the single element that appears only once. 8 | * Your solution must run in O(log n) time and O(1) space. 9 | * 10 | * Example 1: 11 | * Input: nums = [1,1,2,3,3,4,4,8,8] 12 | * Output: 2 13 | * 14 | * Example 2: 0,1,2,3,4 ,5 ,6 15 | * Input: nums = [3,3,7,7,10,11,11] 16 | * Output: 10 17 | * 18 | * Constraints: 19 | * 1 <= nums.length <= 105 20 | * 0 <= nums[i] <= 105 21 | */ 22 | class SingleElementInASortedArray { 23 | public static void main(String[] args) { 24 | SingleElementInASortedArray finder = new SingleElementInASortedArray(); 25 | int[] nums = new int[] { 3, 3, 7, 7, 10, 11, 11 }; 26 | System.out.println("Duplicate is:" 27 | + finder.singleNonDuplicate(nums)); 28 | } 29 | 30 | public int singleNonDuplicate(int[] nums) { 31 | int left = 0, right = nums.length - 1; 32 | while (left < right) { 33 | int mid = left + (right - left) / 2; 34 | if ((mid % 2 == 0 && nums[mid] == nums[mid + 1]) || 35 | (mid % 2 == 1 && nums[mid] == nums[mid - 1])) { 36 | left = mid + 1; 37 | } else { 38 | right = mid - 1; 39 | } 40 | } 41 | return nums[left]; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 74 Search a 2D Matrix.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Write an efficient algorithm that searches for 4 | * a value target in an m x n integer matrix. 5 | * This matrix has the following properties: 6 | * 7 | * Integers in each row are sorted from left to right. 8 | * The first integer of each row is greater than 9 | * the last integer of the previous row. 10 | * 11 | * Example 1: 12 | * Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], 13 | * target = 3 14 | * Output: true 15 | * 16 | * Example 2: 17 | * Input: matrix = [[1,3,5,7],[10,11,16,20], 18 | * [23,30,34,60]], target = 13 19 | * Output: false 20 | * 21 | * Constraints: 22 | * m == matrix.length 23 | * n == matrix[i].length 24 | * 1 <= m, n <= 100 25 | * -104 <= matrix[i][j], target <= 104 26 | */ 27 | class SearchIn2DMatrix { 28 | public static void main(String[] args) { 29 | SearchIn2DMatrix search = new SearchIn2DMatrix(); 30 | int[][] nums = new int[][] { { 1, 3, 5, 7 }, 31 | { 10, 11, 16, 20 }, { 23, 30, 34, 60 } }; 32 | System.out.println("Element status: " 33 | + search.searchMatrix(nums, 24)); 34 | } 35 | 36 | public boolean searchMatrix(int[][] matrix, int target) { 37 | if (matrix == null || matrix.length == 0) 38 | return false; 39 | int m = matrix.length; 40 | int n = matrix[0].length; 41 | int tot = m * n; 42 | int beg = 0; 43 | int end = tot - 1; 44 | while (beg <= end) { 45 | int mid = (beg + end) / 2; 46 | int i = mid / n; 47 | int j = mid % n; 48 | if (matrix[i][j] == target) 49 | return true; 50 | else if (matrix[i][j] < target) 51 | beg = mid + 1; 52 | else 53 | end = mid - 1; 54 | } 55 | return false; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 78 Subsets using Dynamic Programming.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | /** 6 | * SAME PROBLEM IS SOLVED IN BACKTRACKING ALSO 7 | *

8 | * Given an integer array nums of unique elements, 9 | * return all possible subsets (the power set). 10 | *

11 | * The solution set must not contain duplicate 12 | * subsets. Return the solution in any order. 13 | *

14 | * Example 1: Input: nums = [1,2,3] Output: 15 | * [[],[1],[2],[1,2],[3],[1,3],[2,3], [1,2,3]] 16 | *

17 | * Example 2: Input: nums = [0] Output: [[],[0]] 18 | *

19 | * Constraints: 1 <= nums.length <= 10 -10 <= 20 | * nums[i] <= 10 All the numbers of nums are 21 | * unique. 22 | */ 23 | class Subsets { 24 | public static void main(String[] args) { 25 | Subsets subsets = new Subsets(); 26 | int[] nums = new int[] { 1, 2, 3, 4 }; 27 | System.out.println("PowerSet is:" + 28 | subsets.subsets(nums)); 29 | } 30 | 31 | public List> subsets(int[] nums) { 32 | List> res = new ArrayList<>(); 33 | res.add(new ArrayList<>()); 34 | 35 | for (int num : nums) { 36 | int length = res.size(); 37 | for (int i = 0; i < length; i++) { 38 | List copy = new ArrayList<>(res.get(i)); 39 | copy.add(num); 40 | res.add(copy); 41 | } 42 | } 43 | return res; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /2 Leetcode Medium Problems/Leetcode 78 Subsets.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | /** 6 | * SAME PROBLEM IS SOLVED IN DP ALSO 7 | *

8 | * Given an integer array nums of unique elements, 9 | * return all possible subsets (the power set). 10 | *

11 | * The solution set must not contain duplicate 12 | * subsets. Return the solution in any order. 13 | *

14 | * Example 1: Input: nums = [1,2,3] Output: 15 | * [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] 16 | *

17 | * Example 2: Input: nums = [0] Output: [[],[0]] 18 | *

19 | * Constraints: 1 <= nums.length <= 10 -10 <= 20 | * nums[i] <= 10 All the numbers of nums are 21 | * unique. 22 | */ 23 | class Subsets { 24 | public static void main(String[] args) { 25 | Subsets subsets = new Subsets(); 26 | int[] nums = new int[] {}; 27 | System.out.println("PowerSet is :" + 28 | subsets.subsets(nums)); 29 | } 30 | 31 | public List> subsets(int[] nums) { 32 | List> output = new ArrayList<>(); 33 | for (int i = 0; i <= nums.length; i++) { 34 | backtrack(output, i, 0, new ArrayList<>(), 35 | nums); 36 | } 37 | return output; 38 | } 39 | 40 | private void backtrack(List> output, 41 | int length, int beg, List curr, 42 | int[] nums) { 43 | 44 | if (curr.size() == length) { 45 | output.add(new ArrayList<>(curr)); 46 | return; 47 | } 48 | 49 | for (int i = beg; i < nums.length; i++) { 50 | curr.add(nums[i]); 51 | backtrack(output, length, i + 1, curr, 52 | nums); 53 | curr.remove(curr.size() - 1); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /3 Leetcode Hard Problems/Leetcode 51 N-Queens.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | 4 | /** 5 | * The n-queens puzzle is the problem of placing 6 | * n queens on an n x n chessboard such that no 7 | * two queens attack each other. 8 | * 9 | * Given an integer n, return any one solution 10 | * to the n-queens puzzle. You may 11 | * return the answer in any order. 12 | * 13 | * Each solution contains a distinct board 14 | * configuration of the n-queens' placement, 15 | * where 'Q' and '.' both indicate a queen and 16 | * an empty space, respectively. 17 | * 18 | * Example 1: 19 | * Input: n = 4 20 | * Output: [["..Q.","Q...","...Q",".Q.."]] 21 | * 22 | * Example 2: 23 | * Input: n = 1 24 | * Output: [["Q"]] 25 | * 26 | * Constraints: 27 | * 1 <= n <= 30 28 | */ 29 | class NQueen { 30 | private void printBoard(int[][] board) { 31 | for (int i = 0; i < board.length; i++) { 32 | for (int j = 0; j < board[i].length; j++) { 33 | char out = board[i][j] == 1 ? 'Q' : '.'; 34 | System.out.print(" " + out + " "); 35 | } 36 | System.out.println(); 37 | } 38 | } 39 | 40 | private boolean isMoveSafe(int[][] board, 41 | int row, int col) { 42 | 43 | for (int j = 0; j < col; j++) { 44 | if (board[row][j] == 1) { 45 | return false; 46 | } 47 | } 48 | 49 | for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { 50 | if (board[i][j] == 1) { 51 | return false; 52 | } 53 | } 54 | 55 | for (int i = row, j = col; j >= 0 && i < board.length; j--, i++) { 56 | if (board[i][j] == 1) { 57 | return false; 58 | } 59 | } 60 | 61 | return true; 62 | } 63 | 64 | /** 65 | * This method is only responsible to put queen 66 | * in a specific column. 67 | */ 68 | private boolean nQueen(int[][] board, int col) { 69 | if (col >= board.length) { 70 | return true; 71 | } 72 | 73 | for (int i = 0; i < board.length; i++) { 74 | if (isMoveSafe(board, i, col)) { 75 | board[i][col] = 1; 76 | if (nQueen(board, col + 1)) 77 | return true; 78 | board[i][col] = 0; 79 | } 80 | } 81 | 82 | return false; 83 | } 84 | 85 | private void nQueen(int size) { 86 | int[][] board = new int[size][size]; 87 | if (!nQueen(board, 0)) { 88 | System.out.println("Solution does not " + 89 | "exist"); 90 | } else { 91 | printBoard(board); 92 | } 93 | } 94 | 95 | public static void main(String[] args) { 96 | try (Scanner scanner = new Scanner(System.in)) { 97 | NQueen nQueen = new NQueen(); 98 | System.out.print("Enter size of board: "); 99 | int size = scanner.nextInt(); 100 | nQueen.nQueen(size); 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /4 Other Problems/ArrayCopy.java: -------------------------------------------------------------------------------- 1 | 2 | class ArrayCopy { 3 | 4 | public static void main(String[] args) { 5 | int[] newCopy = copy(new int[] { 1, 2, 3, 4, 5 }); 6 | } 7 | 8 | private static int[] copy(int[] array) { 9 | int[] newCopy = new int[array.length]; 10 | for (int i = 0; i < array.length; i++) { 11 | newCopy[i] = array[i]; 12 | } 13 | return newCopy; 14 | } 15 | } -------------------------------------------------------------------------------- /4 Other Problems/ArraySum.java: -------------------------------------------------------------------------------- 1 | 2 | class ArraySum { 3 | public static void main(String[] args) { 4 | System.out.println("Sum:" + sum(new int[] { 5, 6 })); 5 | System.out.println("Sum:" + sum(new int[] { 1, 2, 3, 4, 5 })); 6 | } 7 | 8 | private static int sum(int[] array) { 9 | int result = 0; 10 | for (int i = 0; i < array.length; i++) { 11 | result += array[i]; 12 | } 13 | return result; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /4 Other Problems/BinarySearch.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * implement Binary Search on sorted array 4 | * Example: 5 | * sortedArr: -8, -5, 0, 3, 7, 11, 15 6 | * Number to find: 7 7 | * Number to find: 1 8 | */ 9 | class BinarySearch { 10 | public int search(int[] sortedArr, int target) { 11 | int beg = 0, end = sortedArr.length - 1; 12 | while (beg <= end) { 13 | int mid = beg + (end - beg) / 2; 14 | if (target == sortedArr[mid]) { 15 | return mid; 16 | } else if (target < sortedArr[mid]) { 17 | end = mid - 1; 18 | } else { 19 | beg = mid + 1; 20 | } 21 | } 22 | return -1; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /4 Other Problems/BubbleSort.java: -------------------------------------------------------------------------------- 1 | 2 | class BubbleSort implements SortingAlgo { 3 | 4 | private void swap(int[] nums, int i, int j) { 5 | int temp = nums[i]; 6 | nums[i] = nums[j]; 7 | nums[j] = temp; 8 | } 9 | 10 | @Override 11 | public void sort(int[] nums) { 12 | for (int i = 0; i < nums.length - 1; i++) { 13 | for (int j = 0; j < nums.length - 1 - i; j++) { 14 | if (nums[j] > nums[j + 1]) { 15 | swap(nums, j, j + 1); 16 | } 17 | } 18 | // printArray(nums); 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | int[] nums = { 8, 6, 14, 77, 1, 13 }; 24 | 25 | SortingAlgo sortingAlgo = new BubbleSort(); 26 | sortingAlgo.sort(nums); 27 | System.out.print("Sorted Array:"); 28 | printArray(nums); 29 | } 30 | 31 | private static void printArray(int[] nums) { 32 | for (int num : nums) { 33 | System.out.print(num + " "); 34 | } 35 | System.out.println(); 36 | } 37 | } -------------------------------------------------------------------------------- /4 Other Problems/Factorial.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Factorial 4 | * n! = n X (n-1) X ..... X 1 5 | * F(0) = 1 6 | * F(1) = 1 7 | * F(2) = 2 8 | * F(3) = 6 = 3 * 2 9 | * F(n) = n * F(n-1), n >= 1 10 | */ 11 | class Factorial { 12 | public int fact(int n) { 13 | if (n == 0 || n == 1) 14 | return 1; 15 | return n * fact(n - 1); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /4 Other Problems/InsertionSort.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Implement a sorting algo for Insertion Sort 4 | */ 5 | class InsertionSort implements SortingAlgo { 6 | @Override 7 | public void sort(int[] nums) { 8 | for (int i = 1; i < nums.length; i++) { 9 | int key = nums[i]; 10 | int j = i - 1; 11 | while (j >= 0 && nums[j] > key) { 12 | nums[j + 1] = nums[j]; 13 | j--; 14 | } 15 | nums[j + 1] = key; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /4 Other Problems/ListNode.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | 3 | public int val; 4 | public ListNode next; 5 | 6 | public ListNode() { 7 | } 8 | 9 | public ListNode(int val) { 10 | this.val = val; 11 | } 12 | 13 | public ListNode(int val, ListNode next) { 14 | this.val = val; 15 | this.next = next; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /4 Other Problems/MergeSort.java: -------------------------------------------------------------------------------- 1 | 2 | class MergeSort implements SortingAlgo { 3 | 4 | private void mergeSort(int[] nums) { 5 | int n = nums.length; 6 | if (n < 2) { 7 | return; 8 | } 9 | int mid = n / 2; 10 | int[] left = new int[mid]; 11 | int[] right = new int[n - mid]; 12 | 13 | for (int i = 0; i < mid; i++) { 14 | left[i] = nums[i]; 15 | } 16 | 17 | for (int i = mid; i < n; i++) { 18 | right[i - mid] = nums[i]; 19 | } 20 | 21 | mergeSort(left); 22 | mergeSort(right); 23 | 24 | merge(nums, left, right); 25 | } 26 | 27 | private void merge(int[] result, int[] first, 28 | int[] second) { 29 | int i = 0, j = 0, k = 0; 30 | while (i < first.length && j < second.length) { 31 | if (first[i] <= second[j]) { 32 | result[k++] = first[i++]; 33 | } else { 34 | result[k++] = second[j++]; 35 | } 36 | } 37 | while (i < first.length) { 38 | result[k++] = first[i++]; 39 | } 40 | while (j < second.length) { 41 | result[k++] = second[j++]; 42 | } 43 | } 44 | 45 | @Override 46 | public void sort(int[] nums) { 47 | mergeSort(nums); 48 | } 49 | 50 | public static void main(String[] args) { 51 | int[] arr = { 8, 6, 14, 77, 1, 13 }; 52 | int n = arr.length; 53 | 54 | SortingAlgo sort = new MergeSort(); 55 | sort.sort(arr); 56 | System.out.println("Sorted array: "); 57 | printArray(arr, n); 58 | } 59 | 60 | static void printArray(int[] arr, int size) { 61 | for (int i = 0; i < size; i++) 62 | System.out.print(arr[i] + " "); 63 | System.out.println(); 64 | } 65 | } -------------------------------------------------------------------------------- /4 Other Problems/MiniMahjongWinningHand.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashMap; 3 | import java.util.Map; 4 | 5 | /** 6 | * You're creating a game with some amusing mini-games, 7 | * and you've decided to make a simple variant of 8 | * the game Mahjong. 9 | * 10 | * In this variant, players have a number of tiles, 11 | * each marked 0-9. The tiles can be grouped into 12 | * pairs or triples of the same tile. For example, 13 | * if a player has "33344466", the player's hand 14 | * has a triple of 3s, a triple of 4s, and a pair 15 | * of 6s. Similarly, "55555777" has a triple of 5s, 16 | * a pair of 5s, and a triple of 7s. 17 | * 18 | * A "complete hand" is defined as a collection 19 | * of tiles where all the tiles can be grouped 20 | * into any number of triples (zero or more) and 21 | * exactly one pair, and each tile is used in 22 | * exactly one triple or pair. 23 | * 24 | * Write a function that takes a string representation of a collection of tiles 25 | * in no particular order, and returns true or false depending on whether or not 26 | * the collection represents a complete hand. 27 | * 28 | * tiles1 = "11133555" # True. 111 33 555 29 | * tiles2 = "111333555" # False. There are three triples, 111 333 555 but no 30 | * pair. 31 | * tiles3 = "00000111" # True. 000 00 111. Your pair and a triplet can be of the 32 | * same value 33 | * # There is also no limit to how many of each tile there is. 34 | * tiles4 = "13233121" # True. Tiles are not guaranteed to be in order 35 | * tiles5 = "11223344555" # False. There cannot be more than one pair 36 | * tiles6 = "99999999" # True. You can have many of one tile 37 | * tiles7 = "999999999" # False. 38 | * tiles8 = "9" # False. 39 | * tiles9 = "99" # True. One pair. 40 | * tiles10 = "000022" # False. 41 | * tiles11 = "888889" # False. There cannot be any tiles left over. 42 | * tiles12 = "889" # False. There cannot be any tiles left over. 43 | * tiles13 = "88888844" # True. Two triples and one pair 44 | * tiles14 = "77777777777777" # True. Four triples and one pair 45 | * tiles15 = "1111111" # False. 46 | * tiles16 = "1111122222" # False. 47 | * 48 | * complete(tiles1) => True 49 | * complete(tiles2) => False 50 | * complete(tiles3) => True 51 | * complete(tiles4) => True 52 | * complete(tiles5) => False 53 | * complete(tiles6) => True 54 | * complete(tiles7) => False 55 | * complete(tiles8) => False 56 | * complete(tiles9) => True 57 | * complete(tiles10) => False 58 | * complete(tiles11) => False 59 | * complete(tiles12) => False 60 | * complete(tiles13) => True 61 | * complete(tiles14) => True 62 | * complete(tiles15) => False 63 | * complete(tiles16) => False 64 | * 65 | * Complexity Variable 66 | * N - Number of tiles in the input string 67 | */ 68 | class MiniMahjongWinningHand { 69 | public boolean isWinningHand(String hand) { 70 | Map map = new HashMap<>(); 71 | for (int i = 0; i < hand.length(); i++) { 72 | char c = hand.charAt(i); 73 | map.put(c, map.getOrDefault(c, 0) + 1); 74 | } 75 | 76 | boolean pairFound = false; 77 | for (Integer freq : map.values()) { 78 | if (freq % 3 == 2) { 79 | if (pairFound) { 80 | return false; 81 | } else { 82 | pairFound = true; 83 | } 84 | } else if (freq % 3 != 0) { 85 | return false; 86 | } 87 | } 88 | 89 | return pairFound; 90 | } 91 | 92 | public static void main(String[] args) { 93 | String tiles1 = "11133555"; 94 | String tiles2 = "111333555"; 95 | String tiles3 = "00000111"; 96 | String tiles4 = "13233121"; 97 | String tiles5 = "11223344555"; 98 | String tiles6 = "99999999"; 99 | String tiles7 = "999999999"; 100 | String tiles8 = "9"; 101 | String tiles9 = "99"; 102 | String tiles10 = "000022"; 103 | String tiles11 = "888889"; 104 | String tiles12 = "889"; 105 | String tiles13 = "88888844"; 106 | String tiles14 = "77777777777777"; 107 | String tiles15 = "1111111"; 108 | String tiles16 = "1111122222"; 109 | MiniMahjongWinningHand obj = new MiniMahjongWinningHand(); 110 | System.out.println(tiles1 + ":" + obj.isWinningHand(tiles1)); 111 | System.out.println(tiles2 + ":" + obj.isWinningHand(tiles2)); 112 | System.out.println(tiles3 + ":" + obj.isWinningHand(tiles3)); 113 | System.out.println(tiles4 + ":" + obj.isWinningHand(tiles4)); 114 | System.out.println(tiles5 + ":" + obj.isWinningHand(tiles5)); 115 | System.out.println(tiles6 + ":" + obj.isWinningHand(tiles6)); 116 | System.out.println(tiles7 + ":" + obj.isWinningHand(tiles7)); 117 | System.out.println(tiles8 + ":" + obj.isWinningHand(tiles8)); 118 | System.out.println(tiles9 + ":" + obj.isWinningHand(tiles9)); 119 | System.out.println(tiles10 + ":" + obj.isWinningHand(tiles10)); 120 | System.out.println(tiles11 + ":" + obj.isWinningHand(tiles11)); 121 | System.out.println(tiles12 + ":" + obj.isWinningHand(tiles12)); 122 | System.out.println(tiles13 + ":" + obj.isWinningHand(tiles13)); 123 | System.out.println(tiles14 + ":" + obj.isWinningHand(tiles14)); 124 | System.out.println(tiles15 + ":" + obj.isWinningHand(tiles15)); 125 | System.out.println(tiles16 + ":" + obj.isWinningHand(tiles16)); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /4 Other Problems/MiniMahjongWinningHand2.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashMap; 3 | import java.util.Map; 4 | 5 | /** 6 | * You've decided to make an advanced version of a 7 | * variant of the game Mahjong, incorporating runs. 8 | * 9 | * Players have a number of hand, each marked 0-9. 10 | * The hand can be grouped into pairs or triples of 11 | * the same tile or runs. 12 | * 13 | * A run is a series of three consecutive hand, 14 | * like 123, 678, or 456. 0 counts as the lowest tile, 15 | * so 012 is a valid run, but 890 is not. 16 | * 17 | * A complete hand consists of exactly one pair, and 18 | * any number (including zero) of triples and/or 19 | * three-tile runs. Each tile is used in exactly one 20 | * triple, pair, or run. 21 | * 22 | * Write a function that returns true or false 23 | * depending on whether or not the collection 24 | * represents a complete hand under these rules. 25 | * 26 | * hand1 = "11123" # True. 11 123 27 | * hand2 = "12131" # True. Also 11 123. hand are not necessarily sorted. 28 | * hand3 = "11123455" # True. 111 234 55 29 | * hand4 = "11122334" # True. 11 123 234 30 | * hand5 = "11234" # True. 11 234 31 | * hand6 = "123456" # False. Needs a pair 32 | * hand7 = "11133355577" # True. 111 333 555 77 33 | * hand8 = "11223344556677" # True. 11 234 234 567 567 among others 34 | * hand9 = "12233444556677" # True. 123 234 44 567 567 35 | * hand10 = "11234567899" # False. 36 | * hand11 = "00123457" # False. 37 | * hand12 = "0012345" # False. A run is only three hand 38 | * hand13 = "11890" # False. 890 is not a valid run 39 | * hand14 = "99" # True. 40 | * hand15 = "111223344" # False. 41 | * 42 | * All Test Cases 43 | * advanced(hand1) => True 44 | * advanced(hand2) => True 45 | * advanced(hand3) => True 46 | * advanced(hand4) => True 47 | * advanced(hand5) => True 48 | * advanced(hand6) => False 49 | * advanced(hand7) => True 50 | * advanced(hand8) => True 51 | * advanced(hand9) => True 52 | * advanced(hand10) => False 53 | * advanced(hand11) => False 54 | * advanced(hand12) => False 55 | * advanced(hand13) => False 56 | * advanced(hand14) => True 57 | * advanced(hand15) => False 58 | * 59 | * Complexity Variable 60 | * N - Number of hand in the input string 61 | */ 62 | class MiniMahjongWinningHand2 { 63 | 64 | public boolean isWinningHand(String hand) { 65 | Map map = new HashMap<>(); 66 | for (int i = 0; i < hand.length(); i++) { 67 | int c = hand.charAt(i) - '0'; 68 | map.put(c, map.getOrDefault(c, 0) + 1); 69 | } 70 | 71 | for (Map.Entry entry : map.entrySet()) { 72 | if (entry.getValue() < 2) 73 | continue; 74 | Map newMap = new HashMap<>(map); 75 | newMap.put(entry.getKey(), 76 | entry.getValue() - 2); 77 | if (isWinningHand(newMap)) { 78 | return true; 79 | } 80 | } 81 | return false; 82 | } 83 | 84 | private boolean isWinningHand(Map newMap) { 85 | // remove triplets 86 | for (int i = 0; i <= 9; i++) { 87 | int val = newMap.getOrDefault(i, 0); 88 | newMap.put(i, val % 3); 89 | } 90 | 91 | // remove all possible runs 92 | for (int i = 0; i < 7; i++) { 93 | int val1 = newMap.getOrDefault(i, 0); 94 | int val2 = newMap.getOrDefault(i + 1, 0); 95 | int val3 = newMap.getOrDefault(i + 2, 0); 96 | int run = Math.min(Math.min(val1, val2), 97 | val3); 98 | if (run > 0) { 99 | newMap.put(i, val1 - run); 100 | newMap.put(i + 1, val2 - run); 101 | newMap.put(i + 2, val3 - run); 102 | } 103 | } 104 | 105 | // any value remaining 106 | for (Integer value : newMap.values()) { 107 | if (value > 0) { 108 | return false; 109 | } 110 | } 111 | 112 | return true; 113 | } 114 | 115 | public static void main(String[] args) { 116 | String hand1 = "11123"; 117 | String hand2 = "12131"; 118 | String hand3 = "11123455"; 119 | String hand4 = "11122334"; 120 | String hand5 = "11234"; 121 | String hand6 = "123456"; 122 | String hand7 = "11133355577"; 123 | String hand8 = "11223344556677"; 124 | String hand9 = "12233444556677"; 125 | String hand10 = "11234567899"; 126 | String hand11 = "00123457"; 127 | String hand12 = "0012345"; 128 | String hand13 = "11890"; 129 | String hand14 = "99"; 130 | String hand15 = "111223344"; 131 | MiniMahjongWinningHand2 obj = new MiniMahjongWinningHand2(); 132 | System.out.println(hand1 + ":" + obj.isWinningHand(hand1)); 133 | System.out.println(hand2 + ":" + obj.isWinningHand(hand2)); 134 | System.out.println(hand3 + ":" + obj.isWinningHand(hand3)); 135 | System.out.println(hand4 + ":" + obj.isWinningHand(hand4)); 136 | System.out.println(hand5 + ":" + obj.isWinningHand(hand5)); 137 | System.out.println(hand6 + ":" + obj.isWinningHand(hand6)); 138 | System.out.println(hand7 + ":" + obj.isWinningHand(hand7)); 139 | System.out.println(hand8 + ":" + obj.isWinningHand(hand8)); 140 | System.out.println(hand9 + ":" + obj.isWinningHand(hand9)); 141 | System.out.println(hand10 + ":" + obj.isWinningHand(hand10)); 142 | System.out.println(hand11 + ":" + obj.isWinningHand(hand11)); 143 | System.out.println(hand12 + ":" + obj.isWinningHand(hand12)); 144 | System.out.println(hand13 + ":" + obj.isWinningHand(hand13)); 145 | System.out.println(hand14 + ":" + obj.isWinningHand(hand14)); 146 | System.out.println(hand15 + ":" + obj.isWinningHand(hand15)); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /4 Other Problems/QuickSort.java: -------------------------------------------------------------------------------- 1 | 2 | class QuickSort implements SortingAlgo { 3 | 4 | private void swap(int[] arr, int i, int j) { 5 | int temp = arr[i]; 6 | arr[i] = arr[j]; 7 | arr[j] = temp; 8 | } 9 | 10 | private int partition(int[] nums, int low, 11 | int high) { 12 | int pivot = nums[high]; 13 | int i = low; 14 | 15 | for (int j = low; j < high; j++) { 16 | if (nums[j] < pivot) { 17 | swap(nums, i++, j); 18 | } 19 | } 20 | swap(nums, i, high); 21 | return i; 22 | } 23 | 24 | private void quickSort(int[] nums, int low, 25 | int high) { 26 | if (low < high) { 27 | int partitionIndex = partition(nums, low, 28 | high); 29 | quickSort(nums, 0, partitionIndex - 1); 30 | quickSort(nums, partitionIndex + 1, high); 31 | } 32 | } 33 | 34 | @Override 35 | public void sort(int[] nums) { 36 | quickSort(nums, 0, nums.length - 1); 37 | } 38 | 39 | public static void main(String[] args) { 40 | int[] arr = { 8, 6, 14, 77, 1, 13 }; 41 | int n = arr.length; 42 | 43 | SortingAlgo sort = new QuickSort(); 44 | sort.sort(arr); 45 | System.out.println("Sorted array: "); 46 | printArray(arr, n); 47 | } 48 | 49 | static void printArray(int[] arr, int size) { 50 | for (int i = 0; i < size; i++) 51 | System.out.print(arr[i] + " "); 52 | System.out.println(); 53 | } 54 | } -------------------------------------------------------------------------------- /4 Other Problems/RodCutting.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashMap; 3 | import java.util.Map; 4 | 5 | /** 6 | * Given a rod of length n inches and an array 7 | * of prices that includes prices of all pieces of 8 | * size smaller than n. Determine the maximum 9 | * value obtainable by cutting up the rod and 10 | * selling the pieces. For example, if the length 11 | * of the rod is 8 and the values of different pieces 12 | * are given as the following, then the maximum 13 | * obtainable value is 22 (by cutting in two 14 | * pieces of lengths 2 and 6) 15 | * 16 | * Example: 17 | * length | 1 2 3 4 5 6 7 8 18 | * -------------------------------------------- 19 | * price | 1 5 8 9 10 17 17 20 20 | * And if the prices are as following, then the 21 | * maximum obtainable value is 24 (by cutting in 22 | * eight pieces of length 1) 23 | * 24 | */ 25 | class RodCutting { 26 | static int count = 0; 27 | 28 | public static void main(String[] args) { 29 | RodCutting rodCutting = new RodCutting(); 30 | int price[] = new int[] { 1, 5, 8, 9, 10, 17, 17, 31 | 20, 24 }; 32 | int n = price.length; 33 | Map maxProfit = new HashMap<>(); 34 | System.out.println( 35 | "Maximum obtained value is " 36 | + rodCutting.cutRod(price, n, maxProfit)); 37 | System.out.println("count is:" + count); 38 | } 39 | 40 | public int cutRod(int prices[], int length, 41 | Map maxProfit) { 42 | if (length <= 0) 43 | return 0; 44 | if (maxProfit.containsKey(length)) { 45 | return maxProfit.get(length); 46 | } 47 | count++; 48 | int maxVal = Integer.MIN_VALUE; 49 | 50 | for (int i = 0; i < length; i++) { 51 | maxVal = Math.max(maxVal, 52 | prices[i] + cutRod(prices, 53 | length - i - 1, maxProfit)); 54 | } 55 | 56 | maxProfit.put(length, maxVal); 57 | return maxVal; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /4 Other Problems/SelectionSort.java: -------------------------------------------------------------------------------- 1 | 2 | class SelectionSort implements SortingAlgo { 3 | 4 | private void swap(int[] nums, int i, int j) { 5 | int temp = nums[i]; 6 | nums[i] = nums[j]; 7 | nums[j] = temp; 8 | } 9 | 10 | @Override 11 | public void sort(int[] nums) { 12 | int n = nums.length; 13 | for (int i = 0; i < n - 1; i++) { 14 | int minIndex = i; 15 | for (int j = i + 1; j < n; j++) { 16 | if (nums[j] < nums[minIndex]) { 17 | minIndex = j; 18 | } 19 | } 20 | swap(nums, minIndex, i); 21 | } 22 | } 23 | 24 | public static void main(String[] args) { 25 | int[] nums = { 8, 6, 14, 77, 1, 13 }; 26 | 27 | SortingAlgo sortingAlgo = new SelectionSort(); 28 | sortingAlgo.sort(nums); 29 | System.out.print("Sorted Array:"); 30 | printArray(nums); 31 | } 32 | 33 | private static void printArray(int[] nums) { 34 | for (int num : nums) { 35 | System.out.print(num + " "); 36 | } 37 | System.out.println(); 38 | } 39 | } -------------------------------------------------------------------------------- /4 Other Problems/Solitaire.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * While your players are waiting for a game, 4 | * you've developed a solitaire game for the 5 | * players to pass the time with. 6 | * The player is given an NxM board of tiles from 7 | * 0 to 9 like this: 8 | * 4 4 4 4 9 | * 5 5 5 4 10 | * 2 5 7 5 11 | * The player selects one of these tiles, and that 12 | * tile will disappear, along with any tiles with 13 | * the same number that are connected with that tile 14 | * (up, down, left, or right), and any tiles with the 15 | * same number connected with those, and so on. For 16 | * example, if the 4 in the upper left corner is 17 | * selected, these five tiles disappear 18 | * >4< >4< >4< >4< 19 | * 5 5 5 >4< 20 | * 2 5 7 5 21 | * If the 5 just below it is selected, these four 22 | * tiles disappear. Note that tiles are not 23 | * connected diagonally. 24 | * 4 4 4 4 25 | * >5< >5< >5< 4 26 | * 2 >5< 7 5 27 | * Write a function that, given a grid of tiles 28 | * and a selected row and column of a tile, 29 | * returns how many tiles will disappear. 30 | * grid1 = [[4, 4, 4, 4], 31 | * [5, 5, 5, 4], 32 | * [2, 5, 7, 5]] 33 | * disappear(grid1, 0, 0) => 5 34 | * disappear(grid1, 1, 1) => 4 35 | * disappear(grid1, 1, 0) => 4 36 | * This is the grid from above. 37 | * 38 | * Additional Inputs 39 | * grid2 = [[0, 3, 3, 3, 3, 3, 3], 40 | * [0, 1, 1, 1, 1, 1, 3], 41 | * [0, 2, 2, 0, 2, 1, 4], 42 | * [0, 1, 2, 2, 2, 1, 3], 43 | * [0, 1, 1, 1, 1, 1, 3], 44 | * [0, 0, 0, 0, 0, 0, 0]] 45 | * 46 | * grid3 = [[0]] 47 | * 48 | * grid4 = [[1, 1, 1], 49 | * [1, 1, 1], 50 | * [1, 1, 1]] 51 | * 52 | * All Test Cases 53 | * disappear(grid1, 0, 0) => 5 54 | * disappear(grid1, 1, 1) => 4 55 | * disappear(grid1, 1, 0) => 4 56 | * disappear(grid2, 0, 0) => 12 57 | * disappear(grid2, 3, 0) => 12 58 | * disappear(grid2, 1, 1) => 13 59 | * disappear(grid2, 2, 2) => 6 60 | * disappear(grid2, 0, 3) => 7 61 | * disappear(grid3, 0, 0) => 1 62 | * disappear(grid4, 0, 0) => 9 63 | * 64 | * N - Width of the grid 65 | * M - Height of the grid 66 | * 67 | * Clarifications 68 | * - All values are between 0 and 9 69 | * - The grid will not be empty 70 | * - The input board is immutable. If the 71 | * candidate suggests modifying the board you 72 | * should suggest they make a deep copy of the board 73 | * instead. This does not constitute handholding. 74 | * - The input row and column will always be on 75 | * the board. 76 | */ 77 | class Solitaire { 78 | public int disappear(int[][] grid, int x, 79 | int y) { 80 | if (grid.length <= 0) 81 | return 0; 82 | int[][] newGrid = new int[grid.length][grid[0].length]; 83 | for (int i = 0; i < grid.length; i++) { 84 | for (int j = 0; j < grid[i].length; j++) { 85 | newGrid[i][j] = grid[i][j]; 86 | } 87 | } 88 | return disappear(newGrid, x, y, newGrid[x][y]); 89 | } 90 | 91 | public int disappear(int[][] grid, int x, 92 | int y, int num) { 93 | if (x >= grid.length || y >= grid[0].length || 94 | x < 0 || y < 0 || grid[x][y] != num || 95 | grid[x][y] == -1) 96 | return 0; 97 | 98 | grid[x][y] = -1; 99 | return 1 + disappear(grid, x, y + 1, num) 100 | + disappear(grid, x + 1, y, num) 101 | + disappear(grid, x - 1, y, num) 102 | + disappear(grid, x, y - 1, num); 103 | } 104 | 105 | public static void main(String[] args) { 106 | int[][] grid1 = { { 4, 4, 4, 4 }, 107 | { 5, 5, 5, 4 }, 108 | { 2, 5, 7, 5 } }; 109 | int[][] grid2 = { { 0, 3, 3, 3, 3, 3, 3 }, 110 | { 0, 1, 1, 1, 1, 1, 3 }, 111 | { 0, 2, 2, 0, 2, 1, 4 }, 112 | { 0, 1, 2, 2, 2, 1, 3 }, 113 | { 0, 1, 1, 1, 1, 1, 3 }, 114 | { 0, 0, 0, 0, 0, 0, 0 } }; 115 | int[][] grid3 = { { 0 } }; 116 | int[][] grid4 = { { 1, 1, 1 }, 117 | { 1, 1, 1 }, 118 | { 1, 1, 1 } }; 119 | 120 | Solitaire solitaire = new Solitaire(); 121 | System.out.println(solitaire.disappear(grid1, 0, 0)); 122 | System.out.println(solitaire.disappear(grid1, 1, 0)); 123 | System.out.println(solitaire.disappear(grid1, 2, 0)); 124 | System.out.println(solitaire.disappear(grid1, 2, 2)); 125 | 126 | System.out.println(solitaire.disappear(grid2, 0, 0)); 127 | System.out.println(solitaire.disappear(grid2, 0, 1)); 128 | System.out.println(solitaire.disappear(grid2, 1, 1)); 129 | System.out.println(solitaire.disappear(grid2, 2, 1)); 130 | System.out.println(solitaire.disappear(grid2, 0, 0)); 131 | 132 | System.out.println(solitaire.disappear(grid3, 0, 0)); 133 | 134 | System.out.println(solitaire.disappear(grid4, 0, 0)); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /4 Other Problems/SortingAlgo.java: -------------------------------------------------------------------------------- 1 | 2 | public interface SortingAlgo { 3 | void sort(int[] nums); 4 | } 5 | -------------------------------------------------------------------------------- /4 Other Problems/Sum.java: -------------------------------------------------------------------------------- 1 | 2 | class Sum { 3 | public static void main(String[] args) { 4 | System.out.println("Sum:" + sum(5, 6)); 5 | System.out.println("Sum:" + sum(8, 10)); 6 | } 7 | 8 | private static int sum(int a, int b) { 9 | return a + b; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /4 Other Problems/TreeNode.java: -------------------------------------------------------------------------------- 1 | public class TreeNode { 2 | 3 | public int val; 4 | public TreeNode left; 5 | public TreeNode right; 6 | 7 | public TreeNode() { 8 | } 9 | 10 | public TreeNode(int val) { 11 | this.val = val; 12 | } 13 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DSA using Java 2 | 3 | Course Link: https://www.kgcoding.in/courses/DSA-using-Java 4 | 5 | ![DSA Thumbnail](https://github.com/KG-Coding-with-Prashant-Sir/DSA_using_Java/assets/102736197/1cda942b-d878-40bd-9b09-59f7d673c917) 6 | --------------------------------------------------------------------------------