From fc9d892f1be05e0b508276ebfa9529de36b4dbdb Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 21 May 2024 08:14:13 -0700 Subject: [PATCH 001/182] Update Minimum Knight Moves.java --- Medium/Minimum Knight Moves.java | 52 ++++++++++++++++---------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/Medium/Minimum Knight Moves.java b/Medium/Minimum Knight Moves.java index e1352ac4..35759df8 100644 --- a/Medium/Minimum Knight Moves.java +++ b/Medium/Minimum Knight Moves.java @@ -1,30 +1,30 @@ class Solution { - private final int[][] DIRS = {{1, 2}, {2, 1}, {1, -2}, {-2, 1}, {2, -1}, {-2, -1}, {-1, -2}, {-1, 2}}; - - public int minKnightMoves(int x, int y) { - int numOfSteps = 0; - boolean[][] visited = new boolean[607][607]; - Queue queue = new LinkedList<>(); - queue.add(new int[]{0, 0}); - while (!queue.isEmpty()) { - int size = queue.size(); - while (size-- > 0) { - int[] removed = queue.remove(); - if (removed[0] == x && removed[1] == y) { - return numOfSteps; + + private static final int[][] MOVES = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}; + + public int minKnightMoves(int x, int y) { + boolean[][] visited = new boolean[607][607]; + Queue queue = new LinkedList<>(); + queue.add(new int[]{0, 0}); + int steps = 0; + while (!queue.isEmpty()) { + int size = queue.size(); + while (size-- > 0) { + int[] removed = queue.remove(); + if (removed[0] == x && removed[1] == y) { + return steps; + } + for (int[] move : MOVES) { + int newX = removed[0] + move[0]; + int newY = removed[1] + move[1]; + if (!visited[newX + 302][newY + 302]) { + visited[newX + 302][newY + 302] = true; + queue.add(new int[]{newX, newY}); + } + } + } + steps++; } - for (int[] dir : DIRS) { - int newX = removed[0] + dir[0]; - int newY = removed[1] + dir[1]; - if (visited[newX + 302][newY + 302]) { - continue; - } - visited[newX + 302][newY + 302] = true; - queue.add(new int[]{newX, newY}); - } - } - numOfSteps++; + return steps; } - return numOfSteps; - } } From 9d417554f8b3db6c721f4f9ee5e4c2e9f3d4055a Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 23 May 2024 07:41:33 -0700 Subject: [PATCH 002/182] Create The Number of Beautiful Subsets.java --- Medium/The Number of Beautiful Subsets.java | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Medium/The Number of Beautiful Subsets.java diff --git a/Medium/The Number of Beautiful Subsets.java b/Medium/The Number of Beautiful Subsets.java new file mode 100644 index 00000000..7057a18d --- /dev/null +++ b/Medium/The Number of Beautiful Subsets.java @@ -0,0 +1,20 @@ +class Solution { + public int beautifulSubsets(int[] nums, int k) { + Map freqMap = new HashMap<>(); + Arrays.sort(nums); + return countBeautifulSubsets(nums, k, freqMap, 0) - 1; + } + + private int countBeautifulSubsets(int[] nums, int k, Map freqMap, int idx) { + if (idx == nums.length) { + return 1; + } + int count = countBeautifulSubsets(nums, k, freqMap, idx + 1); + if (freqMap.getOrDefault(nums[idx] - k, 0) == 0) { + freqMap.put(nums[idx], freqMap.getOrDefault(nums[idx], 0) + 1); + count += countBeautifulSubsets(nums, k, freqMap, idx + 1); + freqMap.put(nums[idx], freqMap.getOrDefault(nums[idx], 0) - 1); + } + return count; + } +} From 447d746712a16287560af23e523a2641ac847f5e Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 29 May 2024 07:17:12 -0700 Subject: [PATCH 003/182] Create Number of Steps to Reduce a Number in Binary Representation to One.java --- ...umber in Binary Representation to One.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Medium/Number of Steps to Reduce a Number in Binary Representation to One.java diff --git a/Medium/Number of Steps to Reduce a Number in Binary Representation to One.java b/Medium/Number of Steps to Reduce a Number in Binary Representation to One.java new file mode 100644 index 00000000..00a8296a --- /dev/null +++ b/Medium/Number of Steps to Reduce a Number in Binary Representation to One.java @@ -0,0 +1,27 @@ +class Solution { + public int numSteps(String s) { + int operations = 0; + StringBuilder sb = new StringBuilder(s); + while (sb.length() > 1) { + int n = sb.length(); + if (sb.charAt(n - 1) == '0') { + // divide by 2 + sb.deleteCharAt(n - 1); + } else { + // add 1 + int idx = n - 1; + while (idx >= 0 && sb.charAt(idx) != '0') { + sb.setCharAt(idx, '0'); + idx--; + } + if (idx < 0) { + sb.insert(0, '1'); + } else { + sb.setCharAt(idx, '1'); + } + } + operations++; + } + return operations; + } +} From f967067bddf85a35522c0246e0a85386d0514cb8 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 29 May 2024 07:20:42 -0700 Subject: [PATCH 004/182] Create Find the Number of Good Pairs I.java --- Easy/Find the Number of Good Pairs I.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Easy/Find the Number of Good Pairs I.java diff --git a/Easy/Find the Number of Good Pairs I.java b/Easy/Find the Number of Good Pairs I.java new file mode 100644 index 00000000..143d6abd --- /dev/null +++ b/Easy/Find the Number of Good Pairs I.java @@ -0,0 +1,13 @@ +class Solution { + public int numberOfPairs(int[] nums1, int[] nums2, int k) { + int count = 0; + for (int i = 0; i < nums1.length; i++) { + for (int j = 0; j < nums2.length; j++) { + if (nums1[i] % (nums2[j] * k) == 0) { + count++; + } + } + } + return count; + } +} From 010f42b1f2319b3f4f430b0377df571bf8998248 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 29 May 2024 07:22:58 -0700 Subject: [PATCH 005/182] Create Find the XOR of Numbers Which Appear Twice.java --- Easy/Find the XOR of Numbers Which Appear Twice.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Easy/Find the XOR of Numbers Which Appear Twice.java diff --git a/Easy/Find the XOR of Numbers Which Appear Twice.java b/Easy/Find the XOR of Numbers Which Appear Twice.java new file mode 100644 index 00000000..baa845bc --- /dev/null +++ b/Easy/Find the XOR of Numbers Which Appear Twice.java @@ -0,0 +1,12 @@ +class Solution { + public int duplicateNumbersXOR(int[] nums) { + Set set = new HashSet<>(); + int xor = 0; + for (int num : nums) { + if (!set.add(num)) { + xor = xor ^ num; + } + } + return xor; + } +} From b4ddaff710706d5bd1804fd0a5de1ad1f7d36008 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 1 Jun 2024 07:30:52 -0700 Subject: [PATCH 006/182] Create Longest Common Subsequence Between Sorted Arrays.java --- ... Common Subsequence Between Sorted Arrays.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Medium/Longest Common Subsequence Between Sorted Arrays.java diff --git a/Medium/Longest Common Subsequence Between Sorted Arrays.java b/Medium/Longest Common Subsequence Between Sorted Arrays.java new file mode 100644 index 00000000..d050d3fd --- /dev/null +++ b/Medium/Longest Common Subsequence Between Sorted Arrays.java @@ -0,0 +1,15 @@ +class Solution { + public List longestCommonSubsequence(int[][] arrays) { + List result = new ArrayList<>(); + Map map = new HashMap<>(); + for (int[] arr : arrays) { + for (int num : arr) { + map.put(num, map.getOrDefault(num, 0) + 1); + if (map.get(num) == arrays.length) { + result.add(num); + } + } + } + return result; + } +} From 210a81b9ad3d8a5ebb84ce6b546845641389dfe9 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 2 Jun 2024 07:31:09 -0700 Subject: [PATCH 007/182] Create Minimum Number of Chairs in a Waiting Room.java --- Easy/Minimum Number of Chairs in a Waiting Room.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Easy/Minimum Number of Chairs in a Waiting Room.java diff --git a/Easy/Minimum Number of Chairs in a Waiting Room.java b/Easy/Minimum Number of Chairs in a Waiting Room.java new file mode 100644 index 00000000..d7db8060 --- /dev/null +++ b/Easy/Minimum Number of Chairs in a Waiting Room.java @@ -0,0 +1,11 @@ +class Solution { + public int minimumChairs(String s) { + int requiredChairCount = 0; + int currChairCount = 0; + for (char c : s.toCharArray()) { + currChairCount += c == 'E' ? 1 : -1; + requiredChairCount = Math.max(requiredChairCount, currChairCount); + } + return requiredChairCount; + } +} From 4b1a03b1fdf1cb4b387ee4ff9b60d649971e3ab2 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 6 Jun 2024 07:16:35 -0700 Subject: [PATCH 008/182] Update Hand of Straights.java --- Medium/Hand of Straights.java | 53 ++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/Medium/Hand of Straights.java b/Medium/Hand of Straights.java index ceff444a..5f407cf0 100644 --- a/Medium/Hand of Straights.java +++ b/Medium/Hand of Straights.java @@ -1,29 +1,32 @@ class Solution { - public boolean isNStraightHand(int[] hand, int W) { - if (hand.length % W != 0) { - return false; - } - Map counterMap = new HashMap<>(); - Set set = new TreeSet<>(); - for (int num : hand) { - counterMap.put(num, counterMap.getOrDefault(num, 0) + 1); - set.add(num); - } - Iterator iter = set.iterator(); - Integer curr = iter.next(); - while (counterMap.get(curr) > 0) { - int temp = curr; - for (int i = 0; i < W; i++) { - if (counterMap.getOrDefault(temp, 0) == 0) { - return false; + public boolean isNStraightHand(int[] hand, int groupSize) { + if (hand.length % groupSize != 0) { + return false; + } + Map map = new HashMap<>(); + for (int num : hand) { + map.put(num, map.getOrDefault(num, 0) + 1); + } + PriorityQueue pq = new PriorityQueue<>(map.keySet()); + while (!pq.isEmpty()) { + List temp = new ArrayList<>(); + int prev = -1; + for (int i = 0; i < groupSize; i++) { + if (pq.isEmpty()) { + return false; + } + int removed = pq.remove(); + map.put(removed, map.get(removed) - 1); + if (map.get(removed) > 0) { + temp.add(removed); + } + if (prev != -1 && removed != prev + 1) { + return false; + } + prev = removed; + } + pq.addAll(temp); } - counterMap.put(temp, counterMap.get(temp) - 1); - temp++; - } - while (iter.hasNext() && counterMap.get(curr) == 0) { - curr = iter.next(); - } + return true; } - return true; - } } From b8a29e6a085598af7c6d2190d18ca55a6cf29b74 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 9 Jun 2024 09:45:41 -0700 Subject: [PATCH 009/182] Create Substrings That Begin and End With the Same Letter.java --- ...ings That Begin and End With the Same Letter.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Medium/Substrings That Begin and End With the Same Letter.java diff --git a/Medium/Substrings That Begin and End With the Same Letter.java b/Medium/Substrings That Begin and End With the Same Letter.java new file mode 100644 index 00000000..62c93389 --- /dev/null +++ b/Medium/Substrings That Begin and End With the Same Letter.java @@ -0,0 +1,12 @@ +class Solution { + public long numberOfSubstrings(String s) { + int n = s.length(); + long result = 0; + long[] prefixCount = new long[26]; + for (int i = 0; i < n; i++) { + prefixCount[s.charAt(i) - 'a']++; + result += prefixCount[s.charAt(i) - 'a']; + } + return result; + } +} From 91e35a8936aa0ff52ad594953550c2d52bf51edd Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 9 Jun 2024 09:50:21 -0700 Subject: [PATCH 010/182] Create Clear Digits.java --- Easy/Clear Digits.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Easy/Clear Digits.java diff --git a/Easy/Clear Digits.java b/Easy/Clear Digits.java new file mode 100644 index 00000000..1d308863 --- /dev/null +++ b/Easy/Clear Digits.java @@ -0,0 +1,15 @@ +class Solution { + public String clearDigits(String s) { + StringBuilder sb = new StringBuilder(); + for (char c : s.toCharArray()) { + if (Character.isDigit(c)) { + if (!sb.isEmpty()) { + sb.deleteCharAt(sb.length() - 1); + } + } else { + sb.append(c); + } + } + return sb.toString(); + } +} From 55d0ecf0bbc7bdd6ce5f35d61f761718679a9f0f Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 9 Jun 2024 09:54:37 -0700 Subject: [PATCH 011/182] Create Find the Child Who Has the Ball After K Seconds.java --- Easy/Find the Child Who Has the Ball After K Seconds.java | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Easy/Find the Child Who Has the Ball After K Seconds.java diff --git a/Easy/Find the Child Who Has the Ball After K Seconds.java b/Easy/Find the Child Who Has the Ball After K Seconds.java new file mode 100644 index 00000000..6a4c8193 --- /dev/null +++ b/Easy/Find the Child Who Has the Ball After K Seconds.java @@ -0,0 +1,7 @@ +class Solution { + public int numberOfChild(int n, int k) { + int factor = k / (n - 1); + int remainder = k % (n - 1); + return factor % 2 == 0 ? remainder : n - 1 - remainder; + } +} From 1cebeb3b089d01a796ed508a225ebdc7622d6a6f Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 12 Jun 2024 06:58:16 -0700 Subject: [PATCH 012/182] Create Find the N-th Value After K Seconds.java --- Medium/Find the N-th Value After K Seconds.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Medium/Find the N-th Value After K Seconds.java diff --git a/Medium/Find the N-th Value After K Seconds.java b/Medium/Find the N-th Value After K Seconds.java new file mode 100644 index 00000000..e457d0eb --- /dev/null +++ b/Medium/Find the N-th Value After K Seconds.java @@ -0,0 +1,15 @@ +class Solution { + + private final int MOD = 1000_000_007; + + public int valueAfterKSeconds(int n, int k) { + int[] arr = new int[n]; + Arrays.fill(arr, 1); + while (k-- > 0) { + for (int i = 1; i < n; i++) { + arr[i] = (arr[i] + arr[i - 1]) % MOD; + } + } + return arr[n - 1]; + } +} From 27aee486fa9a7ff0ca0cd9ff340e2c01e4bd1837 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 12 Jun 2024 07:05:31 -0700 Subject: [PATCH 013/182] Create Find The First Player to win K Games in a Row.java --- ... First Player to win K Games in a Row.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Medium/Find The First Player to win K Games in a Row.java diff --git a/Medium/Find The First Player to win K Games in a Row.java b/Medium/Find The First Player to win K Games in a Row.java new file mode 100644 index 00000000..fe26c684 --- /dev/null +++ b/Medium/Find The First Player to win K Games in a Row.java @@ -0,0 +1,24 @@ +class Solution { + public int findWinningPlayer(int[] skills, int k) { + Map indexMap = new HashMap<>(); + for (int i = 0; i < skills.length; i++) { + indexMap.put(skills[i], i); + } + Map winCountMap = new HashMap<>(); + Deque deque = new ArrayDeque<>(); + for (int num : skills) { + deque.addFirst(num); + } + while (deque.size() > 1) { + int first = deque.pollLast(); + int second = deque.pollLast(); + int winner = Math.max(first, second); + winCountMap.put(winner, winCountMap.getOrDefault(winner, 0) + 1); + deque.addLast(winner); + if (winCountMap.get(winner) == k) { + return indexMap.get(winner); + } + } + return indexMap.get(deque.poll()); + } +} From fd3899c2bb07e8518e8d2113f0fbe4439cc9efdd Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 14 Jun 2024 08:42:34 -0700 Subject: [PATCH 014/182] Create Minimum Increment to Make Array Unique.java --- Medium/Minimum Increment to Make Array Unique.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Medium/Minimum Increment to Make Array Unique.java diff --git a/Medium/Minimum Increment to Make Array Unique.java b/Medium/Minimum Increment to Make Array Unique.java new file mode 100644 index 00000000..7be5a583 --- /dev/null +++ b/Medium/Minimum Increment to Make Array Unique.java @@ -0,0 +1,13 @@ +class Solution { + public int minIncrementForUnique(int[] nums) { + Arrays.sort(nums); + int increments = 0; + for (int i = 1; i < nums.length; i++) { + if (nums[i] <= nums[i - 1]) { + increments += nums[i - 1] + 1 - nums[i]; + nums[i] = nums[i - 1] + 1; + } + } + return increments; + } +} From a47c0009db592d3f446566f53352857df356918f Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 15 Jun 2024 17:26:31 -0700 Subject: [PATCH 015/182] Create Patching Array.java --- Hard/Patching Array.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Hard/Patching Array.java diff --git a/Hard/Patching Array.java b/Hard/Patching Array.java new file mode 100644 index 00000000..6bf2a8ed --- /dev/null +++ b/Hard/Patching Array.java @@ -0,0 +1,16 @@ +class Solution { + public int minPatches(int[] nums, int n) { + int patches = 0; + long miss = 1; + int idx = 0; + while (miss <= n) { + if (idx < nums.length && nums[idx] <= miss) { + miss += nums[idx++]; + } else { + miss += miss; + patches++; + } + } + return patches; + } +} From 31a4de9251647d7d234fb336337751dd7152282b Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 16 Jun 2024 07:30:21 -0700 Subject: [PATCH 016/182] Create Count Pairs That Form a Complete Day I.java --- Easy/Count Pairs That Form a Complete Day I.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Easy/Count Pairs That Form a Complete Day I.java diff --git a/Easy/Count Pairs That Form a Complete Day I.java b/Easy/Count Pairs That Form a Complete Day I.java new file mode 100644 index 00000000..785a5937 --- /dev/null +++ b/Easy/Count Pairs That Form a Complete Day I.java @@ -0,0 +1,11 @@ +class Solution { + public int countCompleteDayPairs(int[] hours) { + int count = 0; + Map map = new HashMap<>(); + for (int hour : hours) { + count += map.getOrDefault((24 - hour % 24) % 24, 0); + map.put(hour % 24, map.getOrDefault(hour % 24, 0) + 1); + } + return count; + } +} From 33be1b9c03a87638dd9b6e377216ff771e5f915c Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 17 Jun 2024 06:33:01 -0700 Subject: [PATCH 017/182] Update and rename Sum of Square Numbers.java to Sum of Square Numbers.java --- Easy/Sum of Square Numbers.java | 17 ----------------- Medium/Sum of Square Numbers.java | 18 ++++++++++++++++++ 2 files changed, 18 insertions(+), 17 deletions(-) delete mode 100644 Easy/Sum of Square Numbers.java create mode 100644 Medium/Sum of Square Numbers.java diff --git a/Easy/Sum of Square Numbers.java b/Easy/Sum of Square Numbers.java deleted file mode 100644 index 61e26dde..00000000 --- a/Easy/Sum of Square Numbers.java +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { - public boolean judgeSquareSum(int c) { - int left = 0; - int right = (int) Math.sqrt(c); - while (left <= right) { - int currSquareSum = left * left + right * right; - if (currSquareSum < c) { - left++; - } else if (currSquareSum > c) { - right--; - } else { - return true; - } - } - return false; - } -} diff --git a/Medium/Sum of Square Numbers.java b/Medium/Sum of Square Numbers.java new file mode 100644 index 00000000..13f138c2 --- /dev/null +++ b/Medium/Sum of Square Numbers.java @@ -0,0 +1,18 @@ +class Solution { + public boolean judgeSquareSum(int c) { + long left = 0; + long right = (long) Math.sqrt(c); + while (left <= right) { + long sum = left * left + right * right; + if (sum == c) { + return true; + } + if (sum > c) { + right--; + } else { + left++; + } + } + return false; + } +} From afa6897e96bfbbdb962b93586795c73bee61c0ec Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 19 Jun 2024 13:30:47 -0700 Subject: [PATCH 018/182] Create Minimum Number of Days to Make m Bouquets.java --- ...mum Number of Days to Make m Bouquets.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Medium/Minimum Number of Days to Make m Bouquets.java diff --git a/Medium/Minimum Number of Days to Make m Bouquets.java b/Medium/Minimum Number of Days to Make m Bouquets.java new file mode 100644 index 00000000..83578712 --- /dev/null +++ b/Medium/Minimum Number of Days to Make m Bouquets.java @@ -0,0 +1,37 @@ +class Solution { + public int minDays(int[] bloomDay, int m, int k) { + int left = 0; + int right = 0; + for (int day : bloomDay) { + right = Math.max(right, day); + } + int days = -1; + while (left <= right) { + int mid = (left + right) / 2; + if (numberOfBouquet(bloomDay, mid, k) >= m) { + days = mid; + right = mid - 1; + } else { + left = mid + 1; + } + } + return days; + } + + private int numberOfBouquet(int[] bloomDay, int mid, int k) { + int bouquetCount = 0; + int count = 0; + for (int i = 0; i < bloomDay.length; i++) { + if (bloomDay[i] <= mid) { + count++; + } else { + count = 0; + } + if (count == k) { + bouquetCount++; + count = 0; + } + } + return bouquetCount; + } +} From 865f81f10f77b149e5e6619ef81884ff8f4b8834 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 20 Jun 2024 14:07:47 -0700 Subject: [PATCH 019/182] Create Magnetic Force Between Two Balls.java --- Medium/Magnetic Force Between Two Balls.java | 32 ++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Medium/Magnetic Force Between Two Balls.java diff --git a/Medium/Magnetic Force Between Two Balls.java b/Medium/Magnetic Force Between Two Balls.java new file mode 100644 index 00000000..9ca9708b --- /dev/null +++ b/Medium/Magnetic Force Between Two Balls.java @@ -0,0 +1,32 @@ +class Solution { + public int maxDistance(int[] position, int m) { + int result = 0; + int n = position.length; + Arrays.sort(position); + int left = 1; + int right = (int) Math.ceil(position[n - 1] / (m - 1.0)); + while (left <= right) { + int mid = (left + right) / 2; + if (isPossible(position, mid, m)) { + result = mid; + left = mid + 1; + } else { + right = mid - 1; + } + } + return result; + } + + private boolean isPossible(int[] position, int distance, int m) { + int prevBall = position[0]; + int ballCount = 1; + for (int i = 1; i < position.length && ballCount < m; i++) { + int curr = position[i]; + if (curr - prevBall >= distance) { + ballCount++; + prevBall = curr; + } + } + return ballCount == m; + } +} From 397b6b81b5f0cf0f9809e9b72e969743f81e7ab5 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 22 Jun 2024 08:48:10 -0700 Subject: [PATCH 020/182] Create Count Number of Nice Subarrays.java --- Medium/Count Number of Nice Subarrays.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Medium/Count Number of Nice Subarrays.java diff --git a/Medium/Count Number of Nice Subarrays.java b/Medium/Count Number of Nice Subarrays.java new file mode 100644 index 00000000..e2648bd3 --- /dev/null +++ b/Medium/Count Number of Nice Subarrays.java @@ -0,0 +1,14 @@ +class Solution { + public int numberOfSubarrays(int[] nums, int k) { + int sum = 0; + int count = 0; + Map map = new HashMap<>(); + map.put(sum, 1); + for (int i = 0; i < nums.length; i++) { + sum += nums[i] % 2; + count += map.getOrDefault(sum - k, 0); + map.put(sum, map.getOrDefault(sum, 0) + 1); + } + return count; + } +} From 2c963723a148f3d328299c9aa14263a243ba20ba Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 22 Jun 2024 10:49:45 -0700 Subject: [PATCH 021/182] Create Find Minimum Operations to Make All Elements Divisible by Three.java --- ...tions to Make All Elements Divisible by Three.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Easy/Find Minimum Operations to Make All Elements Divisible by Three.java diff --git a/Easy/Find Minimum Operations to Make All Elements Divisible by Three.java b/Easy/Find Minimum Operations to Make All Elements Divisible by Three.java new file mode 100644 index 00000000..c8d6f59e --- /dev/null +++ b/Easy/Find Minimum Operations to Make All Elements Divisible by Three.java @@ -0,0 +1,11 @@ +class Solution { + public int minimumOperations(int[] nums) { + int count = 0; + for (int num : nums) { + if (num % 3 != 0) { + count++; + } + } + return count; + } +} From d5206efa86285870633ce24b787c615174e262bc Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 22 Jun 2024 10:59:45 -0700 Subject: [PATCH 022/182] Create Count Substrings Without Repeating Character.java --- ...ubstrings Without Repeating Character.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Medium/Count Substrings Without Repeating Character.java diff --git a/Medium/Count Substrings Without Repeating Character.java b/Medium/Count Substrings Without Repeating Character.java new file mode 100644 index 00000000..6ffcf7cd --- /dev/null +++ b/Medium/Count Substrings Without Repeating Character.java @@ -0,0 +1,19 @@ +class Solution { + public int numberOfSpecialSubstrings(String s) { + int start = 0; + int end = 0; + int n = s.length(); + int result = 0; + Map map = new HashMap<>(); + while (end < n) { + map.put(s.charAt(end), map.getOrDefault(s.charAt(end), 0) + 1); + while (start < end && map.get(s.charAt(end)) > 1) { + map.put(s.charAt(start), map.get(s.charAt(start)) - 1); + start++; + } + end++; + result += end - start; + } + return result; + } +} From 1063dfd5b34ccff45628bd431e23aa294b43ff40 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 24 Jun 2024 07:46:06 -0700 Subject: [PATCH 023/182] Create Minimum Average of Smallest and Largest Elements.java --- ... Average of Smallest and Largest Elements.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Easy/Minimum Average of Smallest and Largest Elements.java diff --git a/Easy/Minimum Average of Smallest and Largest Elements.java b/Easy/Minimum Average of Smallest and Largest Elements.java new file mode 100644 index 00000000..f1fd9e2d --- /dev/null +++ b/Easy/Minimum Average of Smallest and Largest Elements.java @@ -0,0 +1,15 @@ +class Solution { + public double minimumAverage(int[] nums) { + double minAverage = Double.MAX_VALUE; + Arrays.sort(nums); + int left = 0; + int right = nums.length - 1; + while (left < right) { + double average = (nums[left] + nums[right]) / 2.0; + minAverage = Math.min(minAverage, average); + left++; + right--; + } + return minAverage; + } +} From 35ee9b003d7dd5e17a732680fd195e2a75fe2c37 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 25 Jun 2024 07:18:51 -0700 Subject: [PATCH 024/182] Create Find the Minimum Area to Cover All Ones I.java --- ... the Minimum Area to Cover All Ones I.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Medium/Find the Minimum Area to Cover All Ones I.java diff --git a/Medium/Find the Minimum Area to Cover All Ones I.java b/Medium/Find the Minimum Area to Cover All Ones I.java new file mode 100644 index 00000000..538bf894 --- /dev/null +++ b/Medium/Find the Minimum Area to Cover All Ones I.java @@ -0,0 +1,24 @@ +class Solution { + public int minimumArea(int[][] grid) { + int minRow = Integer.MAX_VALUE; + int minCol = Integer.MAX_VALUE; + int maxRow = Integer.MIN_VALUE; + int maxCol = Integer.MIN_VALUE; + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == 1) { + minRow = Math.min(minRow, i); + minCol = Math.min(minCol, j); + maxRow = Math.max(maxRow, i); + maxCol = Math.max(maxCol, j); + } + } + } + if (minRow == Integer.MAX_VALUE) { + return 0; + } + int length = maxRow - minRow + 1; + int breadth = maxCol - minCol + 1; + return length * breadth; + } +} From acfa4c155ad1e7a95a28695f1d142b6fe80fbd7d Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 25 Jun 2024 18:09:27 -0700 Subject: [PATCH 025/182] Update Balance a Binary Search Tree.java --- Medium/Balance a Binary Search Tree.java | 54 ++++++++++++++---------- 1 file changed, 31 insertions(+), 23 deletions(-) diff --git a/Medium/Balance a Binary Search Tree.java b/Medium/Balance a Binary Search Tree.java index 9fbf14ce..dd07996e 100644 --- a/Medium/Balance a Binary Search Tree.java +++ b/Medium/Balance a Binary Search Tree.java @@ -14,29 +14,37 @@ * } */ class Solution { - public TreeNode balanceBST(TreeNode root) { - List sortedList = new ArrayList<>(); - inorderTraversal(root, sortedList); - return buildBST(sortedList, 0, sortedList.size() - 1); - } - - private TreeNode buildBST(List sortedList, int start, int end) { - if (start > end) { - return null; + public TreeNode balanceBST(TreeNode root) { + List inorder = getInorderNodes(root); + return createBST(inorder, 0, inorder.size() - 1); } - int mid = (start + end) / 2; - TreeNode root = new TreeNode(sortedList.get(mid)); - root.left = buildBST(sortedList, start, mid - 1); - root.right = buildBST(sortedList, mid + 1, end); - return root; - } - - private void inorderTraversal(TreeNode root, List sortedList) { - if (root == null) { - return; + + private List getInorderNodes(TreeNode root) { + Stack stack = new Stack<>(); + while (root != null) { + stack.push(root); + root = root.left; + } + List list = new ArrayList<>(); + while (!stack.isEmpty()) { + TreeNode node = stack.pop(); + list.add(node.val); + TreeNode rightNode = node.right; + while (rightNode != null) { + stack.push(rightNode); + rightNode = rightNode.left; + } + } + return list; + } + + private TreeNode createBST(List list, int start, int end) { + if (start > end) { + return null; + } + int mid = (start + end) / 2; + TreeNode leftTree = createBST(list, start, mid - 1); + TreeNode rightTree = createBST(list, mid + 1, end); + return new TreeNode(list.get(mid), leftTree, rightTree); } - inorderTraversal(root.left, sortedList); - sortedList.add(root.val); - inorderTraversal(root.right, sortedList); - } } From a116f9b3c5fa4477a54e5ebef4531f46ddfecdd5 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 26 Jun 2024 07:21:54 -0700 Subject: [PATCH 026/182] Create Minimum Operations to Make Binary Array Elements Equal to One I.java --- ... Binary Array Elements Equal to One I.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Medium/Minimum Operations to Make Binary Array Elements Equal to One I.java diff --git a/Medium/Minimum Operations to Make Binary Array Elements Equal to One I.java b/Medium/Minimum Operations to Make Binary Array Elements Equal to One I.java new file mode 100644 index 00000000..4b5b20a1 --- /dev/null +++ b/Medium/Minimum Operations to Make Binary Array Elements Equal to One I.java @@ -0,0 +1,19 @@ +class Solution { + public int minOperations(int[] nums) { + int count = 0; + for (int i = 0; i <= nums.length - 3; i++) { + if (nums[i] == 0) { + nums[i] = nums[i] == 0 ? 1 : 0; + nums[i + 1] = nums[i + 1] == 0 ? 1 : 0; + nums[i + 2] = nums[i + 2] == 0 ? 1 : 0; + count++; + } + } + for (int i = nums.length - 3; i < nums.length; i++) { + if (nums[i] == 0) { + return -1; + } + } + return count; + } +} From f981b3283fbd6a9bd483a813cd1c502c3e27de67 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 27 Jun 2024 06:32:40 -0700 Subject: [PATCH 027/182] Update Find Center of Star Graph.java --- Medium/Find Center of Star Graph.java | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/Medium/Find Center of Star Graph.java b/Medium/Find Center of Star Graph.java index f3f6de5a..8270ad2d 100644 --- a/Medium/Find Center of Star Graph.java +++ b/Medium/Find Center of Star Graph.java @@ -1,13 +1,16 @@ -import java.util.Map.Entry; - class Solution { - public int findCenter(int[][] edges) { - Map> map = new HashMap<>(); - for (int[] edge : edges) { - map.computeIfAbsent(edge[0], k -> new HashSet<>()).add(edge[1]); - map.computeIfAbsent(edge[1], k -> new HashSet<>()).add(edge[0]); + public int findCenter(int[][] edges) { + Map map = new HashMap<>(); + int n = edges.length; + for (int[] edge : edges) { + map.put(edge[0], map.getOrDefault(edge[0], 0) + 1); + map.put(edge[1], map.getOrDefault(edge[1], 0) + 1); + } + for (Integer key : map.keySet()) { + if (map.get(key) == n) { + return key; + } + } + return -1; } - return map.entrySet().stream().filter(entry -> entry.getValue().size() == edges.length).map( - Entry::getKey).findFirst().orElse(-1); - } } From 41b043a398434deca08dd2d99c179d1fc1c2a3a9 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 29 Jun 2024 12:53:22 -0700 Subject: [PATCH 028/182] Update All Ancestors of a Node in a Directed Acyclic Graph.java --- ...of a Node in a Directed Acyclic Graph.java | 54 +++++++++++-------- 1 file changed, 32 insertions(+), 22 deletions(-) diff --git a/Medium/All Ancestors of a Node in a Directed Acyclic Graph.java b/Medium/All Ancestors of a Node in a Directed Acyclic Graph.java index 60ab5900..36063815 100644 --- a/Medium/All Ancestors of a Node in a Directed Acyclic Graph.java +++ b/Medium/All Ancestors of a Node in a Directed Acyclic Graph.java @@ -1,26 +1,36 @@ class Solution { - public List> getAncestors(int n, int[][] edges) { - Map> graph = new HashMap<>(); - for (int[] edge : edges) { - graph.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]); - } - List> result = new ArrayList<>(); - for (int i = 0; i < n; i++) { - List ancestors = new ArrayList<>(); - Set visited = new HashSet<>(); - Queue queue = new LinkedList<>(graph.getOrDefault(i, new ArrayList<>())); - while (!queue.isEmpty()) { - int removed = queue.remove(); - if (visited.contains(removed)) { - continue; + public List> getAncestors(int n, int[][] edges) { + Map> graph = new HashMap<>(); + int[] indegree = new int[n]; + for (int[] edge : edges) { + graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]); + indegree[edge[1]]++; + } + Queue queue = new LinkedList<>(); + Map> ancestors = new HashMap<>(); + for (int i = 0; i < n; i++) { + if (indegree[i] == 0) { + queue.offer(i); + } + } + while (!queue.isEmpty()) { + int node = queue.poll(); + ancestors.computeIfAbsent(node, k -> new HashSet<>()); + for (int dependents : graph.getOrDefault(node, Collections.emptyList())) { + ancestors.computeIfAbsent(dependents, k -> new HashSet<>()).add(node); + ancestors.get(dependents).addAll(ancestors.get(node)); + indegree[dependents]--; + if (indegree[dependents] == 0) { + queue.offer(dependents); + } + } + } + List> result = new ArrayList<>(); + for (int i = 0; i < n; i++) { + List currNodeAncestors = new ArrayList<>(ancestors.getOrDefault(i, Collections.emptySet())); + currNodeAncestors.sort(Comparator.naturalOrder()); + result.add(currNodeAncestors); } - ancestors.add(removed); - visited.add(removed); - queue.addAll(graph.getOrDefault(removed, new ArrayList<>())); - } - Collections.sort(ancestors); - result.add(ancestors); + return result; } - return result; - } } From 60879733e7648f86e0b1fbc071ad7f72ea520c35 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 1 Jul 2024 07:21:18 -0700 Subject: [PATCH 029/182] Update The Earliest Moment When Everyone Become Friends.java --- ...t Moment When Everyone Become Friends.java | 78 ++++++++----------- 1 file changed, 33 insertions(+), 45 deletions(-) diff --git a/Medium/The Earliest Moment When Everyone Become Friends.java b/Medium/The Earliest Moment When Everyone Become Friends.java index 578a04cb..8de3e818 100644 --- a/Medium/The Earliest Moment When Everyone Become Friends.java +++ b/Medium/The Earliest Moment When Everyone Become Friends.java @@ -1,54 +1,42 @@ class Solution { - public int earliestAcq(int[][] logs, int n) { - Arrays.sort(logs, Comparator.comparingInt(o -> o[0])); - DisjointSet disjointSet = new DisjointSet(n); - for (int[] log : logs) { - disjointSet.union(log[1], log[2]); - if (disjointSet.unionCount == 1) { - return log[0]; - } + public int earliestAcq(int[][] logs, int n) { + Arrays.sort(logs, Comparator.comparingInt(a -> a[0])); + UnionFind uf = new UnionFind(n); + for (int[] log : logs) { + uf.union(log[1], log[2]); + if (uf.count == 1) { + return log[0]; + } + } + return -1; } - return -1; - } - - private static final class DisjointSet { - private final int[] root; - private final int[] rank; - public int unionCount; - - public DisjointSet(int size) { - this.root = new int[size]; - this.rank = new int[size]; - for (int i = 0; i < size; i++) { - this.root[i] = i; - this.rank[i] = 1; - } - this.unionCount = size; - } + static class UnionFind { + private final int[] parent; + private int count; - public void union(int nodeOne, int nodeTwo) { - int rootOne = find(nodeOne); - int rootTwo = find(nodeTwo); - if (rootOne != rootTwo) { - if (this.rank[rootOne] > this.rank[rootTwo]) { - this.root[rootTwo] = rootOne; - } else if (this.rank[rootOne] < this.rank[rootTwo]) { - this.root[rootOne] = rootTwo; - } else { - this.root[rootTwo] = rootOne; - this.rank[rootOne]++; + public UnionFind(int n) { + parent = new int[n]; + count = n; + for (int i = 0; i < n; i++) { + parent[i] = i; + } } - this.unionCount--; - } - } + public int find(int node) { + if (parent[node] != node) { + parent[node] = find(parent[node]); + } + return parent[node]; + } - public int find(int node) { - if (node == root[node]) { - return node; - } - return root[node] = find(root[node]); + public void union(int x, int y) { + int rootX = find(x); + int rootY = find(y); + if (rootX != rootY) { + parent[rootX] = rootY; + count--; + } + } } - } } From 568f9bad22717e799a2aa1b910df29b14f92f5a2 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 3 Jul 2024 07:40:43 -0700 Subject: [PATCH 030/182] Create Minimum Difference Between Largest and Smallest Value in Three Moves.java --- ...argest and Smallest Value in Three Moves.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Medium/Minimum Difference Between Largest and Smallest Value in Three Moves.java diff --git a/Medium/Minimum Difference Between Largest and Smallest Value in Three Moves.java b/Medium/Minimum Difference Between Largest and Smallest Value in Three Moves.java new file mode 100644 index 00000000..2722191a --- /dev/null +++ b/Medium/Minimum Difference Between Largest and Smallest Value in Three Moves.java @@ -0,0 +1,16 @@ +class Solution { + public int minDifference(int[] nums) { + int n = nums.length; + if (n <= 4) { + return 0; + } + Arrays.sort(nums); + int minDiff = Integer.MAX_VALUE; + int left = 0; + int right = n - 4; + while (left < 4) { + minDiff = Math.min(minDiff, nums[right++] - nums[left++]); + } + return minDiff; + } +} From 86ad1a23993e937706f6572c2b10bc6ba012ee07 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 8 Jul 2024 13:39:33 -0700 Subject: [PATCH 031/182] Create Find the Winner of the Circular Game.java --- Medium/Find the Winner of the Circular Game.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Medium/Find the Winner of the Circular Game.java diff --git a/Medium/Find the Winner of the Circular Game.java b/Medium/Find the Winner of the Circular Game.java new file mode 100644 index 00000000..816b3aa4 --- /dev/null +++ b/Medium/Find the Winner of the Circular Game.java @@ -0,0 +1,15 @@ +class Solution { + public int findTheWinner(int n, int k) { + Queue circle = new LinkedList<>(); + for (int i = 1; i <= n; i++) { + circle.add(i); + } + while (circle.size() > 1) { + for (int i = 0; i < k - 1; i++) { + circle.add(circle.remove()); + } + circle.remove(); + } + return circle.peek(); + } +} From be7bd21bae156c80b5d304f095e4c1c7c3c1a9ba Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 9 Jul 2024 16:31:31 -0700 Subject: [PATCH 032/182] Update Remove Duplicates From an Unsorted Linked List.java --- ...plicates From an Unsorted Linked List.java | 46 +++++++++---------- 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/Medium/Remove Duplicates From an Unsorted Linked List.java b/Medium/Remove Duplicates From an Unsorted Linked List.java index e62d60c7..18308224 100644 --- a/Medium/Remove Duplicates From an Unsorted Linked List.java +++ b/Medium/Remove Duplicates From an Unsorted Linked List.java @@ -9,31 +9,29 @@ * } */ class Solution { - public ListNode deleteDuplicatesUnsorted(ListNode head) { - Map map = new HashMap<>(); - ListNode curr = head; - while (curr != null) { - map.put(curr.val, map.getOrDefault(curr.val, 0) + 1); - curr = curr.next; - } - curr = head; - ListNode newHead = null; - ListNode prev = null; - while (curr != null) { - if (map.get(curr.val) > 1) { - ListNode nextNode = curr.next; - if (prev != null) { - prev.next = nextNode; + public ListNode deleteDuplicatesUnsorted(ListNode head) { + Map map = new HashMap<>(); + ListNode curr = head; + while (curr != null) { + map.put(curr.val, map.getOrDefault(curr.val, 0) + 1); + curr = curr.next; } - curr = nextNode; - } else { - if (newHead == null) { - newHead = curr; + curr = head; + ListNode prev = null; + ListNode newHead = null; + while (curr != null) { + if (map.get(curr.val) > 1) { + if (prev != null) { + prev.next = curr.next; + } + } else { + prev = curr; + if (newHead == null) { + newHead = curr; + } + } + curr = curr.next; } - prev = curr; - curr = curr.next; - } + return newHead; } - return newHead; - } } From 3625ba91340dcefb6ff2183a75d4c7e333dc7481 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 12 Jul 2024 06:50:40 -0700 Subject: [PATCH 033/182] Create Maximum Score From Removing Substrings.java --- ...aximum Score From Removing Substrings.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Medium/Maximum Score From Removing Substrings.java diff --git a/Medium/Maximum Score From Removing Substrings.java b/Medium/Maximum Score From Removing Substrings.java new file mode 100644 index 00000000..0f7ccf87 --- /dev/null +++ b/Medium/Maximum Score From Removing Substrings.java @@ -0,0 +1,29 @@ +class Solution { + public int maximumGain(String s, int x, int y) { + int score = 0; + String firstPass = removeSubstring(s, x > y ? "ab" : "ba"); + int removeCount = (s.length() - firstPass.length()) / 2; + score += removeCount * Math.max(x, y); + String secondPass = removeSubstring(firstPass, x > y ? "ba" : "ab"); + removeCount = (firstPass.length() - secondPass.length()) / 2; + score += removeCount * Math.min(x, y); + return score; + } + + private String removeSubstring(String s, String target) { + Stack stack = new Stack<>(); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == target.charAt(1) && !stack.isEmpty() && stack.peek() == target.charAt(0)) { + stack.pop(); + } else { + stack.push(c); + } + } + StringBuilder sb = new StringBuilder(); + while (!stack.isEmpty()) { + sb.append(stack.pop()); + } + return sb.reverse().toString(); + } +} From df3dac19974910cc81c4c737a0ee85245adf5685 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 13 Jul 2024 10:03:58 -0700 Subject: [PATCH 034/182] Create Robot Collisions.java --- Hard/Robot Collisions.java | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Hard/Robot Collisions.java diff --git a/Hard/Robot Collisions.java b/Hard/Robot Collisions.java new file mode 100644 index 00000000..4202122c --- /dev/null +++ b/Hard/Robot Collisions.java @@ -0,0 +1,38 @@ +class Solution { + public List survivedRobotsHealths(int[] positions, int[] healths, String directions) { + int n = positions.length; + Integer[] indices = new Integer[n]; + for (int i = 0; i < n; i++) { + indices[i] = i; + } + Arrays.sort(indices, (a, b) -> Integer.compare(positions[a], positions[b])); + Stack stack = new Stack<>(); + for (Integer index : indices) { + if (directions.charAt(index) == 'R') { + stack.push(index); + } else { + while (!stack.isEmpty() && healths[index] > 0) { + int poppedIndex = stack.pop(); + if (healths[poppedIndex] > healths[index]) { + healths[poppedIndex]--; + healths[index] = 0; + stack.push(poppedIndex); + } else if (healths[poppedIndex] < healths[index]) { + healths[index]--; + healths[poppedIndex] = 0; + } else { + healths[poppedIndex] = 0; + healths[index] = 0; + } + } + } + } + List result = new ArrayList<>(); + for (int i = 0; i < n; i++) { + if (healths[i] > 0) { + result.add(healths[i]); + } + } + return result; + } +} From 62f366439d3bdf7e63794356eb1c544a3b5afef4 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 13 Jul 2024 17:34:13 -0700 Subject: [PATCH 035/182] Create Maximum Points After Enemy Battles.java --- Medium/Maximum Points After Enemy Battles.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Medium/Maximum Points After Enemy Battles.java diff --git a/Medium/Maximum Points After Enemy Battles.java b/Medium/Maximum Points After Enemy Battles.java new file mode 100644 index 00000000..2358cd8f --- /dev/null +++ b/Medium/Maximum Points After Enemy Battles.java @@ -0,0 +1,16 @@ +class Solution { + public long maximumPoints(int[] enemyEnergies, int currentEnergy) { + long sum = 0; + int minimumEnergy = Integer.MAX_VALUE; + for (int energy : enemyEnergies) { + sum += energy; + minimumEnergy = Math.min(minimumEnergy, energy); + } + if (currentEnergy < minimumEnergy) { + return 0; + } + long totalEnergy = currentEnergy; + totalEnergy += sum - minimumEnergy; + return totalEnergy / minimumEnergy; + } +} From 57435b89c7cbca66b994cf2f3c05de888bf3c924 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 17 Jul 2024 07:12:38 -0700 Subject: [PATCH 036/182] Update Delete Nodes And Return Forest.java --- Medium/Delete Nodes And Return Forest.java | 53 +++++++++++----------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/Medium/Delete Nodes And Return Forest.java b/Medium/Delete Nodes And Return Forest.java index c3ec8f1b..344770b5 100644 --- a/Medium/Delete Nodes And Return Forest.java +++ b/Medium/Delete Nodes And Return Forest.java @@ -14,33 +14,34 @@ * } */ class Solution { - public List delNodes(TreeNode root, int[] to_delete) { - List result = new ArrayList<>(); - Set deleteSet = Arrays.stream(to_delete).boxed().collect(Collectors.toSet()); - helper(root, deleteSet, result, null); - return result; - } - - private void helper(TreeNode node, Set deleteSet, List result, TreeNode parent) { - if (node == null) { - return; + public List delNodes(TreeNode root, int[] toDelete) { + Set set = new HashSet<>(); + for (int val : toDelete) { + set.add(val); + } + List result = new ArrayList<>(); + recurse(root, result, set, null); + return result; } - TreeNode nextParent = null; - if (deleteSet.contains(node.val)) { - if (parent != null) { - if (parent.left == node) { - parent.left = null; - } else { - parent.right = null; + + private void recurse(TreeNode root, List result, Set set, TreeNode parent) { + if (root == null) { + return; + } + if (set.contains(root.val)) { + if (parent != null && parent.left == root) { + parent.left = null; + } else if (parent != null && parent.right == root) { + parent.right = null; + } + recurse(root.left, result, set, null); + recurse(root.right, result, set, null); + return; + } + if (parent == null) { + result.add(root); } - } - } else { - if (parent == null) { - result.add(node); - } - nextParent = node; + recurse(root.left, result, set, root); + recurse(root.right, result, set, root); } - helper(node.left, deleteSet, result, nextParent); - helper(node.right, deleteSet, result, nextParent); - } } From e69114728912b48564c236b4744428d4aecccfb2 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 22 Jul 2024 07:35:17 -0700 Subject: [PATCH 037/182] Create Number of Good Leaf Nodes Pairs.java --- Medium/Number of Good Leaf Nodes Pairs.java | 59 +++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Medium/Number of Good Leaf Nodes Pairs.java diff --git a/Medium/Number of Good Leaf Nodes Pairs.java b/Medium/Number of Good Leaf Nodes Pairs.java new file mode 100644 index 00000000..c54d967f --- /dev/null +++ b/Medium/Number of Good Leaf Nodes Pairs.java @@ -0,0 +1,59 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int countPairs(TreeNode root, int distance) { + Map> graph = new HashMap<>(); + Set leaves = new HashSet<>(); + traverse(root, null, graph, leaves); + int result = 0; + for (TreeNode leaf : leaves) { + Queue queue = new LinkedList<>(); + Set visited = new HashSet<>(); + queue.add(leaf); + visited.add(leaf); + for (int i = 0; i <= distance; i++) { + int size = queue.size(); + while (size-- > 0) { + TreeNode curr = queue.remove(); + if (leaves.contains(curr) && curr != leaf) { + result++; + } + for (TreeNode neighbor : graph.getOrDefault(curr, new ArrayList<>())) { + if (visited.add(neighbor)) { + queue.add(neighbor); + } + } + } + } + } + return result / 2; + } + + private void traverse(TreeNode node, TreeNode parent, Map> graph, Set leaves) { + if (node == null) { + return; + } + if (node.left == null && node.right == null) { + leaves.add(node); + } + if (parent != null) { + graph.computeIfAbsent(parent, k -> new ArrayList<>()).add(node); + graph.computeIfAbsent(node, k -> new ArrayList<>()).add(parent); + } + traverse(node.left, node, graph, leaves); + traverse(node.right, node, graph, leaves); + } +} From 9800de288ad74098afb62b6eebe3ffa044f9604a Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 28 Jul 2024 13:44:49 -0700 Subject: [PATCH 038/182] Create Find if Digit Game Can Be Won.java --- Easy/Find if Digit Game Can Be Won.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Easy/Find if Digit Game Can Be Won.java diff --git a/Easy/Find if Digit Game Can Be Won.java b/Easy/Find if Digit Game Can Be Won.java new file mode 100644 index 00000000..22c76892 --- /dev/null +++ b/Easy/Find if Digit Game Can Be Won.java @@ -0,0 +1,14 @@ +class Solution { + public boolean canAliceWin(int[] nums) { + int singleDigitSum = 0; + int doubleDigitSum = 0; + for (int num : nums) { + if (String.valueOf(num).length() > 1) { + doubleDigitSum += num; + } else { + singleDigitSum += num; + } + } + return singleDigitSum > doubleDigitSum || doubleDigitSum > singleDigitSum; + } +} From c977c77ff129b5957082b1134361538b9ef997d1 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 3 Aug 2024 09:43:37 -0700 Subject: [PATCH 039/182] Create Make Two Arrays Equal by Reversing Subarrays.java --- ...wo Arrays Equal by Reversing Subarrays.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Easy/Make Two Arrays Equal by Reversing Subarrays.java diff --git a/Easy/Make Two Arrays Equal by Reversing Subarrays.java b/Easy/Make Two Arrays Equal by Reversing Subarrays.java new file mode 100644 index 00000000..62ce7dca --- /dev/null +++ b/Easy/Make Two Arrays Equal by Reversing Subarrays.java @@ -0,0 +1,18 @@ +class Solution { + public boolean canBeEqual(int[] target, int[] arr) { + Map map = new HashMap<>(); + for (int num : target) { + map.put(num, map.getOrDefault(num, 0) + 1); + } + for (int num : arr) { + if (!map.containsKey(num)) { + return false; + } + map.put(num, map.get(num) - 1); + if (map.get(num) == 0) { + map.remove(num); + } + } + return map.isEmpty(); + } +} From cf1d49ca0da00b6e50a10a2a0a440609a7d13601 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 3 Aug 2024 17:32:33 -0700 Subject: [PATCH 040/182] Update Range Sum of Sorted Subarray Sums.java --- Medium/Range Sum of Sorted Subarray Sums.java | 43 +++++++++---------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/Medium/Range Sum of Sorted Subarray Sums.java b/Medium/Range Sum of Sorted Subarray Sums.java index c8dad58b..9b7504b7 100644 --- a/Medium/Range Sum of Sorted Subarray Sums.java +++ b/Medium/Range Sum of Sorted Subarray Sums.java @@ -1,26 +1,23 @@ class Solution { - final int MOD = 100000007; - public int rangeSum(int[] nums, int n, int left, int right) { - PriorityQueue pq = new PriorityQueue<>(new Comparator(){ - public int compare(int[] o1, int[] o2) { - return o1[0] - o2[0]; - } - }); - for (int i = 0; i < n; i++) { - pq.add(new int[]{nums[i], i + 1}); + private static final int MOD = 1000_000_007; + + public int rangeSum(int[] nums, int n, int left, int right) { + Queue pq = new PriorityQueue<>(Comparator.comparingInt(o -> o[0])); + for (int i = 0; i < n; i++) { + pq.add(new int[]{nums[i], i + 1}); + } + int sum = 0; + for (int i = 1; i <= right; i++) { + int[] removed = pq.poll(); + if (i >= left) { + sum = (sum + removed[0]) % MOD; + } + if (removed[1] < n) { + removed[0] = removed[0] + nums[removed[1]]; + removed[1]++; + pq.add(removed); + } + } + return sum; } - int sum = 0; - for (int i = 1; i <= right; i++) { - int[] removed = pq.poll(); - if (i >= left) { - sum = (sum + removed[0]) % MOD; - } - if (removed[1] < n) { - removed[0] = removed[0] + nums[removed[1]]; - removed[1]++; - pq.add(removed); - } - } - return sum; - } } From b082bd05c66faa3219ce3252834d273131100a28 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 4 Aug 2024 11:14:17 -0700 Subject: [PATCH 041/182] Create Design Neighbor Sum Service.java --- Easy/Design Neighbor Sum Service.java | 50 +++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Easy/Design Neighbor Sum Service.java diff --git a/Easy/Design Neighbor Sum Service.java b/Easy/Design Neighbor Sum Service.java new file mode 100644 index 00000000..93446e53 --- /dev/null +++ b/Easy/Design Neighbor Sum Service.java @@ -0,0 +1,50 @@ +class neighborSum { + + private static final int[][] ADJACENT_DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + private static final int[][] DIAGONAL_DIRS = {{1, -1}, {-1, 1}, {1, 1}, {-1, -1}}; + + private final int[][] grid; + private final int numRows; + private final int numCols; + private final Map valueToCoordinateMap; + + public neighborSum(int[][] grid) { + this.numRows = grid.length; + this.numCols = grid[0].length; + this.valueToCoordinateMap = new HashMap<>(); + this.grid = new int[numRows][numCols]; + for (int i = 0; i < numRows; i++) { + for (int j = 0; j < numCols; j++) { + this.grid[i][j] = grid[i][j]; + this.valueToCoordinateMap.put(grid[i][j], new int[]{i, j}); + } + } + } + + public int adjacentSum(int value) { + return calculateSum(valueToCoordinateMap.get(value), ADJACENT_DIRS); + } + + public int diagonalSum(int value) { + return calculateSum(valueToCoordinateMap.get(value), DIAGONAL_DIRS); + } + + private int calculateSum(int[] coordinate, int[][] directions) { + int sum = 0; + for (int[] dir : directions) { + int newX = dir[0] + coordinate[0]; + int newY = dir[1] + coordinate[1]; + if (newX >= 0 && newX < numRows && newY >= 0 && newY < numCols) { + sum += grid[newX][newY]; + } + } + return sum; + } +} + +/** + * Your neighborSum object will be instantiated and called as such: + * neighborSum obj = new neighborSum(grid); + * int param_1 = obj.adjacentSum(value); + * int param_2 = obj.diagonalSum(value); + */ From d9d2a0cfdccbb6d2c0439839abfce89e534ec0f0 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 5 Aug 2024 07:45:47 -0700 Subject: [PATCH 042/182] Create Find the Number of Winning Players.java --- Easy/Find the Number of Winning Players.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Easy/Find the Number of Winning Players.java diff --git a/Easy/Find the Number of Winning Players.java b/Easy/Find the Number of Winning Players.java new file mode 100644 index 00000000..fd4ea2ba --- /dev/null +++ b/Easy/Find the Number of Winning Players.java @@ -0,0 +1,14 @@ +class Solution { + public int winningPlayerCount(int n, int[][] pick) { + Map> map = new HashMap<>(); + Set winners = new HashSet<>(); + for (int[] p : pick) { + map.computeIfAbsent(p[0], k -> new HashMap<>()); + map.get(p[0]).put(p[1], map.get(p[0]).getOrDefault(p[1], 0) + 1); + if (map.get(p[0]).get(p[1]) > p[0]) { + winners.add(p[0]); + } + } + return winners.size(); + } +} From ed0f41e4e3f6c4a2bf7b60609d5c4d8ea214e049 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 5 Aug 2024 18:17:23 -0700 Subject: [PATCH 043/182] Create Minimum Number of Pushes to Type Word II.java --- ...imum Number of Pushes to Type Word II.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Medium/Minimum Number of Pushes to Type Word II.java diff --git a/Medium/Minimum Number of Pushes to Type Word II.java b/Medium/Minimum Number of Pushes to Type Word II.java new file mode 100644 index 00000000..71ec90f6 --- /dev/null +++ b/Medium/Minimum Number of Pushes to Type Word II.java @@ -0,0 +1,23 @@ +class Solution { + public int minimumPushes(String word) { + Map map = new HashMap<>(); + for (char c : word.toCharArray()) { + map.put(c, map.getOrDefault(c, 0) + 1); + } + PriorityQueue pq = new PriorityQueue<>((a, b) -> map.get(b).compareTo(map.get(a))); + pq.addAll(map.keySet()); + int count = 0; + int typeMultiple = 1; + int counter = 0; + while (!pq.isEmpty()) { + char removed = pq.poll(); + count += typeMultiple * map.get(removed); + counter++; + if (counter == 8) { + counter = 0; + typeMultiple++; + } + } + return count; + } +} From 961e9f70e34b77d1d2cf69c745e9ec46cb27cf58 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 7 Aug 2024 08:13:34 -0700 Subject: [PATCH 044/182] Create Shortest Distance After Road Addition Queries I.java --- ...istance After Road Addition Queries I.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Medium/Shortest Distance After Road Addition Queries I.java diff --git a/Medium/Shortest Distance After Road Addition Queries I.java b/Medium/Shortest Distance After Road Addition Queries I.java new file mode 100644 index 00000000..19a2ea74 --- /dev/null +++ b/Medium/Shortest Distance After Road Addition Queries I.java @@ -0,0 +1,39 @@ +class Solution { + public int[] shortestDistanceAfterQueries(int n, int[][] queries) { + Map> graph = new HashMap<>(); + for (int i = 0; i < n - 1; i++) { + graph.computeIfAbsent(i, k -> new HashSet<>()).add(i + 1); + } + int[] result = new int[queries.length]; + for (int i = 0; i < queries.length; i++) { + int[] query = queries[i]; + graph.computeIfAbsent(query[0], k -> new HashSet<>()).add(query[1]); + result[i] = findDistance(graph, n - 1); + } + return result; + } + + private int findDistance(Map> graph, int target) { + Queue queue = new LinkedList<>(); + Set visited = new HashSet<>(); + queue.add(0); + int distance = 0; + while (!queue.isEmpty()) { + int size = queue.size(); + for (int i = 0; i < size; i++) { + Integer node = queue.poll(); + if (node == target) { + return distance; + } + for (Integer neighbor : graph.get(node)) { + if (!visited.contains(neighbor)) { + queue.add(neighbor); + visited.add(node); + } + } + } + distance++; + } + return -1; + } +} From c0e0d7de8dc5b583bf1086c5d96f4f9345a4ee69 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 11 Aug 2024 15:55:40 -0700 Subject: [PATCH 045/182] Create Snake in Matrix.java --- Easy/Snake in Matrix.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Easy/Snake in Matrix.java diff --git a/Easy/Snake in Matrix.java b/Easy/Snake in Matrix.java new file mode 100644 index 00000000..5dce2568 --- /dev/null +++ b/Easy/Snake in Matrix.java @@ -0,0 +1,22 @@ +class Solution { + + private static final Map COMMAND_TO_DIRECTION = Map.of( + "UP", new int[]{-1, 0}, + "DOWN", new int[]{1, 0}, + "LEFT", new int[]{0, -1}, + "RIGHT", new int[]{0, 1} + ); + + public int finalPositionOfSnake(int n, List commands) { + int position = 0; + int x = 0; + int y = 0; + for (String command : commands) { + int[] change = COMMAND_TO_DIRECTION.get(command); + x += change[0]; + y += change[1]; + position = x * n + y; + } + return position; + } +} From 0a57dc54af4305a89540e031d7da72c6dcae9548 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 11 Aug 2024 16:28:37 -0700 Subject: [PATCH 046/182] Create Count the Number of Good Nodes.java --- Medium/Count the Number of Good Nodes.java | 34 ++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Medium/Count the Number of Good Nodes.java diff --git a/Medium/Count the Number of Good Nodes.java b/Medium/Count the Number of Good Nodes.java new file mode 100644 index 00000000..d100513d --- /dev/null +++ b/Medium/Count the Number of Good Nodes.java @@ -0,0 +1,34 @@ +class Solution { + public int countGoodNodes(int[][] edges) { + Map> map = new HashMap<>(); + for (int[] edge : edges) { + map.computeIfAbsent(edge[0], k -> new HashSet<>()).add(edge[1]); + map.computeIfAbsent(edge[1], k -> new HashSet<>()).add(edge[0]); + } + int[] result = {0}; + recurse(map, result, 0, -1); + return result[0]; + } + + private int recurse(Map> map, int[] result, int node, int prevNode) { + int count = -1; + int total = 1; + boolean flag = true; + for (Integer conn : map.getOrDefault(node, new HashSet<>())) { + if (conn == prevNode) { + continue; + } + int temp = recurse(map, result, conn, node); + total += temp; + if (count == -1) { + count = temp; + } else if (count != temp) { + flag = false; + } + } + if (flag) { + result[0]++; + } + return total; + } +} From 8b69a0991f768cb0e7eee430604c769bd24c90e9 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 14 Aug 2024 16:50:03 -0700 Subject: [PATCH 047/182] Create Find K-th Smallest Pair Distance.java --- Hard/Find K-th Smallest Pair Distance.java | 31 ++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Hard/Find K-th Smallest Pair Distance.java diff --git a/Hard/Find K-th Smallest Pair Distance.java b/Hard/Find K-th Smallest Pair Distance.java new file mode 100644 index 00000000..6d84cfa8 --- /dev/null +++ b/Hard/Find K-th Smallest Pair Distance.java @@ -0,0 +1,31 @@ +class Solution { + public int smallestDistancePair(int[] nums, int k) { + Arrays.sort(nums); + int n = nums.length; + int left = 0; + int right = nums[n - 1] - nums[0]; + while (left < right) { + int mid = (left + right) / 2; + int count = countPairs(nums, mid); + if (count < k) { + left = mid + 1; + } else { + right = mid; + } + } + return left; + } + + private int countPairs(int[] nums, int distance) { + int count = 0; + int n = nums.length; + int left = 0; + for (int i = 0; i < n; i++) { + while (nums[i] - nums[left] > distance) { + left++; + } + count += i - left; + } + return count; + } +} From dbff4c4f75e097d5189d566d4bcc28b163efaa1c Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 16 Aug 2024 15:05:13 -0700 Subject: [PATCH 048/182] Update and rename Maximum Distance in Arrays.java to Maximum Distance in Arrays.java --- Easy/Maximum Distance in Arrays.java | 17 ----------------- Medium/Maximum Distance in Arrays.java | 17 +++++++++++++++++ 2 files changed, 17 insertions(+), 17 deletions(-) delete mode 100644 Easy/Maximum Distance in Arrays.java create mode 100644 Medium/Maximum Distance in Arrays.java diff --git a/Easy/Maximum Distance in Arrays.java b/Easy/Maximum Distance in Arrays.java deleted file mode 100644 index 71a4581d..00000000 --- a/Easy/Maximum Distance in Arrays.java +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { - public static int maxDistance(List> arrays) { - int min = arrays.get(0).get(0); - int max = arrays.get(0).get(arrays.get(0).size()-1); - int result = Integer.MIN_VALUE; - - for (int i=1; i> arrays) { + int result = 0; + int n = arrays.get(0).size(); + int min = arrays.get(0).get(0); + int max = arrays.get(0).get(n - 1); + for (int i = 1; i < arrays.size(); i++) { + n = arrays.get(i).size(); + result = Math.max(result, + Math.max(Math.abs(arrays.get(i).get(n - 1) - min), + Math.abs(max - arrays.get(i).get(0)))); + min = Math.min(min, arrays.get(i).get(0)); + max = Math.max(max, arrays.get(i).get(n - 1)); + } + return result; + } +} From bad1223b35eb5306161d677a54157e84114727dc Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 20 Aug 2024 08:29:45 -0700 Subject: [PATCH 049/182] Create Count Substrings That Satisfy K-Constraint I.java --- ...ubstrings That Satisfy K-Constraint I.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Easy/Count Substrings That Satisfy K-Constraint I.java diff --git a/Easy/Count Substrings That Satisfy K-Constraint I.java b/Easy/Count Substrings That Satisfy K-Constraint I.java new file mode 100644 index 00000000..9f44425d --- /dev/null +++ b/Easy/Count Substrings That Satisfy K-Constraint I.java @@ -0,0 +1,21 @@ +class Solution { + public int countKConstraintSubstrings(String s, int k) { + Map map = new HashMap<>(); + int start = 0; + int end = 0; + int n = s.length(); + int result = 0; + while (end < n) { + map.put(s.charAt(end), map.getOrDefault(s.charAt(end), 0) + 1); + end++; + while (start < end && map.getOrDefault('0', 0) > k && map.getOrDefault('1', 0) > k) { + map.put(s.charAt(start), map.get(s.charAt(start)) - 1); + start++; + } + if (map.getOrDefault('0', 0) <= k || map.getOrDefault('1', 0) <= k) { + result += end - start; + } + } + return result; + } +} From 700f9c3e8889b5c97cf03ba4f4859f451422078c Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 20 Aug 2024 17:38:24 -0700 Subject: [PATCH 050/182] Create Find the Power of K-Size Subarrays I.java --- Easy/Find the Power of K-Size Subarrays I.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Easy/Find the Power of K-Size Subarrays I.java diff --git a/Easy/Find the Power of K-Size Subarrays I.java b/Easy/Find the Power of K-Size Subarrays I.java new file mode 100644 index 00000000..975c1a3a --- /dev/null +++ b/Easy/Find the Power of K-Size Subarrays I.java @@ -0,0 +1,18 @@ +class Solution { + public int[] resultsArray(int[] nums, int k) { + if (k == 1) { + return nums; + } + int n = nums.length; + int[] result = new int[n - k + 1]; + Arrays.fill(result, -1); + int count = 1; + for (int i = 0; i < nums.length - 1; i++) { + count = (nums[i + 1] - nums[i] == 1) ? count + 1 : 1; + if (count >= k) { + result[i - k + 2] = nums[i + 1]; + } + } + return result; + } +} From 9f4be8534e7a2658e69fc80c9f52722451071f04 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 22 Aug 2024 17:22:21 -0700 Subject: [PATCH 051/182] Create Fraction Addition and Subtraction.java --- Medium/Fraction Addition and Subtraction.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Medium/Fraction Addition and Subtraction.java diff --git a/Medium/Fraction Addition and Subtraction.java b/Medium/Fraction Addition and Subtraction.java new file mode 100644 index 00000000..3d26da63 --- /dev/null +++ b/Medium/Fraction Addition and Subtraction.java @@ -0,0 +1,42 @@ +class Solution { + public String fractionAddition(String expression) { + int numerator = 0; + int denominator = 1; + int idx = 0; + int n = expression.length(); + while (idx < n) { + int currNumerator = 0; + int currDenominator = 0; + boolean negative = false; + if (expression.charAt(idx) == '-' || expression.charAt(idx) == '+') { + negative = expression.charAt(idx) == '-' ? true : false; + idx++; + } + while (Character.isDigit(expression.charAt(idx))) { + currNumerator = currNumerator * 10 + Character.getNumericValue(expression.charAt(idx)); + idx++; + } + if (negative) { + currNumerator *= -1; + } + idx++; + while (idx < n && Character.isDigit(expression.charAt(idx))) { + currDenominator = currDenominator * 10 + Character.getNumericValue(expression.charAt(idx)); + idx++; + } + numerator = numerator * currDenominator + currNumerator * denominator; + denominator = denominator * currDenominator; + } + int gcd = Math.abs(gcd(numerator, denominator)); + numerator /= gcd; + denominator /= gcd; + return numerator + "/" + denominator; + } + + private int gcd(int a, int b) { + if (a == 0) { + return b; + } + return gcd(b % a, a); + } +} From 17c7839ced9bc02a8ad2595706989700a1caab41 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 25 Aug 2024 17:23:09 -0700 Subject: [PATCH 052/182] Create Final Array State After K Multiplication Operations I.java --- ...e After K Multiplication Operations I.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Easy/Final Array State After K Multiplication Operations I.java diff --git a/Easy/Final Array State After K Multiplication Operations I.java b/Easy/Final Array State After K Multiplication Operations I.java new file mode 100644 index 00000000..da5670de --- /dev/null +++ b/Easy/Final Array State After K Multiplication Operations I.java @@ -0,0 +1,25 @@ +class Solution { + public int[] getFinalState(int[] nums, int k, int multiplier) { + int n = nums.length; + PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt((int[] o) -> o[0]) + .thenComparingInt(o -> o[1])); + for (int i = 0; i < n; i++) { + pq.add(new int[]{nums[i], i}); + } + while (k-- > 0) { + int[] removed = pq.remove(); + int value = removed[0]; + int index = removed[1]; + int newValue = value * multiplier; + pq.add(new int[]{newValue, index}); + } + int[] result = new int[n]; + while (!pq.isEmpty()) { + int[] removed = pq.remove(); + int value = removed[0]; + int index = removed[1]; + result[index] = value; + } + return result; + } +} From d717b453af22cd7a8f21cf3db668b30edbb7734e Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 1 Sep 2024 07:36:13 -0700 Subject: [PATCH 053/182] Create Add Two Polynomials Represented as Linked Lists.java --- ...lynomials Represented as Linked Lists.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Medium/Add Two Polynomials Represented as Linked Lists.java diff --git a/Medium/Add Two Polynomials Represented as Linked Lists.java b/Medium/Add Two Polynomials Represented as Linked Lists.java new file mode 100644 index 00000000..f7eafe3a --- /dev/null +++ b/Medium/Add Two Polynomials Represented as Linked Lists.java @@ -0,0 +1,43 @@ +/** + * Definition for polynomial singly-linked list. + * class PolyNode { + * int coefficient, power; + * PolyNode next = null; + + * PolyNode() {} + * PolyNode(int x, int y) { this.coefficient = x; this.power = y; } + * PolyNode(int x, int y, PolyNode next) { this.coefficient = x; this.power = y; this.next = next; } + * } + */ + +class Solution { + public PolyNode addPoly(PolyNode poly1, PolyNode poly2) { + Map powerToValue = new HashMap<>(); + populateMap(powerToValue, poly1); + populateMap(powerToValue, poly2); + List powerKeys = new ArrayList<>(powerToValue.keySet()); + Collections.sort(powerKeys); + PolyNode dummy = new PolyNode(); + PolyNode curr = dummy; + for (int i = powerKeys.size() - 1; i >= 0; i--) { + if (powerToValue.get(powerKeys.get(i)) == 0) { + continue; + } + PolyNode node = new PolyNode(powerToValue.get(powerKeys.get(i)), powerKeys.get(i)); + curr.next = node; + curr = curr.next; + } + return dummy.next; + } + + private void populateMap(Map powerToValue, PolyNode poly) { + while (poly != null) { + PolyNode node = poly; + int power = node.power; + if (node.coefficient != 0) { + powerToValue.put(power, powerToValue.getOrDefault(power, 0) + node.coefficient); + } + poly = poly.next; + } + } +} From abc7fd46d0bd7d89fb9534dc4487f107a4293a21 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 1 Sep 2024 17:39:57 -0700 Subject: [PATCH 054/182] Update Find the Student that Will Replace the Chalk.java --- ...e Student that Will Replace the Chalk.java | 34 +++++++++++-------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/Medium/Find the Student that Will Replace the Chalk.java b/Medium/Find the Student that Will Replace the Chalk.java index 8ee73065..bdf79d9a 100644 --- a/Medium/Find the Student that Will Replace the Chalk.java +++ b/Medium/Find the Student that Will Replace the Chalk.java @@ -1,17 +1,23 @@ class Solution { - public int chalkReplacer(int[] chalk, int k) { - int initialResult = chalkReplacerHelper(chalk, k); - return initialResult != -1 ? initialResult - : chalkReplacerHelper(chalk, k % Arrays.stream(chalk).sum()); - } - - private int chalkReplacerHelper(int[] chalk, int k) { - for (int i = 0; i < chalk.length; i++) { - if (k - chalk[i] < 0) { - return i; - } - k -= chalk[i]; + public int chalkReplacer(int[] chalk, int k) { + int n = chalk.length; + long[] prefixSum = new long[n]; + prefixSum[0] = chalk[0]; + for (int i = 1; i < n; i++) { + prefixSum[i] = chalk[i] + prefixSum[i - 1]; + } + long total = prefixSum[n - 1]; + long remaining = k % total; + int left = 0; + int right = n - 1; + while (left < right) { + int mid = (left + right) / 2; + if (prefixSum[mid] <= remaining) { + left = mid + 1; + } else { + right = mid; + } + } + return right; } - return -1; - } } From 391f4c4f861b0e95ae7281346e190c2b3ef7dff4 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 3 Sep 2024 06:11:54 -0700 Subject: [PATCH 055/182] Update Sum of Digits of String After Convert.java --- ...Sum of Digits of String After Convert.java | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/Easy/Sum of Digits of String After Convert.java b/Easy/Sum of Digits of String After Convert.java index c86c724c..3b78aaae 100644 --- a/Easy/Sum of Digits of String After Convert.java +++ b/Easy/Sum of Digits of String After Convert.java @@ -1,17 +1,18 @@ class Solution { - public int getLucky(String s, int k) { - StringBuilder sb = new StringBuilder(); - for (char c : s.toCharArray()) { - sb.append(c - 'a' + 1); + public int getLucky(String s, int k) { + StringBuilder sb = new StringBuilder(); + for (char c : s.toCharArray()) { + sb.append(c - 'a' + 1); + } + while (k-- > 0) { + String temp = sb.toString(); + sb.setLength(0); + int val = 0; + for (char c : temp.toCharArray()) { + val += Character.getNumericValue(c); + } + sb.append(val); + } + return Integer.parseInt(sb.toString()); } - String num = sb.toString(); - while (k-- > 0) { - int sum = 0; - for (char c : num.toCharArray()) { - sum += Character.getNumericValue(c); - } - num = String.valueOf(sum); - } - return Integer.parseInt(num); - } } From e1dcfeaa1f25a8985962ec1f2544cf93fef7823d Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 3 Sep 2024 18:14:48 -0700 Subject: [PATCH 056/182] Create Walking Robot Simulation.java --- Medium/Walking Robot Simulation.java | 41 ++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Medium/Walking Robot Simulation.java diff --git a/Medium/Walking Robot Simulation.java b/Medium/Walking Robot Simulation.java new file mode 100644 index 00000000..bfc2784f --- /dev/null +++ b/Medium/Walking Robot Simulation.java @@ -0,0 +1,41 @@ +class Solution { + private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + private static final int HASH_MULTIPLIER = 60001; + + public int robotSim(int[] commands, int[][] obstacles) { + Set obstacleSet = new HashSet<>(); + for (int[] obstacle : obstacles) { + obstacleSet.add(hashCoordinates(obstacle[0], obstacle[1])); + } + int maxDistance = 0; + int currentDirection = 0; + int x = 0; + int y = 0; + for (int command : commands) { + if (command == -1) { + currentDirection = (currentDirection + 1) % 4; + continue; + } + if (command == -2) { + currentDirection = (currentDirection + 3) % 4; + continue; + } + int[] direction = DIRECTIONS[currentDirection]; + for (int i = 0; i < command; i++) { + int nextX = x + direction[0]; + int nextY = y + direction[1]; + if (obstacleSet.contains(hashCoordinates(nextX, nextY))) { + break; + } + x = nextX; + y = nextY; + } + maxDistance = Math.max(maxDistance, x * x + y * y); + } + return maxDistance; + } + + private static int hashCoordinates(int x, int y) { + return x + HASH_MULTIPLIER * y; + } +} From 0dd2c3bc6121d307e42223df055bc7d0e1d01bb7 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 4 Sep 2024 08:11:01 -0700 Subject: [PATCH 057/182] Create Diagonal Traverse II.java --- Medium/Diagonal Traverse II.java | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Medium/Diagonal Traverse II.java diff --git a/Medium/Diagonal Traverse II.java b/Medium/Diagonal Traverse II.java new file mode 100644 index 00000000..dabfc5ef --- /dev/null +++ b/Medium/Diagonal Traverse II.java @@ -0,0 +1,26 @@ +class Solution { + public int[] findDiagonalOrder(List> nums) { + Queue queue = new LinkedList<>(); + List result = new ArrayList<>(); + queue.add(new int[]{0, 0}); + while (!queue.isEmpty()) { + int[] removed = queue.remove(); + int x = removed[0]; + int y = removed[1]; + result.add(nums.get(x).get(y)); + // move down in column first + if (y == 0 && x + 1 < nums.size()) { + queue.add(new int[]{x + 1, y}); + } + // then pick the next element in row + if (y + 1 < nums.get(x).size()) { + queue.add(new int[]{x, y + 1}); + } + } + int[] ans = new int[result.size()]; + for (int i = 0; i < result.size(); i++) { + ans[i] = result.get(i); + } + return ans; + } +} From d214eff088dc8dc903de22e3f672e7ebce83f633 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 4 Sep 2024 08:25:09 -0700 Subject: [PATCH 058/182] Create Sum of All Subset XOR Totals.java --- Easy/Sum of All Subset XOR Totals.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Easy/Sum of All Subset XOR Totals.java diff --git a/Easy/Sum of All Subset XOR Totals.java b/Easy/Sum of All Subset XOR Totals.java new file mode 100644 index 00000000..fe82567a --- /dev/null +++ b/Easy/Sum of All Subset XOR Totals.java @@ -0,0 +1,14 @@ +class Solution { + public int subsetXORSum(int[] nums) { + return recurse(nums, 0, 0); + } + + private int recurse(int[] nums, int idx, int currXor) { + if (idx == nums.length) { + return currXor; + } + int performXor = recurse(nums, idx + 1, currXor ^ nums[idx]); + int notPerformXor = recurse(nums, idx + 1, currXor); + return performXor + notPerformXor; + } +} From a13c10b8f5ed445486e4668b5981486212488422 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 4 Sep 2024 09:52:37 -0700 Subject: [PATCH 059/182] Update Lowest Common Ancestor of a Binary Tree III.java --- ... Common Ancestor of a Binary Tree III.java | 48 +++++++++---------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/Medium/Lowest Common Ancestor of a Binary Tree III.java b/Medium/Lowest Common Ancestor of a Binary Tree III.java index 26269fcc..098b0f86 100644 --- a/Medium/Lowest Common Ancestor of a Binary Tree III.java +++ b/Medium/Lowest Common Ancestor of a Binary Tree III.java @@ -9,30 +9,30 @@ class Node { */ class Solution { - public Node lowestCommonAncestor(Node p, Node q) { - int pDepth = getDepth(p); - int qDepth = getDepth(q); - while (pDepth > qDepth) { - pDepth--; - p = p.parent; + public Node lowestCommonAncestor(Node p, Node q) { + int pDepth = getDepth(p); + int qDepth = getDepth(q); + while (pDepth > qDepth) { + pDepth--; + p = p.parent; + } + while (qDepth > pDepth) { + qDepth--; + q = q.parent; + } + while (p != q) { + p = p.parent; + q = q.parent; + } + return p; } - while (pDepth < qDepth) { - qDepth--; - q = q.parent; - } - while (p != q) { - p = p.parent; - q = q.parent; - } - return p; - } - - private int getDepth(Node node) { - int depth = 0; - while (node != null) { - depth++; - node = node.parent; + + private int getDepth(Node node) { + int depth = 0; + while (node != null) { + depth++; + node = node.parent; + } + return depth; } - return depth; - } } From 0a57a4f4521e99065dd2c7cdeaad99732ef85b9a Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 4 Sep 2024 17:22:56 -0700 Subject: [PATCH 060/182] Update Find Missing Observations.java --- Medium/Find Missing Observations.java | 32 +++++++++++++++------------ 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/Medium/Find Missing Observations.java b/Medium/Find Missing Observations.java index 7b738edc..fe724572 100644 --- a/Medium/Find Missing Observations.java +++ b/Medium/Find Missing Observations.java @@ -1,17 +1,21 @@ class Solution { - public int[] missingRolls(int[] rolls, int mean, int n) { - int currSum = Arrays.stream(rolls).sum(); - int missingSum = mean * (n + rolls.length) - currSum; - if (missingSum > n * 6 || missingSum < n) { - return new int[]{}; + public int[] missingRolls(int[] rolls, int mean, int n) { + int m = rolls.length; + int sum = 0; + for (int roll : rolls) { + sum += roll; + } + int expectedSum = mean * (n + m); + int remaining = expectedSum - sum; + if (remaining > 6 * n || remaining < n) { + return new int[]{}; + } + int[] result = new int[n]; + Arrays.fill(result, remaining / n); + remaining = remaining % n; + for (int i = 0; i < remaining; i++) { + result[i]++; + } + return result; } - int[] ans = new int[n]; - int part = missingSum / n; - int remainder = missingSum % n; - Arrays.fill(ans, part); - for (int i = 0; i < remainder; i++) { - ans[i]++; - } - return ans; - } } From 4137cce7391bef40a4fff4400dcf863c0115596f Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 4 Sep 2024 17:30:29 -0700 Subject: [PATCH 061/182] Update Buildings With an Ocean View.java --- Medium/Buildings With an Ocean View.java | 25 ++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/Medium/Buildings With an Ocean View.java b/Medium/Buildings With an Ocean View.java index b9735daa..6d52576e 100644 --- a/Medium/Buildings With an Ocean View.java +++ b/Medium/Buildings With an Ocean View.java @@ -1,13 +1,18 @@ class Solution { - public int[] findBuildings(int[] heights) { - List oceanViewBuildings = new ArrayList<>(); - int maxHeight = 0; - for (int i = heights.length - 1; i >= 0; i--) { - if (heights[i] > maxHeight) { - oceanViewBuildings.add(i); - } - maxHeight = Math.max(maxHeight, heights[i]); + public int[] findBuildings(int[] heights) { + List result = new ArrayList<>(); + int maxHeight = -1; + for (int i = heights.length - 1; i >= 0; i--) { + if (heights[i] > maxHeight) { + result.add(i); + } + maxHeight = Math.max(maxHeight, heights[i]); + } + int[] ans = new int[result.size()]; + Collections.reverse(result); + for (int i = 0; i < result.size(); i++) { + ans[i] = result.get(i); + } + return ans; } - return oceanViewBuildings.stream().sorted().mapToInt(Integer::valueOf).toArray(); - } } From 88ca3f65bd13f7af1d3836e56dc7fed521893d80 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 6 Sep 2024 07:05:29 -0700 Subject: [PATCH 062/182] Create Delete Nodes From Linked List Present in Array.java --- ...des From Linked List Present in Array.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Medium/Delete Nodes From Linked List Present in Array.java diff --git a/Medium/Delete Nodes From Linked List Present in Array.java b/Medium/Delete Nodes From Linked List Present in Array.java new file mode 100644 index 00000000..ff184902 --- /dev/null +++ b/Medium/Delete Nodes From Linked List Present in Array.java @@ -0,0 +1,31 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode modifiedList(int[] nums, ListNode head) { + Set set = new HashSet<>(); + for (int num : nums) { + set.add(num); + } + while (head != null && set.contains(head.val)) { + head = head.next; + } + ListNode newHead = head; + ListNode curr = head; + while (curr.next != null) { + if (set.contains(curr.next.val)) { + curr.next = curr.next.next; + } else { + curr = curr.next; + } + } + return newHead; + } +} From fb8b21f8a92f46d47a505e1e05a2a66429afda05 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 6 Sep 2024 07:42:55 -0700 Subject: [PATCH 063/182] Create Making A Large Island.java --- Hard/Making A Large Island.java | 68 +++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Hard/Making A Large Island.java diff --git a/Hard/Making A Large Island.java b/Hard/Making A Large Island.java new file mode 100644 index 00000000..d1026bd7 --- /dev/null +++ b/Hard/Making A Large Island.java @@ -0,0 +1,68 @@ +class Solution { + + private static final int[][] DIRS = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; + + public int largestIsland(int[][] grid) { + int n = grid.length; + int tag = 2; + int result = 0; + Map tagToAreaMapping = new HashMap<>(); + // Calculate area without changing 0 to 1 & tag each island for future reference + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + tagToAreaMapping.put(tag, dfs(grid, i, j, tag)); + result = Math.max(result, tagToAreaMapping.get(tag)); + tag++; + } + } + } + // Now start changing each 0 to 1 & add the area of all connected islands by referencing their tags + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 0) { + Set visited = new HashSet<>(); + int currArea = 1; + List moves = getMoves(i, j, n); + for (int[] move : moves) { + int x = move[0]; + int y = move[1]; + int currTag = grid[x][y]; + if (currTag > 1 && visited.add(currTag)) { + currArea += tagToAreaMapping.get(currTag); + } + } + result = Math.max(result, currArea); + } + } + } + return result; + } + + private int dfs(int[][] grid, int x, int y, int tag) { + int area = 1; + int n = grid.length; + grid[x][y] = tag; + List moves = getMoves(x, y, n); + for (int[] move : moves) { + int i = move[0]; + int j = move[1]; + if (grid[i][j] == 1) { + area += dfs(grid, i, j, tag); + } + } + return area; + } + + private List getMoves(int x, int y, int n) { + List moves = new ArrayList<>(); + for (int[] dir : DIRS) { + int newX = x + dir[0]; + int newY = y + dir[1]; + if (newX >= 0 && newX < n && newY >= 0 && newY < n) { + moves.add(new int[]{newX, newY}); + } + } + return moves; + } +} From 5028a9e5f102e02eaa78f86313087d21181fb841 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 6 Sep 2024 08:43:03 -0700 Subject: [PATCH 064/182] Create Max Consecutive Ones III.java --- Medium/Max Consecutive Ones III.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Medium/Max Consecutive Ones III.java diff --git a/Medium/Max Consecutive Ones III.java b/Medium/Max Consecutive Ones III.java new file mode 100644 index 00000000..cec14a87 --- /dev/null +++ b/Medium/Max Consecutive Ones III.java @@ -0,0 +1,23 @@ +class Solution { + public int longestOnes(int[] nums, int k) { + int start = 0; + int end = 0; + int flipped = 0; + int n = nums.length; + int max = 0; + while (end < nums.length) { + if (nums[end] == 0) { + flipped++; + } + end++; + while (start < end && flipped > k) { + if (nums[start] == 0) { + flipped--; + } + start++; + } + max = Math.max(max, end - start); + } + return max; + } +} From b54f9b0024f91c558910d8724bc601bd3400cf4c Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 6 Sep 2024 09:03:57 -0700 Subject: [PATCH 065/182] Update Valid Number.java --- Hard/Valid Number.java | 106 +++++++++++++++-------------------------- 1 file changed, 39 insertions(+), 67 deletions(-) diff --git a/Hard/Valid Number.java b/Hard/Valid Number.java index d9a68285..1cdebfa8 100644 --- a/Hard/Valid Number.java +++ b/Hard/Valid Number.java @@ -1,90 +1,62 @@ class Solution { - public boolean isNumber(String s) { - s = s.trim(); - char[] ch = s.toCharArray(); + public boolean isNumber(String s) { int idx = 0; - int n = ch.length; - boolean signFound = false; - boolean decimalFound = false; - boolean numFound = false; - boolean expoFound = false; - + boolean isDecimal = false; + boolean isDigit = false; + boolean digitsBeforeDecimal = false; + boolean digitsAfterDecimal = false; + int n = s.length(); + if (s.charAt(idx) == '-' || s.charAt(idx) == '+') { + idx++; + } while (idx < n) { - if (ch[idx] == '+' || ch[idx] == '-') { - if (numFound || signFound || decimalFound) { + if (s.charAt(idx) == '.') { + if (isDecimal) { return false; } - - signFound = true; - } - else if (ch[idx] == '.') { - if (decimalFound) { + isDecimal = true; + } else if (s.charAt(idx) == 'e' || s.charAt(idx) == 'E') { + if (!isDigit) { return false; } - decimalFound = true; - } - else if (Character.isLetter(ch[idx])) { - if (ch[idx] == 'e') { - if (!numFound) { - return false; - } - idx++; - expoFound = true; - break; - } - else { + boolean valid = isValidExponent(s, idx + 1); + if (!valid) { return false; } - } - else if (Character.isDigit(ch[idx])) { - numFound = true; - } - else if (ch[idx] == ' ') { - if (numFound || signFound || decimalFound) { - return false; + break; + } else if (Character.isDigit(s.charAt(idx))) { + if (isDecimal) { + digitsAfterDecimal = true; + } else { + digitsBeforeDecimal = true; } + isDigit = true; + } else { + return false; } - idx++; } - - if (!numFound) { - return false; + if (isDecimal) { + return digitsBeforeDecimal || digitsAfterDecimal; } + return isDigit; + } - if (expoFound && idx == n) { + private boolean isValidExponent(String s, int idx) { + if (idx == s.length()) { return false; } - - signFound = false; - numFound = false; - while (idx < n) { - if (ch[idx] == '.') { - return false; - } - else if (ch[idx] == '+' || ch[idx] == '-') { - if (signFound) { - return false; - } - if (numFound) { - return false; - } - signFound = true; - } - else if (Character.isDigit(ch[idx])) { - numFound = true; - } - else { + if (s.charAt(idx) == '-' || s.charAt(idx) == '+') { + idx++; + } + boolean digitFound = false; + while (idx < s.length()) { + if (!Character.isDigit(s.charAt(idx))) { return false; } - + digitFound = true; idx++; } - - if (expoFound && !numFound) { - return false; - } - - return true; + return digitFound; } } From 6a4ac34e8808f4eff237a7d4d4a95eb79d8e3a47 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 7 Sep 2024 14:32:30 -0700 Subject: [PATCH 066/182] Update Exclusive Time of Functions.java --- Medium/Exclusive Time of Functions.java | 50 +++++++++++-------------- 1 file changed, 21 insertions(+), 29 deletions(-) diff --git a/Medium/Exclusive Time of Functions.java b/Medium/Exclusive Time of Functions.java index 8212e0c0..cd85e84c 100644 --- a/Medium/Exclusive Time of Functions.java +++ b/Medium/Exclusive Time of Functions.java @@ -1,33 +1,25 @@ class Solution { - public int[] exclusiveTime(int n, List logs) { - int[] result = new int[n]; - Stack stack = new Stack<>(); - for (String log : logs) { - Log currentLog = new Log(log); - if (currentLog.isStart) { - stack.push(currentLog); - } else { - Log topLog = stack.pop(); - result[topLog.id] += currentLog.time - topLog.time + 1 - topLog.overLappingTime; - if (!stack.isEmpty()) { - stack.peek().overLappingTime += currentLog.time - topLog.time + 1; + public int[] exclusiveTime(int n, List logs) { + Stack stack = new Stack<>(); + int[] result = new int[n]; + int lastTimestamp = 0; + for (String log : logs) { + String[] split = log.split(":"); + int id = Integer.parseInt(split[0]); + int timestamp = Integer.parseInt(split[2]); + if (split[1].equals("start")) { + // We consider timestamp as part of current computation + if (!stack.isEmpty()) { + result[stack.peek()] += timestamp - lastTimestamp; + } + stack.push(id); + lastTimestamp = timestamp; + } else { + // We consider timestamp as part of previous computation + result[stack.pop()] += timestamp - lastTimestamp + 1; + lastTimestamp = timestamp + 1; + } } - } + return result; } - return result; - } - - private static class Log { - public int id; - public boolean isStart; - public int time; - public int overLappingTime; - - public Log(String log) { - String[] split = log.split(":"); - this.id = Integer.parseInt(split[0]); - this.isStart = split[1].equals("start"); - this.time = Integer.parseInt(split[2]); - } - } } From 6f1feb4a469506b8555f0b0ef8f0e367535874ee Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 7 Sep 2024 16:08:59 -0700 Subject: [PATCH 067/182] Update Product of Two Run-Length Encoded Arrays.java --- ...duct of Two Run-Length Encoded Arrays.java | 64 ++++++++----------- 1 file changed, 28 insertions(+), 36 deletions(-) diff --git a/Medium/Product of Two Run-Length Encoded Arrays.java b/Medium/Product of Two Run-Length Encoded Arrays.java index 7aa0b117..4aab9bc8 100644 --- a/Medium/Product of Two Run-Length Encoded Arrays.java +++ b/Medium/Product of Two Run-Length Encoded Arrays.java @@ -1,39 +1,31 @@ class Solution { - public List> findRLEArray(int[][] encoded1, int[][] encoded2) { - int idxOne = 0; - int idxTwo = 0; - List> result = new ArrayList<>(); - while (idxOne < encoded1.length && idxTwo < encoded2.length) { - int valueOne = encoded1[idxOne][0]; - int frequencyOne = 0; - while (idxOne < encoded1.length && encoded1[idxOne][0] == valueOne) { - frequencyOne += encoded1[idxOne++][1]; - } - idxOne--; - encoded1[idxOne][1] = frequencyOne; - int valueTwo = encoded2[idxTwo][0]; - int frequencyTwo = 0; - while (idxTwo < encoded2.length && encoded2[idxTwo][0] == valueTwo) { - frequencyTwo += encoded2[idxTwo++][1]; - } - idxTwo--; - encoded2[idxTwo][1] = frequencyTwo; - int prod = encoded1[idxOne][0] * encoded2[idxTwo][0]; - int frequency = Math.min(encoded1[idxOne][1], encoded2[idxTwo][1]); - if (result.size() > 0 && result.get(result.size() - 1).get(0) == prod) { - result.get(result.size() - 1).set(1, result.get(result.size() - 1).get(1) + frequency); - } else { - result.add(Arrays.asList(prod, frequency)); - } - encoded1[idxOne][1] -= frequency; - encoded2[idxTwo][1] -= frequency; - if (encoded1[idxOne][1] == 0) { - idxOne++; - } - if (encoded2[idxTwo][1] == 0) { - idxTwo++; - } + public List> findRLEArray(int[][] encoded1, int[][] encoded2) { + int idxOne = 0; + int idxTwo = 0; + List> result = new ArrayList<>(); + while (idxOne < encoded1.length && idxTwo < encoded2.length) { + int valOne = encoded1[idxOne][0]; + int valTwo = encoded2[idxTwo][0]; + int countOne = encoded1[idxOne][1]; + int countTwo = encoded2[idxTwo][1]; + int value = valOne * valTwo; + int count = Math.min(countOne, countTwo); + encoded1[idxOne][1] -= count; + encoded2[idxTwo][1] -= count; + if (encoded1[idxOne][1] == 0) { + idxOne++; + } + if (encoded2[idxTwo][1] == 0) { + idxTwo++; + } + if (!result.isEmpty() && result.get(result.size() - 1).get(0) == value) { + int existingCount = result.get(result.size() - 1).get(1); + int newCount = existingCount + count; + result.get(result.size() - 1).set(1, newCount); + } else { + result.add(Arrays.asList(value, count)); + } + } + return result; } - return result; - } } From f4665a1b78411741240061f2a93b5dc4a7999410 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 8 Sep 2024 11:56:52 -0700 Subject: [PATCH 068/182] Update Minimum Time to Collect All Apples in a Tree.java --- ... Time to Collect All Apples in a Tree.java | 44 ++++++++++--------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/Medium/Minimum Time to Collect All Apples in a Tree.java b/Medium/Minimum Time to Collect All Apples in a Tree.java index 24feb762..0e54b3ec 100644 --- a/Medium/Minimum Time to Collect All Apples in a Tree.java +++ b/Medium/Minimum Time to Collect All Apples in a Tree.java @@ -1,25 +1,27 @@ class Solution { - public int minTime(int n, int[][] edges, List hasApple) { - Map> tree = new HashMap<>(); - for (int[] edge : edges) { - tree.computeIfAbsent(edge[0], k -> new HashSet<>()).add(edge[1]); - tree.computeIfAbsent(edge[1], k -> new HashSet<>()).add(edge[0]); + public int minTime(int n, int[][] edges, List hasApple) { + Map> map = new HashMap<>(); + for (int[] edge : edges) { + map.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]); + map.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]); + } + return recurse(0, -1, map, hasApple); } - Set visited = new HashSet<>(); - return dfs(0, hasApple, visited, tree); - } - - private int dfs(int node, List hasApple, Set visited, Map> tree) { - visited.add(node); - int result = 0; - for (Integer child : tree.getOrDefault(node, new HashSet<>())) { - if (!visited.contains(child)) { - result += dfs(child, hasApple, visited, tree); - } + + private int recurse(int node, int parent, Map> graph, List hasApple) { + if (!graph.containsKey(node)) { + return 0; + } + int time = 0; + for (Integer conn: graph.get(node)) { + if (conn == parent) { + continue; + } + int connTime = recurse(conn, node, graph, hasApple); + if (connTime > 0 || hasApple.get(conn)) { + time += connTime + 2; + } + } + return time; } - if ((result > 0 || hasApple.get(node)) && node != 0) { - result += 2; - } - return result; - } } From 56554ae1b5bbc84477ce970a0e70578697429c5b Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 8 Sep 2024 12:08:47 -0700 Subject: [PATCH 069/182] Update Meeting Scheduler.java --- Medium/Meeting Scheduler.java | 37 ++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/Medium/Meeting Scheduler.java b/Medium/Meeting Scheduler.java index d5bf6b16..aeb5d8e9 100644 --- a/Medium/Meeting Scheduler.java +++ b/Medium/Meeting Scheduler.java @@ -1,21 +1,22 @@ class Solution { - public List minAvailableDuration(int[][] slots1, int[][] slots2, int duration) { - Arrays.sort(slots1, Comparator.comparingInt(o -> o[0])); - Arrays.sort(slots2, Comparator.comparingInt(o -> o[0])); - int idxOne = 0; - int idxTwo = 0; - while (idxOne < slots1.length && idxTwo < slots2.length) { - int maxStart = Math.max(slots1[idxOne][0], slots2[idxTwo][0]); - int minEnd = Math.min(slots1[idxOne][1], slots2[idxTwo][1]); - if (minEnd - maxStart >= duration) { - return Arrays.asList(maxStart, maxStart + duration); - } - if (slots1[idxOne][1] > slots2[idxTwo][1]) { - idxTwo++; - } else { - idxOne++; - } + public List minAvailableDuration(int[][] slots1, int[][] slots2, int duration) { + Arrays.sort(slots1, Comparator.comparingInt(o -> o[0])); + Arrays.sort(slots2, Comparator.comparingInt(o -> o[0])); + int idxOne = 0; + int idxTwo = 0; + while (idxOne < slots1.length && idxTwo < slots2.length) { + int maxStart = Math.max(slots1[idxOne][0], slots2[idxTwo][0]); + int minEnd = Math.min(slots1[idxOne][1], slots2[idxTwo][1]); + if (minEnd - maxStart >= duration) { + return List.of(maxStart, maxStart + duration); + } + if (minEnd == slots1[idxOne][1]) { + idxOne++; + } + if (minEnd == slots2[idxTwo][1]) { + idxTwo++; + } + } + return Collections.emptyList(); } - return new ArrayList<>(); - } } From 3ba562353c17ddfcc35c87757145c3bfd5a21558 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 8 Sep 2024 15:49:02 -0700 Subject: [PATCH 070/182] Create Alternating Groups I.java --- Easy/Alternating Groups I.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Easy/Alternating Groups I.java diff --git a/Easy/Alternating Groups I.java b/Easy/Alternating Groups I.java new file mode 100644 index 00000000..9730d5ea --- /dev/null +++ b/Easy/Alternating Groups I.java @@ -0,0 +1,18 @@ +class Solution { + public int numberOfAlternatingGroups(int[] colors) { + int count = 0; + int n = colors.length; + for (int i = 0; i < n - 2; i++) { + if (colors[i + 1] != colors[i] && colors[i + 1] != colors[i + 2]) { + count++; + } + } + if (colors[n - 2] != colors[n - 1] && colors[n - 2] == colors[0]) { + count++; + } + if (colors[n - 1] != colors[0] && colors[n - 1] == colors[1]) { + count++; + } + return count; + } +} From bd41f382ab668b5de9e605ed0fc4d75d4843e183 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 8 Sep 2024 15:54:49 -0700 Subject: [PATCH 071/182] Update Base 7.java --- Easy/Base 7.java | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/Easy/Base 7.java b/Easy/Base 7.java index 210d6c39..8da9a029 100644 --- a/Easy/Base 7.java +++ b/Easy/Base 7.java @@ -1,16 +1,15 @@ class Solution { - public String convertToBase7(int num) { - StringBuilder sb = new StringBuilder(); - char sign = num < 0 ? '-' : ' '; - num = Math.abs(num); - while (num > 0) { - sb.append(num % 7); - num /= 7; + public String convertToBase7(int num) { + StringBuilder sb = new StringBuilder(); + boolean isNegative = num < 0; + num = Math.abs(num); + while (num > 0) { + sb.append(num % 7); + num /= 7; + } + if (isNegative) { + sb.append('-'); + } + return sb.isEmpty() ? "0" : sb.reverse().toString(); } - String representation = sb.length() == 0 ? "0" : sb.reverse().toString(); - if (sign == '-') { - return sign + representation; - } - return representation; - } } From 238c35b45c0b2d09e497e165945b749b9a2d651c Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 8 Sep 2024 16:17:19 -0700 Subject: [PATCH 072/182] Create Faulty Sensor.java --- Easy/Faulty Sensor.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Easy/Faulty Sensor.java diff --git a/Easy/Faulty Sensor.java b/Easy/Faulty Sensor.java new file mode 100644 index 00000000..dabed6c0 --- /dev/null +++ b/Easy/Faulty Sensor.java @@ -0,0 +1,13 @@ +class Solution { + public int badSensor(int[] sensor1, int[] sensor2) { + int idx = 0; + int n = sensor1.length; + while (idx < n && sensor1[idx] == sensor2[idx]) { + idx++; + } + while (idx + 1 < n && sensor1[idx] == sensor2[idx + 1] && sensor1[idx + 1] == sensor2[idx]) { + idx++; + } + return idx >= n - 1 ? -1 : sensor1[idx] == sensor2[idx + 1] ? 1 : 2; + } +} From fe13960db86695574eb4afdbd214fad5bbc9acba Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 9 Sep 2024 08:38:15 -0700 Subject: [PATCH 073/182] Update Palindrome Partitioning.java --- Medium/Palindrome Partitioning.java | 40 ++++++++++++++++------------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/Medium/Palindrome Partitioning.java b/Medium/Palindrome Partitioning.java index 1171f009..de89ed16 100644 --- a/Medium/Palindrome Partitioning.java +++ b/Medium/Palindrome Partitioning.java @@ -1,27 +1,31 @@ class Solution { - public List> partition(String a) { - List> ans = new ArrayList<>(); - helper(ans, new ArrayList(), a, 0); - return ans; + public List> partition(String s) { + List> result = new ArrayList<>(); + backtrack(result, new ArrayList<>(), s, 0); + return result; } - - private void helper(List> ans, List temp, String a, int idx) { - if (idx == a.length()) { - ans.add(new ArrayList<>(temp)); + + private void backtrack(List> result, List currentList, + String s, int idx) { + if (idx == s.length()) { + result.add(new ArrayList<>(currentList)); return; } - for (int i=idx; i Date: Mon, 9 Sep 2024 08:48:50 -0700 Subject: [PATCH 074/182] Update Largest BST Subtree.java --- Medium/Largest BST Subtree.java | 52 ++++++++++++++++----------------- 1 file changed, 25 insertions(+), 27 deletions(-) diff --git a/Medium/Largest BST Subtree.java b/Medium/Largest BST Subtree.java index 45c83c6f..18ddfeaf 100644 --- a/Medium/Largest BST Subtree.java +++ b/Medium/Largest BST Subtree.java @@ -4,43 +4,41 @@ * int val; * TreeNode left; * TreeNode right; - * TreeNode(int x) { val = x; } + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } * } */ class Solution { public int largestBSTSubtree(TreeNode root) { - return largestBSTSubtreeHelper(root); - } - - private int largestBSTSubtreeHelper(TreeNode root) { - if (isBST(root)) { - return getNodeCount(root); - } - - return Math.max(-1, Math.max(largestBSTSubtreeHelper(root.left), largestBSTSubtreeHelper(root.right))); - } - - private boolean isBST(TreeNode root) { - return isBSTHelper(root, Integer.MAX_VALUE, Integer.MIN_VALUE); - } - - private boolean isBSTHelper(TreeNode root, int max, int min) { if (root == null) { - return true; + return 0; } - - if (root.val >= max || root.val <= min) { - return false; + int[] isBstResult = isBst(root, Integer.MIN_VALUE, Integer.MAX_VALUE); + if (isBstResult[0] == 1) { + return isBstResult[1]; } - - return isBSTHelper(root.left, root.val, min) && isBSTHelper(root.right, max, root.val); + return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right)); } - private int getNodeCount(TreeNode root) { + private int[] isBst(TreeNode root, int minValue, int maxValue) { if (root == null) { - return 0; + return new int[]{1, 0}; + } + int[] result = new int[2]; + if (!(root.val > minValue && root.val < maxValue)) { + return result; + } + int[] leftIsBst = isBst(root.left, minValue, root.val); + int[] rightIsBst = isBst(root.right, root.val, maxValue); + if (leftIsBst[0] == 1 && rightIsBst[0] == 1) { + result[0] = 1; + result[1] = 1 + leftIsBst[1] + rightIsBst[1]; } - - return 1 + getNodeCount(root.left) + getNodeCount(root.right); + return result; } } From ad5efe48ef18c914dfc941fd0e201aa6da5e0452 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 9 Sep 2024 09:03:48 -0700 Subject: [PATCH 075/182] Update One Edit Distance.java --- Medium/One Edit Distance.java | 59 ++++++++++++++--------------------- 1 file changed, 24 insertions(+), 35 deletions(-) diff --git a/Medium/One Edit Distance.java b/Medium/One Edit Distance.java index dc32eede..662a41d1 100644 --- a/Medium/One Edit Distance.java +++ b/Medium/One Edit Distance.java @@ -1,39 +1,28 @@ class Solution { - public boolean isOneEditDistance(String s, String t) { - int lengthDiff = Math.abs(s.length() - t.length()); - if (s.equals(t) || lengthDiff > 1) { - return false; - } - if (s.length() == 0 || t.length() == 0) { - return true; - } - int idxOne = 0; - int idxTwo = 0; - boolean changeDone = false; - while (idxOne < s.length() && idxTwo < t.length()) { - if (s.charAt(idxOne) == t.charAt(idxTwo)) { - idxOne++; - idxTwo++; - continue; - } - if (changeDone) { - return false; - } - if (lengthDiff != 0) { - if (s.length() > t.length()) { - idxOne++; - } else { - idxTwo++; + public boolean isOneEditDistance(String s, String t) { + int diff = Math.abs(s.length() - t.length()); + if (s.equals(t) || diff > 1) { + return false; } - } else { - idxOne++; - idxTwo++; - } - changeDone = true; - } - if (changeDone && (idxOne != s.length() || idxTwo != t.length())) { - return false; + int idx = 0; + while (idx < s.length() && idx < t.length()) { + if (s.charAt(idx) != t.charAt(idx)) { + // Replace character + if (s.substring(idx + 1).equals(t.substring(idx + 1))) { + return true; + } + // Delete 1 character from s + if (s.substring(idx + 1).equals(t.substring(idx))) { + return true; + } + // Delete 1 character from t + if (s.substring(idx).equals(t.substring(idx + 1))) { + return true; + } + return false; + } + idx++; + } + return true; } - return true; - } } From c968c70d73ca733683e6f14aaa54d4513531e7ca Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 9 Sep 2024 17:47:51 -0700 Subject: [PATCH 076/182] Create Spiral Matrix IV.java --- Medium/Spiral Matrix IV.java | 45 ++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Medium/Spiral Matrix IV.java diff --git a/Medium/Spiral Matrix IV.java b/Medium/Spiral Matrix IV.java new file mode 100644 index 00000000..5136b493 --- /dev/null +++ b/Medium/Spiral Matrix IV.java @@ -0,0 +1,45 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public int[][] spiralMatrix(int m, int n, ListNode head) { + int[][] result = new int[m][n]; + for (int i = 0; i < m; i++) { + Arrays.fill(result[i], -1); + } + int topRow = 0; + int bottomRow = m - 1; + int leftColumn = 0; + int rightColumn = n - 1; + while (head != null) { + for (int col = leftColumn; col <= rightColumn && head != null; col++) { + result[topRow][col] = head.val; + head = head.next; + } + topRow++; + for (int row = topRow; row <= bottomRow && head != null; row++) { + result[row][rightColumn] = head.val; + head = head.next; + } + rightColumn--; + for (int col = rightColumn; col >= leftColumn && head != null; col--) { + result[bottomRow][col] = head.val; + head = head.next; + } + bottomRow--; + for (int row = bottomRow; row >= topRow && head != null; row--) { + result[row][leftColumn] = head.val; + head = head.next; + } + leftColumn++; + } + return result; + } +} From aebf179f19b50136a7d8e2738a5ced9de4a9a22f Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 10 Sep 2024 07:33:58 -0700 Subject: [PATCH 077/182] Update Shuffle String.java --- Easy/Shuffle String.java | 28 +++++++--------------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/Easy/Shuffle String.java b/Easy/Shuffle String.java index 10340050..f38bf1c2 100644 --- a/Easy/Shuffle String.java +++ b/Easy/Shuffle String.java @@ -1,24 +1,10 @@ class Solution { - public String restoreString(String s, int[] indices) { - char[] letters = s.toCharArray(); - for (int i = 0; i < indices.length; i++) { - while (indices[i] != i) { - swapLetter(letters, i, indices[i]); - swapIndex(indices, i, indices[i]); - } + public String restoreString(String s, int[] indices) { + char[] result = new char[s.length()]; + for (int i = 0; i < s.length(); i++) { + int index = indices[i]; + result[index] = s.charAt(i); + } + return String.valueOf(result); } - return String.valueOf(letters); - } - - private void swapLetter(char[] arr, int idxOne, int idxTwo) { - char temp = arr[idxOne]; - arr[idxOne] = arr[idxTwo]; - arr[idxTwo] = temp; - } - - private void swapIndex(int[] arr, int idxOne, int idxTwo) { - int temp = arr[idxOne]; - arr[idxOne] = arr[idxTwo]; - arr[idxTwo] = temp; - } } From 94209cf76f7ab258a49eebe18c04e38ad76cf345 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 10 Sep 2024 07:34:47 -0700 Subject: [PATCH 078/182] Update Minimum Time Visiting All Points.java --- Easy/Minimum Time Visiting All Points.java | 24 +++++++++++++--------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/Easy/Minimum Time Visiting All Points.java b/Easy/Minimum Time Visiting All Points.java index 774ac97c..ee1a85b1 100644 --- a/Easy/Minimum Time Visiting All Points.java +++ b/Easy/Minimum Time Visiting All Points.java @@ -1,13 +1,17 @@ class Solution { - public int minTimeToVisitAllPoints(int[][] points) { - int time = 0; - for (int i = 1; i < points.length; i++) { - int[] prevPoint = points[i - 1]; - int[] currPoint = points[i]; - time += Math.max( - Math.abs(prevPoint[0] - currPoint[0]), Math.abs(prevPoint[1] - currPoint[1]) - ); + public int minTimeToVisitAllPoints(int[][] points) { + int time = 0; + int idx = 0; + while (idx < points.length - 1) { + time += calculateTime(points[idx], points[idx + 1]); + idx++; + } + return time; + } + + private static int calculateTime(int[] p1, int[] p2) { + int x = Math.abs(p1[0] - p2[0]); + int y = Math.abs(p1[1] - p2[1]); + return Math.max(x, y); } - return time; - } } From c8457b18c67c6944a3fd05e0266e5b9e2f66091c Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 10 Sep 2024 11:02:34 -0700 Subject: [PATCH 079/182] Update Reverse Vowels of a String.java --- Easy/Reverse Vowels of a String.java | 42 ++++++++++++++-------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/Easy/Reverse Vowels of a String.java b/Easy/Reverse Vowels of a String.java index c1ea0294..ea10d13c 100644 --- a/Easy/Reverse Vowels of a String.java +++ b/Easy/Reverse Vowels of a String.java @@ -1,24 +1,24 @@ class Solution { - public String reverseVowels(String s) { - int left = 0; - int right = s.length() - 1; - String vowels = "aeiouAEIOU"; - char[] chars = s.toCharArray(); - while (left < right) { - int vowelIndexLeft = vowels.indexOf(chars[left]); - int vowelIndexRight = vowels.indexOf(chars[right]); - if (vowelIndexLeft != -1 && vowelIndexRight != -1) { - char temp = chars[left]; - chars[left++] = chars[right]; - chars[right--] = temp; - } - else if (vowelIndexRight == -1) { - right--; - } - else { - left++; - } + + private static final Set VOWELS = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'); + + public String reverseVowels(String s) { + int left = 0; + int right = s.length() - 1; + char[] chars = s.toCharArray(); + while (left <= right) { + if (VOWELS.contains(chars[left]) && VOWELS.contains(chars[right])) { + char temp = chars[left]; + chars[left] = chars[right]; + chars[right] = temp; + left++; + right--; + } else if (!VOWELS.contains(chars[left])) { + left++; + } else if (!VOWELS.contains(chars[right])) { + right--; + } + } + return String.valueOf(chars); } - return String.valueOf(chars); - } } From f029595755aa34a81caae72c31ad1a629cfd9fda Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 12 Sep 2024 08:30:42 -0700 Subject: [PATCH 080/182] Update Maximum Size Subarray Sum Equals k.java --- .../Maximum Size Subarray Sum Equals k.java | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/Medium/Maximum Size Subarray Sum Equals k.java b/Medium/Maximum Size Subarray Sum Equals k.java index 97d37973..dce7007a 100644 --- a/Medium/Maximum Size Subarray Sum Equals k.java +++ b/Medium/Maximum Size Subarray Sum Equals k.java @@ -1,18 +1,17 @@ class Solution { - public int maxSubArrayLen(int[] nums, int k) { - Map map = new HashMap<>(); - int res = 0; - int sum = 0; - for (int i = 0; i < nums.length; i++) { - sum += nums[i]; - if (sum == k) { - res = i + 1; - } - else if (map.containsKey(sum - k)) { - res = Math.max(res, i - map.get(sum - k)); - } - map.putIfAbsent(sum, i); + public int maxSubArrayLen(int[] nums, int k) { + Map map = new HashMap<>(); + int prefixSum = 0; + int max = 0; + for (int i = 0; i < nums.length; i++) { + prefixSum += nums[i]; + if (prefixSum == k) { + max = i + 1; + } else if (map.containsKey(prefixSum - k)) { + max = Math.max(max, i - map.get(prefixSum - k)); + } + map.putIfAbsent(prefixSum, i); + } + return max; } - return res; - } } From 08ae7d68bdaea6e4d8a1141b5d2a7574e3c47cdb Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 13 Sep 2024 09:12:25 -0700 Subject: [PATCH 081/182] Create XOR Queries of a Subarray.java --- Medium/XOR Queries of a Subarray.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Medium/XOR Queries of a Subarray.java diff --git a/Medium/XOR Queries of a Subarray.java b/Medium/XOR Queries of a Subarray.java new file mode 100644 index 00000000..0bdfc9ca --- /dev/null +++ b/Medium/XOR Queries of a Subarray.java @@ -0,0 +1,24 @@ +class Solution { + public int[] xorQueries(int[] arr, int[][] queries) { + int n = arr.length; + int[] prefixXors = new int[n]; + int xor = 0; + for (int i = 0; i < n; i++) { + xor = xor ^ arr[i]; + prefixXors[i] = xor; + } + n = queries.length; + int[] result = new int[n]; + for (int i = 0; i < n; i++) { + int[] query = queries[i]; + int left = query[0]; + int right = query[1]; + int xorResult = prefixXors[right]; + if (left != 0) { + xorResult = xorResult ^ prefixXors[left - 1]; + } + result[i] = xorResult; + } + return result; + } +} From ec93192b5b6d0d395679043110bef3b3df155d43 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 14 Sep 2024 10:33:16 -0700 Subject: [PATCH 082/182] Create Longest Subarray With Maximum Bitwise AND.java --- ...est Subarray With Maximum Bitwise AND.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Medium/Longest Subarray With Maximum Bitwise AND.java diff --git a/Medium/Longest Subarray With Maximum Bitwise AND.java b/Medium/Longest Subarray With Maximum Bitwise AND.java new file mode 100644 index 00000000..63c1ca55 --- /dev/null +++ b/Medium/Longest Subarray With Maximum Bitwise AND.java @@ -0,0 +1,20 @@ +class Solution { + public int longestSubarray(int[] nums) { + int result = 0; + int max = 0; + int count = 0; + for (int num : nums) { + if (max < num) { + max = num; + result = count = 0; + } + if (max == num) { + count++; + } else { + count = 0; + } + result = Math.max(result, count); + } + return result; + } +} From 4e3321b796755556dbcb22ca263ca558b2fbf626 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 15 Sep 2024 08:56:53 -0700 Subject: [PATCH 083/182] Create Find the Longest Substring Containing Vowels in Even Counts.java --- ...ring Containing Vowels in Even Counts.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Medium/Find the Longest Substring Containing Vowels in Even Counts.java diff --git a/Medium/Find the Longest Substring Containing Vowels in Even Counts.java b/Medium/Find the Longest Substring Containing Vowels in Even Counts.java new file mode 100644 index 00000000..66e33ef9 --- /dev/null +++ b/Medium/Find the Longest Substring Containing Vowels in Even Counts.java @@ -0,0 +1,22 @@ +class Solution { + public int findTheLongestSubstring(String s) { + int prefixXor = 0; + char[] frequency = new char[26]; + frequency['a' - 'a'] = 1; + frequency['e' - 'a'] = 2; + frequency['i' - 'a'] = 4; + frequency['o' - 'a'] = 8; + frequency['u' - 'a'] = 16; + int[] indexMap = new int[32]; + Arrays.fill(indexMap, -1); + int result = 0; + for (int i = 0; i < s.length(); i++) { + prefixXor ^= frequency[s.charAt(i) - 'a']; + if (indexMap[prefixXor] == -1 && prefixXor != 0) { + indexMap[prefixXor] = i; + } + result = Math.max(result, i - indexMap[prefixXor]); + } + return result; + } +} From f6c5fbcf06e1cc589de81072d148ee5933d7b72d Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 15 Sep 2024 21:30:25 -0700 Subject: [PATCH 084/182] Create Find Indices of Stable Mountains.java --- Easy/Find Indices of Stable Mountains.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Easy/Find Indices of Stable Mountains.java diff --git a/Easy/Find Indices of Stable Mountains.java b/Easy/Find Indices of Stable Mountains.java new file mode 100644 index 00000000..3e0fbd79 --- /dev/null +++ b/Easy/Find Indices of Stable Mountains.java @@ -0,0 +1,11 @@ +class Solution { + public List stableMountains(int[] height, int threshold) { + List result = new ArrayList<>(); + for (int i = 1; i < height.length; i++) { + if (height[i - 1] > threshold) { + result.add(i); + } + } + return result; + } +} From b10f51abbd6353d0469b733252bc3c00a0089f75 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 17 Sep 2024 06:34:56 -0700 Subject: [PATCH 085/182] Create Smallest Common Region.java --- Medium/Smallest Common Region.java | 32 ++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Medium/Smallest Common Region.java diff --git a/Medium/Smallest Common Region.java b/Medium/Smallest Common Region.java new file mode 100644 index 00000000..4d8ce894 --- /dev/null +++ b/Medium/Smallest Common Region.java @@ -0,0 +1,32 @@ +class Solution { + public String findSmallestRegion(List> regions, String region1, String region2) { + Map regionToParentMap = new HashMap<>(); + for (List region : regions) { + String parent = region.getFirst(); + for (int i = 1; i < region.size(); i++) { + regionToParentMap.put(region.get(i), parent); + } + } + List pathOne = trace(region1, regionToParentMap); + List pathTwo = trace(region2, regionToParentMap); + int idxOne = 0; + int idxTwo = 0; + while (idxOne < pathOne.size() && idxTwo < pathTwo.size() && pathOne.get(idxOne).equals(pathTwo.get(idxTwo))) { + idxOne++; + idxTwo++; + } + return pathOne.get(idxOne - 1); + } + + private List trace(String region, Map regionToParentMap) { + List path = new ArrayList<>(); + path.add(region); + while (regionToParentMap.containsKey(region)) { + String parent = regionToParentMap.get(region); + path.add(parent); + region = parent; + } + Collections.reverse(path); + return path; + } +} From 20d5bc1645f2112c99ab9296f8ae50b4542e946c Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 19 Sep 2024 06:32:29 -0700 Subject: [PATCH 086/182] Create Different Ways to Add Parentheses.java --- Medium/Different Ways to Add Parentheses.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Medium/Different Ways to Add Parentheses.java diff --git a/Medium/Different Ways to Add Parentheses.java b/Medium/Different Ways to Add Parentheses.java new file mode 100644 index 00000000..706fcf6c --- /dev/null +++ b/Medium/Different Ways to Add Parentheses.java @@ -0,0 +1,42 @@ +class Solution { + public List diffWaysToCompute(String expression) { + List result = new ArrayList<>(); + if (expression.length() == 0) { + return result; + } + if (expression.length() == 1) { + result.add(Integer.parseInt(expression)); + return result; + } + if (expression.length() == 2 && Character.isDigit(expression.charAt(0))) { + result.add(Integer.parseInt(expression)); + return result; + } + for (int i = 0; i < expression.length(); i++) { + char c = expression.charAt(i); + if (Character.isDigit(c)) { + continue; + } + List leftResult = diffWaysToCompute(expression.substring(0, i)); + List rightResult = diffWaysToCompute(expression.substring(i + 1)); + for (int leftVal : leftResult) { + for (int rightVal : rightResult) { + int value = 0; + switch(c) { + case '+': + value = leftVal + rightVal; + break; + case '-': + value = leftVal - rightVal; + break; + case '*': + value = leftVal * rightVal; + break; + } + result.add(value); + } + } + } + return result; + } +} From 33cbd03bdbc238fdfa2ba6949249af8d503c64f6 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 20 Sep 2024 06:58:05 -0700 Subject: [PATCH 087/182] Create Shortest Palindrome.java --- Hard/Shortest Palindrome.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Hard/Shortest Palindrome.java diff --git a/Hard/Shortest Palindrome.java b/Hard/Shortest Palindrome.java new file mode 100644 index 00000000..3ff38e40 --- /dev/null +++ b/Hard/Shortest Palindrome.java @@ -0,0 +1,23 @@ +class Solution { + public String shortestPalindrome(String s) { + int n = s.length(); + if (n == 0) { + return s; + } + int left = 0; + for (int right = n - 1; right >= 0; right--) { + if (s.charAt(right) == s.charAt(left)) { + left++; + } + } + if (left == n) { + return s; + } + String nonPalindromeSuffix = s.substring(left); + StringBuilder reverseSuffix = new StringBuilder(nonPalindromeSuffix).reverse(); + return reverseSuffix + .append(shortestPalindrome(s.substring(0, left))) + .append(nonPalindromeSuffix) + .toString(); + } +} From c97bb9f4059847b67a7f53ca9fb9ee11ff385ab1 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 20 Sep 2024 17:44:54 -0700 Subject: [PATCH 088/182] Update Lexicographical Numbers.java --- Medium/Lexicographical Numbers.java | 31 ++++++++++++++--------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/Medium/Lexicographical Numbers.java b/Medium/Lexicographical Numbers.java index c0ccab5e..4476017b 100644 --- a/Medium/Lexicographical Numbers.java +++ b/Medium/Lexicographical Numbers.java @@ -1,19 +1,18 @@ class Solution { - public List lexicalOrder(int n) { - List result = new ArrayList<>(); - for (int i = 1; i < 10; i++) { - dfs(i, n, result); + public List lexicalOrder(int n) { + List result = new ArrayList<>(); + int curr = 1; + for (int i = 0; i < n; i++) { + result.add(curr); + if (curr * 10 <= n) { + curr *= 10; + } else { + while (curr % 10 == 9 || curr == n) { + curr /= 10; + } + curr++; + } + } + return result; } - return result; - } - - private void dfs(int curr, int n, List result) { - if (curr > n) { - return; - } - result.add(curr); - for (int i = 0; i < 10; i++) { - dfs(10 * curr + i, n, result); - } - } } From 68486f5d8e372ceeed62ff36dedbdfa95799ee11 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 21 Sep 2024 07:13:55 -0700 Subject: [PATCH 089/182] Update Sliding Window Median.java --- Hard/Sliding Window Median.java | 117 ++++++++++++++------------------ 1 file changed, 52 insertions(+), 65 deletions(-) diff --git a/Hard/Sliding Window Median.java b/Hard/Sliding Window Median.java index 944af371..e37c289d 100644 --- a/Hard/Sliding Window Median.java +++ b/Hard/Sliding Window Median.java @@ -1,72 +1,59 @@ class Solution { - List list; - double[] ans; - boolean isEven; - - public double[] medianSlidingWindow(int[] nums, int k) { - list = new ArrayList<>(); - ans = new double[nums.length - k + 1]; - isEven = k % 2 == 0; - - for (int i=0; i list.get(list.size() - 1)) { - return list.size(); - } - - int start = 0; - int end = list.size(); - - while (start < end) { - int mid = (start + end) / 2; - - if (list.get(mid) < num) { - start = mid + 1; - } - else { - end = mid; + public double[] medianSlidingWindow(int[] nums, int windowSize) { + double[] medians = new double[nums.length - windowSize + 1]; + Map delayedRemovals = new HashMap<>(); + PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + PriorityQueue minHeap = new PriorityQueue<>(); + int currentIndex = 0; + while (currentIndex < windowSize) { + maxHeap.add(nums[currentIndex++]); + } + for (int j = 0; j < windowSize / 2; j++) { + minHeap.add(maxHeap.poll()); + } + int medianIndex = 0; + while (true) { + if (windowSize % 2 == 1) { + medians[medianIndex++] = maxHeap.peek(); + } else { + medians[medianIndex++] = ((double) maxHeap.peek() + (double) minHeap.peek()) / 2.0; } - } - - return end; - } - - private void removeElement(int num) { - for (int i=0; i= nums.length) { break; } + int outNum = nums[currentIndex - windowSize]; + int inNum = nums[currentIndex++]; + int balance = 0; + // Handle outgoing number + balance += (outNum <= maxHeap.peek() ? -1 : 1); + delayedRemovals.put(outNum, delayedRemovals.getOrDefault(outNum, 0) + 1); + // Handle incoming number + if (!maxHeap.isEmpty() && inNum <= maxHeap.peek()) { + balance++; + maxHeap.add(inNum); + } else { + balance--; + minHeap.add(inNum); + } + // Rebalance heaps + if (balance < 0) { + maxHeap.add(minHeap.poll()); + balance++; + } + if (balance > 0) { + minHeap.add(maxHeap.poll()); + balance--; + } + // Remove invalid numbers from the top of the heaps + while (delayedRemovals.getOrDefault(maxHeap.peek(), 0) > 0) { + delayedRemovals.put(maxHeap.peek(), delayedRemovals.get(maxHeap.peek()) - 1); + maxHeap.poll(); + } + while (!minHeap.isEmpty() && delayedRemovals.getOrDefault(minHeap.peek(), 0) > 0) { + delayedRemovals.put(minHeap.peek(), delayedRemovals.get(minHeap.peek()) - 1); + minHeap.poll(); + } } - } - - private double getMedian() { - if (isEven) { - return (double) (list.get(list.size()/2) + list.get(list.size()/2 - 1)) / 2; - } - else { - return (double) list.get(list.size()/2); - } + return medians; } } From fe09ade65cbd4a3b05410a7924619253f79d5358 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 21 Sep 2024 07:30:10 -0700 Subject: [PATCH 090/182] Create Most Beautiful Item for Each Query.java --- Medium/Most Beautiful Item for Each Query.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Medium/Most Beautiful Item for Each Query.java diff --git a/Medium/Most Beautiful Item for Each Query.java b/Medium/Most Beautiful Item for Each Query.java new file mode 100644 index 00000000..5d2f75db --- /dev/null +++ b/Medium/Most Beautiful Item for Each Query.java @@ -0,0 +1,17 @@ +class Solution { + public int[] maximumBeauty(int[][] items, int[] queries) { + Arrays.sort(items, (a, b) -> (a[0] - b[0])); + TreeMap map = new TreeMap<>(); + map.put(0, 0); + int currMax = 0; + for (int[] item : items) { + currMax = Math.max(currMax, item[1]); + map.put(item[0], currMax); + } + int[] result = new int[queries.length]; + for (int i = 0; i < queries.length; i++) { + result[i] = map.floorEntry(queries[i]).getValue(); + } + return result; + } +} From 049b2483f54ff74ed04e872c54e272529c99ca8d Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 22 Sep 2024 08:29:37 -0700 Subject: [PATCH 091/182] Update Longest Word With All Prefixes.java --- Medium/Longest Word With All Prefixes.java | 94 ++++++++++++---------- 1 file changed, 50 insertions(+), 44 deletions(-) diff --git a/Medium/Longest Word With All Prefixes.java b/Medium/Longest Word With All Prefixes.java index 567aea3a..a2a69a0f 100644 --- a/Medium/Longest Word With All Prefixes.java +++ b/Medium/Longest Word With All Prefixes.java @@ -1,53 +1,59 @@ class Solution { - public String longestWord(String[] words) { - TrieNode root = new TrieNode(); - root.isWord = true; - Map> map = new TreeMap<>((o1, o2) -> o2 - o1); - for (String word : words) { - addToTrie(word, root); - map.computeIfAbsent(word.length(), k -> new PriorityQueue<>(String::compareTo)).add(word); - } - for (Integer key : map.keySet()) { - PriorityQueue priorityQueue = map.get(key); - while (!priorityQueue.isEmpty()) { - String candidateWord = priorityQueue.poll(); - if (wordContainAllPrefixes(candidateWord, root)) { - return candidateWord; + public String longestWord(String[] words) { + TrieNode root = new TrieNode(); + for (String word : words) { + root.insert(word); + } + String longestValidWord = ""; + for (String word : words) { + if (root.hasAllPrefixes(word)) { + if (word.length() > longestValidWord.length() || + (word.length() == longestValidWord.length() && word.compareTo(longestValidWord) < 0)) { + longestValidWord = word; + } + } } - } + return longestValidWord; } - return ""; - } - private boolean wordContainAllPrefixes(String word, TrieNode root) { - TrieNode curr = root; - for (int i = 0; i < word.length(); i++) { - if (!curr.isWord) { - return false; - } - curr = curr.children.get(word.charAt(i)); - } - return curr.isWord; - } + static class TrieNode { + private final Map children; + private boolean isWord; - private void addToTrie(String word, TrieNode root) { - TrieNode curr = root; - for (int i = 0; i < word.length(); i++) { - if (!curr.children.containsKey(word.charAt(i))) { - curr.children.put(word.charAt(i), new TrieNode()); - } - curr = curr.children.get(word.charAt(i)); - } - curr.isWord = true; - } + public TrieNode() { + this.children = new HashMap<>(); + } - private static class TrieNode { - Map children; - boolean isWord; + public void insert(String word) { + TrieNode curr = this; + for (char c : word.toCharArray()) { + curr = curr.getOrCreateChild(c); + } + curr.isWord = true; + } + + public boolean hasAllPrefixes(String word) { + TrieNode curr = this; + for (char c : word.toCharArray()) { + TrieNode child = curr.children.getOrDefault(c, null); + if (child == null) { + return false; + } + if (!child.isWord) { + return false; + } + curr = child; + } + return true; + } - public TrieNode() { - this.children = new HashMap<>(); - this.isWord = false; + private TrieNode getOrCreateChild(char c) { + if (children.containsKey(c)) { + return children.get(c); + } + TrieNode node = new TrieNode(); + children.put(c, node); + return node; + } } - } } From f12e321cfd48e32055dcbc0036907dfa6f46b4e2 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 22 Sep 2024 10:21:41 -0700 Subject: [PATCH 092/182] Update Binary Search Tree Iterator II.java --- Medium/Binary Search Tree Iterator II.java | 74 +++++++++++----------- 1 file changed, 36 insertions(+), 38 deletions(-) diff --git a/Medium/Binary Search Tree Iterator II.java b/Medium/Binary Search Tree Iterator II.java index 9f98110c..61ab1d10 100644 --- a/Medium/Binary Search Tree Iterator II.java +++ b/Medium/Binary Search Tree Iterator II.java @@ -14,49 +14,47 @@ * } */ class BSTIterator { - - private Deque stack; - private List arr; - private TreeNode lastNode; - private int pointer; - - public BSTIterator(TreeNode root) { - this.stack = new ArrayDeque(); - this.arr = new ArrayList<>(); - this.lastNode = root; - this.pointer = -1; - } - public boolean hasNext() { - return !this.stack.isEmpty() || lastNode != null || this.pointer < arr.size() - 1; - } + private final Deque primary; + private final List secondary; + private int index; - public int next() { - this.pointer++; - if (this.pointer == this.arr.size()) { - updateStack(lastNode); - TreeNode curr = this.stack.pop(); - lastNode = curr.right; - this.arr.add(curr.val); + public BSTIterator(TreeNode root) { + this.primary = new ArrayDeque<>(); + this.secondary = new ArrayList<>(); + this.index = -1; + traverse(root); + } + + public boolean hasNext() { + return !primary.isEmpty() || index < secondary.size() - 1; + } + + public int next() { + index++; + if (index == secondary.size()) { + TreeNode curr = primary.pop(); + secondary.add(curr.val); + traverse(curr.right); + } + return secondary.get(index); + } + + public boolean hasPrev() { + return index > 0; + } + + public int prev() { + index--; + return secondary.get(index); } - return this.arr.get(this.pointer); - } - - public boolean hasPrev() { - return this.pointer > 0; - } - public int prev() { - this.pointer--; - return this.arr.get(this.pointer); - } - - private void updateStack(TreeNode node) { - while (node != null) { - this.stack.push(node); - node = node.left; + private void traverse(TreeNode root) { + while (root != null) { + primary.push(root); + root = root.left; + } } - } } /** From 76548263a55db618f5973d3c7a88f49ace92a772 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 22 Sep 2024 15:16:25 -0700 Subject: [PATCH 093/182] Create K-th Smallest in Lexicographical Order.java --- ...-th Smallest in Lexicographical Order.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Hard/K-th Smallest in Lexicographical Order.java diff --git a/Hard/K-th Smallest in Lexicographical Order.java b/Hard/K-th Smallest in Lexicographical Order.java new file mode 100644 index 00000000..9063cd56 --- /dev/null +++ b/Hard/K-th Smallest in Lexicographical Order.java @@ -0,0 +1,27 @@ +class Solution { + public int findKthNumber(int n, int k) { + int curr = 1; + k--; + while (k > 0) { + int count = countNumsWithPrefix(n, curr, curr + 1); + if (count <= k) { + curr++; + k -= count; + } else { + curr *= 10; + k--; + } + } + return curr; + } + + private int countNumsWithPrefix(int n, long start, long end) { + int count = 0; + while (start <= n) { + count += Math.min(n + 1, end) - start; + start *= 10; + end *= 10; + } + return count; + } +} From 7e4afd555a663578a5662bd8e83459350cd0ccd5 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 28 Sep 2024 09:09:04 -0700 Subject: [PATCH 094/182] Update Design Circular Deque.java --- Medium/Design Circular Deque.java | 154 ++++++++++++++---------------- 1 file changed, 70 insertions(+), 84 deletions(-) diff --git a/Medium/Design Circular Deque.java b/Medium/Design Circular Deque.java index 86949d4a..66667ed5 100644 --- a/Medium/Design Circular Deque.java +++ b/Medium/Design Circular Deque.java @@ -1,104 +1,90 @@ class MyCircularDeque { - - private Node head; - private Node tail; - private int k; - private int currSize; - public MyCircularDeque(int k) { - this.k = k; - this.currSize = 0; - this.head = new Node(-1); - this.tail = new Node(-1); - this.head.next = this.tail; - this.tail.prev = this.head; - } + private final Node head; + private final Node tail; + private final int capacity; + private int size; - public boolean insertFront(int value) { - if (isFull()) { - return false; + public MyCircularDeque(int k) { + head = new Node(-1); + tail = new Node(-1); + head.next = tail; + tail.prev = head; + capacity = k; + size = 0; } - Node node = new Node(value); - Node nextToHead = head.next; - head.next = node; - node.prev = head; - node.next = nextToHead; - nextToHead.prev = node; - currSize++; - return true; - } - public boolean insertLast(int value) { - if (isFull()) { - return false; + public boolean insertFront(int value) { + if (size == capacity) { + return false; + } + Node node = new Node(value); + node.next = head.next; + node.prev = head; + head.next.prev = node; + head.next = node; + size++; + return true; } - Node node = new Node(value); - Node prevToTail = tail.prev; - tail.prev = node; - node.next = tail; - prevToTail.next = node; - node.prev = prevToTail; - currSize++; - return true; - } - public boolean deleteFront() { - if (isEmpty()) { - return false; + public boolean insertLast(int value) { + if (size == capacity) { + return false; + } + Node node = new Node(value); + node.prev = tail.prev; + node.next = tail; + tail.prev.next = node; + tail.prev = node; + size++; + return true; } - Node toDelete = head.next; - deleteNode(toDelete); - return true; - } - public boolean deleteLast() { - if (isEmpty()) { - return false; + public boolean deleteFront() { + if (size == 0) { + return false; + } + head.next.next.prev = head; + head.next = head.next.next; + size--; + return true; } - Node toDelete = tail.prev; - deleteNode(toDelete); - return true; - } - public int getFront() { - if (isEmpty()) { - return -1; + public boolean deleteLast() { + if (size == 0) { + return false; + } + tail.prev.prev.next = tail; + tail.prev = tail.prev.prev; + size--; + return true; } - return head.next.val; - } - public int getRear() { - if (isEmpty()) { - return -1; + public int getFront() { + return head.next.value; } - return tail.prev.val; - } - public boolean isEmpty() { - return currSize == 0; - } + public int getRear() { + return tail.prev.value; + } + + public boolean isEmpty() { + return size == 0; + } + + public boolean isFull() { + return size == capacity; + } + + static class Node { + int value; + Node next; + Node prev; - public boolean isFull() { - return currSize == k; - } - - private void deleteNode(Node node) { - Node prevToNode = node.prev; - Node nextToNode = node.next; - prevToNode.next = nextToNode; - nextToNode.prev = prevToNode; - currSize--; - } - - private static class Node { - int val; - Node next; - Node prev; - - public Node(int val) { - this.val = val; + Node(int value) { + this.value = value; + } } - } } /** From 877f164cd5305a15c080c7e0122c092d3abe4eb2 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 30 Sep 2024 08:21:33 -0700 Subject: [PATCH 095/182] Update Design a Stack With Increment Operation.java --- ...sign a Stack With Increment Operation.java | 62 +++++++++---------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/Medium/Design a Stack With Increment Operation.java b/Medium/Design a Stack With Increment Operation.java index 9164401b..9e4ec3a3 100644 --- a/Medium/Design a Stack With Increment Operation.java +++ b/Medium/Design a Stack With Increment Operation.java @@ -1,40 +1,40 @@ class CustomStack { - - private Stack stack; - private int[] incrementArray; - private int maxSize; - - public CustomStack(int maxSize) { - this.stack = new Stack<>(); - this.incrementArray = new int[maxSize]; - this.maxSize = maxSize; - } - public void push(int x) { - if (this.stack.size() < this.maxSize) { - this.stack.push(x); - } - } + private final int maxSize; + private final Stack stack; + private int[] increment; - public int pop() { - int idx = this.stack.size() - 1; - if (idx < 0) { - return -1; + public CustomStack(int maxSize) { + this.maxSize = maxSize; + this.stack = new Stack<>(); + this.increment = new int[maxSize]; } - if (idx > 0) { - this.incrementArray[idx - 1] += this.incrementArray[idx]; + + public void push(int x) { + if (stack.size() < maxSize) { + stack.push(x); + } } - int result = this.stack.pop() + this.incrementArray[idx]; - this.incrementArray[idx] = 0; - return result; - } - - public void increment(int k, int val) { - int idx = Math.min(k, this.stack.size()) - 1; - if (idx >= 0) { - this.incrementArray[idx] += val; + + public int pop() { + int idx = stack.size() - 1; + if (idx < 0) { + return -1; + } + if (idx > 0) { + increment[idx - 1] += increment[idx]; + } + int result = stack.pop() + increment[idx]; + increment[idx] = 0; + return result; + } + + public void increment(int k, int val) { + int idx = Math.min(k, stack.size()) - 1; + if (idx >= 0) { + increment[idx] += val; + } } - } } /** From a752149a8e834ce931f706737ab398d6e7c57597 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 1 Oct 2024 06:47:24 -0700 Subject: [PATCH 096/182] Create Check If Array Pairs Are Divisible by k.java --- ...eck If Array Pairs Are Divisible by k.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Medium/Check If Array Pairs Are Divisible by k.java diff --git a/Medium/Check If Array Pairs Are Divisible by k.java b/Medium/Check If Array Pairs Are Divisible by k.java new file mode 100644 index 00000000..d942915f --- /dev/null +++ b/Medium/Check If Array Pairs Are Divisible by k.java @@ -0,0 +1,20 @@ +class Solution { + public boolean canArrange(int[] arr, int k) { + Map map = new HashMap<>(); + for (int num : arr) { + int remainder = ((num % k) + k) % k; + map.put(remainder, map.getOrDefault(remainder, 0) + 1); + } + for (int num : arr) { + int remainder = ((num % k) + k) % k; + if (remainder == 0) { + if (map.get(remainder) % 2 == 1) { + return false; + } + } else if (!map.get(remainder).equals(map.get(k - remainder))) { + return false; + } + } + return true; + } +} From 1faa9c843764223e985afa1d6d816b4277f4707c Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 1 Oct 2024 17:34:31 -0700 Subject: [PATCH 097/182] Update Rank Transform of an Array.java --- Easy/Rank Transform of an Array.java | 33 ++++++++++++++-------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/Easy/Rank Transform of an Array.java b/Easy/Rank Transform of an Array.java index 401c317b..3f9192fd 100644 --- a/Easy/Rank Transform of an Array.java +++ b/Easy/Rank Transform of an Array.java @@ -1,20 +1,19 @@ class Solution { - public int[] arrayRankTransform(int[] arr) { - PriorityQueue pq = new PriorityQueue<>(); - for (int num : arr) { - pq.add(num); + public int[] arrayRankTransform(int[] arr) { + int[] copyArr = Arrays.copyOf(arr, arr.length); + Arrays.sort(arr); + int rank = 1; + Map numToRank = new HashMap<>(); + for (int num : arr) { + if (numToRank.containsKey(num)) { + continue; + } + numToRank.put(num, rank++); + } + int[] result = new int[arr.length]; + for (int i = 0; i < arr.length; i++) { + result[i] = numToRank.get(copyArr[i]); + } + return result; } - int rank = 1; - Map map = new HashMap<>(); - while (!pq.isEmpty()) { - int removed = pq.poll(); - if (!map.containsKey(removed)) { - map.put(removed, rank++); - } - } - for (int i = 0; i < arr.length; i++) { - arr[i] = map.get(arr[i]); - } - return arr; - } } From 914a2fc291a5634d072744e2f57289cea48822da Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 3 Oct 2024 09:50:16 -0700 Subject: [PATCH 098/182] Create Make Sum Divisible by P.java --- Medium/Make Sum Divisible by P.java | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Medium/Make Sum Divisible by P.java diff --git a/Medium/Make Sum Divisible by P.java b/Medium/Make Sum Divisible by P.java new file mode 100644 index 00000000..ee94817a --- /dev/null +++ b/Medium/Make Sum Divisible by P.java @@ -0,0 +1,26 @@ +class Solution { + public int minSubarray(int[] nums, int p) { + int n = nums.length; + int sum = 0; + for (int num : nums) { + sum = (sum + num) % p; + } + int target = sum % p; + if (target == 0) { + return 0; + } + Map map = new HashMap<>(); + map.put(0, -1); + int currSum = 0; + int result = n; + for (int i = 0; i < n; i++) { + currSum = (currSum + nums[i]) % p; + int needed = (currSum - target + p) % p; + if (map.containsKey(needed)) { + result = Math.min(result, i - map.get(needed)); + } + map.put(currSum, i); + } + return result == n ? -1 : result; + } +} From 650d084e89e1fe0d4ac6452d502fd280787e4f14 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 3 Oct 2024 17:51:53 -0700 Subject: [PATCH 099/182] Update Divide Players Into Teams of Equal Skill.java --- ...ide Players Into Teams of Equal Skill.java | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/Medium/Divide Players Into Teams of Equal Skill.java b/Medium/Divide Players Into Teams of Equal Skill.java index bebcec21..41a5f1f7 100644 --- a/Medium/Divide Players Into Teams of Equal Skill.java +++ b/Medium/Divide Players Into Teams of Equal Skill.java @@ -1,19 +1,25 @@ class Solution { public long dividePlayers(int[] skill) { - Arrays.sort(skill); + int n = skill.length; + int totalSkill = 0; + Map map = new HashMap<>(); + for (int s : skill) { + totalSkill += s; + map.put(s, map.getOrDefault(s, 0) + 1); + } + if (totalSkill % (n / 2) != 0) { + return -1; + } + int targetSkill = totalSkill / (n / 2); long totalChemistry = 0; - int start = 0; - int end = skill.length - 1; - int totalSkill = skill[start] + skill[end]; - while (start < end) { - int currTotal = skill[start] + skill[end]; - if (currTotal != totalSkill) { + for (int currSkill : map.keySet()) { + int partnerSkill = targetSkill - currSkill; + int currSkillFreq = map.get(currSkill); + if (!map.containsKey(partnerSkill) || currSkillFreq != map.get(partnerSkill)) { return -1; } - totalChemistry += skill[start] * skill[end]; - start++; - end--; + totalChemistry += (long) currSkill * (long) partnerSkill * (long) currSkillFreq; } - return totalChemistry; + return totalChemistry / 2; } } From 1c21ef27bee9a434d927ebaab33aa6910a192f2c Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 5 Oct 2024 18:26:00 -0700 Subject: [PATCH 100/182] Update Sentence Similarity III.java --- Medium/Sentence Similarity III.java | 51 +++++++++++++---------------- 1 file changed, 23 insertions(+), 28 deletions(-) diff --git a/Medium/Sentence Similarity III.java b/Medium/Sentence Similarity III.java index e85bb024..506dc110 100644 --- a/Medium/Sentence Similarity III.java +++ b/Medium/Sentence Similarity III.java @@ -1,31 +1,26 @@ class Solution { - public boolean areSentencesSimilar(String sentence1, String sentence2) { - return isSimilar(sentence1.split(" "), sentence2.split(" ")) || isSimilar(sentence2.split(" "), - sentence1.split(" ")); - } - - private boolean isSimilar(String[] matcher, String[] target) { - int targetStartIdx = 0; - int matcherCurrentIdx = 0; - while (targetStartIdx < target.length && matcherCurrentIdx < matcher.length) { - if (!matcher[matcherCurrentIdx].equals(target[targetStartIdx])) { - break; - } - targetStartIdx++; - matcherCurrentIdx++; + public boolean areSentencesSimilar(String sentence1, String sentence2) { + int idxOneStart = 0; + int idxTwoStart = 0; + String[] wordsOne = sentence1.split("\\s+"); + String[] wordsTwo = sentence2.split("\\s+"); + while (idxOneStart < wordsOne.length && idxOneStart < wordsTwo.length && wordsOne[idxOneStart].equals(wordsTwo[idxTwoStart])) { + idxOneStart++; + idxTwoStart++; + } + boolean startFound = idxOneStart > 0; + if (idxOneStart == wordsOne.length && idxTwoStart == wordsTwo.length) { + return true; + } + int idxOneEnd = wordsOne.length - 1; + int idxTwoEnd = wordsTwo.length - 1; + while (idxOneEnd >= idxOneStart && idxTwoEnd >= idxTwoStart && wordsOne[idxOneEnd].equals(wordsTwo[idxTwoEnd])) { + idxOneEnd--; + idxTwoEnd--; + } + if (idxOneEnd != idxOneStart - 1 && idxTwoEnd != idxTwoStart - 1) { + return false; + } + return true; } - if (targetStartIdx == target.length) { - return true; - } - int targetEndIdx = target.length - 1; - matcherCurrentIdx = matcher.length - 1; - while (targetEndIdx >= targetStartIdx && matcherCurrentIdx >= 0) { - if (!matcher[matcherCurrentIdx].equals(target[targetEndIdx])) { - return false; - } - targetEndIdx--; - matcherCurrentIdx--; - } - return targetEndIdx == targetStartIdx - 1; - } } From ca3dcbee5b4c14751ab1f56532a9380a004dd1bc Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 7 Oct 2024 17:31:53 -0700 Subject: [PATCH 101/182] Create Minimum Number of Swaps to Make the String Balanced.java --- ... of Swaps to Make the String Balanced.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Medium/Minimum Number of Swaps to Make the String Balanced.java diff --git a/Medium/Minimum Number of Swaps to Make the String Balanced.java b/Medium/Minimum Number of Swaps to Make the String Balanced.java new file mode 100644 index 00000000..79935f13 --- /dev/null +++ b/Medium/Minimum Number of Swaps to Make the String Balanced.java @@ -0,0 +1,24 @@ +class Solution { + public int minSwaps(String s) { + char[] chars = s.toCharArray(); + Stack openBrackets = new Stack<>(); + for (int i = 0; i < chars.length; i++) { + if (chars[i] == '[') { + openBrackets.push(i); + } + } + int open = 0; + int swaps = 0; + for (int i = 0; i < chars.length; i++) { + open += chars[i] == '[' ? 1 : -1; + if (open < 0) { + swaps++; + int endIdx = openBrackets.pop(); + chars[endIdx] = ']'; + chars[i] = '['; + open += 2; + } + } + return swaps; + } +} From 6b30e46841a64facd6a0ce6652b3b791c22b4071 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 9 Oct 2024 08:03:17 -0700 Subject: [PATCH 102/182] Update Minimum Add to Make Parentheses Valid.java --- ...Minimum Add to Make Parentheses Valid.java | 24 ++++++++----------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/Medium/Minimum Add to Make Parentheses Valid.java b/Medium/Minimum Add to Make Parentheses Valid.java index f119bfe7..7fcfc88d 100644 --- a/Medium/Minimum Add to Make Parentheses Valid.java +++ b/Medium/Minimum Add to Make Parentheses Valid.java @@ -1,18 +1,14 @@ class Solution { - public int minAddToMakeValid(String s) { - int count = 0; - Stack stack = new Stack<>(); - for (char c : s.toCharArray()) { - if (c == '(') { - stack.push(c); - } else { - if (stack.isEmpty()) { - count++; - } else { - stack.pop(); + public int minAddToMakeValid(String s) { + int open = 0; + int count = 0; + for (char c : s.toCharArray()) { + open += c == '(' ? 1 : -1; + if (open < 0) { + count += Math.abs(open); + open = 0; + } } - } + return count + open; } - return count + stack.size(); - } } From d1379d8078e538484116cb808a78388380b306f0 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 9 Oct 2024 10:14:41 -0700 Subject: [PATCH 103/182] Create Maximum Coins Heroes Can Collect.java --- medium/Maximum Coins Heroes Can Collect.java | 40 ++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 medium/Maximum Coins Heroes Can Collect.java diff --git a/medium/Maximum Coins Heroes Can Collect.java b/medium/Maximum Coins Heroes Can Collect.java new file mode 100644 index 00000000..1e98abf9 --- /dev/null +++ b/medium/Maximum Coins Heroes Can Collect.java @@ -0,0 +1,40 @@ +class Solution { + public long[] maximumCoins(int[] heroes, int[] monsters, int[] coins) { + List monsterEntities = new ArrayList<>(); + int n = monsters.length; + for (int i = 0; i < n; i++) { + monsterEntities.add(new MonsterEntity(monsters[i], coins[i])); + } + Collections.sort(monsterEntities, (a, b) -> (a.health() - b.health())); + long[] prefixCoinSum = new long[n]; + for (int i = 0; i < n; i++) { + prefixCoinSum[i] = i == 0 ? 0 : prefixCoinSum[i - 1]; + prefixCoinSum[i] += monsterEntities.get(i).coin(); + } + int m = heroes.length; + long[] result = new long[m]; + for (int i = 0; i < m; i++) { + int idx = binarySearch(monsterEntities, heroes[i]); + result[i] = idx != Integer.MIN_VALUE ? prefixCoinSum[idx] : 0; + } + return result; + } + + private int binarySearch(List monsterEntities, int heroHealth) { + int left = 0; + int right = monsterEntities.size() - 1; + int idx = Integer.MIN_VALUE; + while (left <= right) { + int mid = (left + right) / 2; + if (monsterEntities.get(mid).health() <= heroHealth) { + idx = Math.max(idx, mid); + left = mid + 1; + } else { + right = mid - 1; + } + } + return idx; + } + + private static record MonsterEntity(int health, int coin) {} +} From e5760b1d4aaeae4b661093b3dec2e62b541545e6 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 9 Oct 2024 10:15:04 -0700 Subject: [PATCH 104/182] Rename Maximum Coins Heroes Can Collect.java to Maximum Coins Heroes Can Collect.java --- {medium => Medium}/Maximum Coins Heroes Can Collect.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {medium => Medium}/Maximum Coins Heroes Can Collect.java (100%) diff --git a/medium/Maximum Coins Heroes Can Collect.java b/Medium/Maximum Coins Heroes Can Collect.java similarity index 100% rename from medium/Maximum Coins Heroes Can Collect.java rename to Medium/Maximum Coins Heroes Can Collect.java From d56f44da8d3fdbae82f4e27bef44e27488c5287e Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 10 Oct 2024 08:39:16 -0700 Subject: [PATCH 105/182] Update Maximum Width Ramp.java --- Medium/Maximum Width Ramp.java | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/Medium/Maximum Width Ramp.java b/Medium/Maximum Width Ramp.java index 37eb1862..2463f02b 100644 --- a/Medium/Maximum Width Ramp.java +++ b/Medium/Maximum Width Ramp.java @@ -1,21 +1,18 @@ class Solution { - public int maxWidthRamp(int[] A) { + public int maxWidthRamp(int[] nums) { + int n = nums.length; Stack stack = new Stack<>(); - int ans = 0; - int n = A.length; - - for (int i=0; i A[i]) { - stack.add(i); + for (int i = 0; i < n; i++) { + if (stack.isEmpty() || nums[stack.peek()] > nums[i]) { + stack.push(i); } } - - for (int i=n-1; i>=ans; i--) { - while (!stack.isEmpty() && A[stack.peek()] <= A[i]) { - ans = Math.max(ans, i - stack.pop()); + int result = 0; + for (int i = n - 1; i >= 0; i--) { + while (!stack.isEmpty() && nums[stack.peek()] <= nums[i]) { + result = Math.max(result, i - stack.pop()); } } - - return ans; + return result; } } From ffe05dfbf9f0fbb017472657a1119a14474af94f Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 11 Oct 2024 14:37:42 -0700 Subject: [PATCH 106/182] Create The Number of the Smallest Unoccupied Chair.java --- ...mber of the Smallest Unoccupied Chair.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Medium/The Number of the Smallest Unoccupied Chair.java diff --git a/Medium/The Number of the Smallest Unoccupied Chair.java b/Medium/The Number of the Smallest Unoccupied Chair.java new file mode 100644 index 00000000..6bd41ad2 --- /dev/null +++ b/Medium/The Number of the Smallest Unoccupied Chair.java @@ -0,0 +1,35 @@ +class Solution { + public int smallestChair(int[][] times, int targetFriend) { + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> { + int c = o1[0] - o2[0]; + if (c == 0) { + return o1[1] - o2[1]; + } + return c; + }); + for (int i = 0; i < times.length; i++) { + pq.add(new int[]{times[i][0], times[i][1], i}); + } + PriorityQueue occupiedChairs = new PriorityQueue<>(Comparator.comparingInt(o -> o[0])); + PriorityQueue emptyChairs = new PriorityQueue<>(); + int currChair = 0; + while (!pq.isEmpty()) { + int[] time = pq.poll(); + while (!occupiedChairs.isEmpty() && occupiedChairs.peek()[0] <= time[0]) { + int[] chair = occupiedChairs.poll(); + emptyChairs.add(chair[1]); + } + if (time[2] == targetFriend) { + return emptyChairs.isEmpty() ? currChair : emptyChairs.poll(); + } + if (emptyChairs.isEmpty()) { + occupiedChairs.add(new int[]{time[1], currChair}); + currChair++; + } else { + int chair = emptyChairs.poll(); + occupiedChairs.add(new int[]{time[1], chair}); + } + } + return -1; + } +} From 771c1a5b06c14648c4c4e2f3a3f7aefa668f4039 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 11 Oct 2024 14:38:57 -0700 Subject: [PATCH 107/182] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a90fb07e..617cd951 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ## Solutions to Leetcode problems in Java -## [Current Leetcode profile: Solved 1600+ Problems](https://leetcode.com/varunsjsu/) +## [Current Leetcode profile: Solved 1700+ Problems](https://leetcode.com/varunsjsu/) ## [Previous Leetcode profile: Solved 759 Problems](https://leetcode.com/varunu28/) Problem Category | Count From 139140dd8a5224d3c7ce675b118d0c2dd0ac89f8 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 12 Oct 2024 07:49:28 -0700 Subject: [PATCH 108/182] Create Divide Intervals Into Minimum Number of Groups.java --- ...tervals Into Minimum Number of Groups.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Medium/Divide Intervals Into Minimum Number of Groups.java diff --git a/Medium/Divide Intervals Into Minimum Number of Groups.java b/Medium/Divide Intervals Into Minimum Number of Groups.java new file mode 100644 index 00000000..b58d0dcb --- /dev/null +++ b/Medium/Divide Intervals Into Minimum Number of Groups.java @@ -0,0 +1,21 @@ +class Solution { + public int minGroups(int[][] intervals) { + Arrays.sort(intervals, (o1, o2) -> { + int c = Integer.compare(o1[0], o2[0]); + if (c == 0) { + return Integer.compare(o1[1], o2[1]); + } + return c; + }); + int max = 0; + PriorityQueue pq = new PriorityQueue<>(); + for (int[] interval : intervals) { + while (!pq.isEmpty() && pq.peek() < interval[0]) { + pq.poll(); + } + pq.add(interval[1]); + max = Math.max(max, pq.size()); + } + return max; + } +} From ab2e5bd95da86a9fd92c7774644c1e91fe14840e Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 13 Oct 2024 16:00:28 -0700 Subject: [PATCH 109/182] Create Smallest Range Covering Elements from K Lists.java --- ... Range Covering Elements from K Lists.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Hard/Smallest Range Covering Elements from K Lists.java diff --git a/Hard/Smallest Range Covering Elements from K Lists.java b/Hard/Smallest Range Covering Elements from K Lists.java new file mode 100644 index 00000000..4e814027 --- /dev/null +++ b/Hard/Smallest Range Covering Elements from K Lists.java @@ -0,0 +1,29 @@ +class Solution { + public int[] smallestRange(List> nums) { + PriorityQueue pq = new PriorityQueue<>( + Comparator.comparingInt(a -> a[0])); + int max = Integer.MIN_VALUE; + int start = 0; + int end = Integer.MAX_VALUE; + for (int i = 0; i < nums.size(); i++) { + pq.add(new int[]{nums.get(i).get(0), i, 0}); + max = Math.max(max, nums.get(i).get(0)); + } + while (pq.size() == nums.size()) { + int[] removed = pq.poll(); + int min = removed[0]; + int row = removed[1]; + int col = removed[2]; + if (max - min < end - start) { + start = min; + end = max; + } + if (col + 1 < nums.get(row).size()) { + int next = nums.get(row).get(col + 1); + pq.add(new int[]{next, row, col + 1}); + max = Math.max(max, next); + } + } + return new int[]{start, end}; + } +} From 74177e433ba8c9723053bf93afd433a275d184a7 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 15 Oct 2024 07:48:08 -0700 Subject: [PATCH 110/182] Create Separate Black and White Balls.java --- Medium/Separate Black and White Balls.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Medium/Separate Black and White Balls.java diff --git a/Medium/Separate Black and White Balls.java b/Medium/Separate Black and White Balls.java new file mode 100644 index 00000000..5fc4900f --- /dev/null +++ b/Medium/Separate Black and White Balls.java @@ -0,0 +1,13 @@ +class Solution { + public long minimumSteps(String s) { + int whitePos = 0; + long swaps = 0; + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == '0') { + swaps += i - whitePos; + whitePos++; + } + } + return swaps; + } +} From d69d6fa23d5303c23a6bb1e7882f71cc5a3faccf Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 15 Oct 2024 07:54:33 -0700 Subject: [PATCH 111/182] Update First Unique Number.java --- Medium/First Unique Number.java | 75 ++++++++------------------------- 1 file changed, 17 insertions(+), 58 deletions(-) diff --git a/Medium/First Unique Number.java b/Medium/First Unique Number.java index d5406335..6affb411 100644 --- a/Medium/First Unique Number.java +++ b/Medium/First Unique Number.java @@ -1,68 +1,27 @@ class FirstUnique { - - private Node head; - private Node tail; - private Map map; - - public FirstUnique(int[] nums) { - this.head = new Node(-1); - this.tail = new Node(-1); - this.head.next = this.tail; - this.tail.prev = this.head; - this.map = new HashMap<>(); - for (int num : nums) { - if (map.containsKey(num)) { - deleteNode(map.get(num)); - } else { - Node node = new Node(num); - map.put(num, node); - addToTail(node); - } - } - } - public int showFirstUnique() { - return this.head.next.val; - } + private Map map; + private Queue queue; - public void add(int value) { - if (map.containsKey(value)) { - deleteNode(map.get(value)); - return; + public FirstUnique(int[] nums) { + map = new HashMap<>(); + queue = new LinkedList<>(); + for (int num : nums) { + add(num); + } } - Node node = new Node(value); - map.put(value, node); - addToTail(node); - } - - private void addToTail(Node node) { - Node prevToTail = this.tail.prev; - prevToTail.next = node; - node.next = this.tail; - node.prev = prevToTail; - this.tail.prev = node; - } - - private void deleteNode(Node node) { - if (node == null) { - return; + + public int showFirstUnique() { + while (!queue.isEmpty() && map.get(queue.peek()) > 1) { + queue.remove(); + } + return queue.isEmpty() ? -1 : queue.peek(); } - map.put(node.val, null); - Node prevToNode = node.prev; - Node nextToNode = node.next; - prevToNode.next = nextToNode; - nextToNode.prev = prevToNode; - } - - private static class Node { - int val; - Node next; - Node prev; - public Node(int val) { - this.val = val; + public void add(int value) { + queue.add(value); + map.put(value, map.getOrDefault(value, 0) + 1); } - } } /** From 40e30d0c6424c785b8b51c8f435175dd3b762054 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 16 Oct 2024 07:00:08 -0700 Subject: [PATCH 112/182] Update Longest Happy String.java --- Medium/Longest Happy String.java | 74 ++++++++++++++++---------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/Medium/Longest Happy String.java b/Medium/Longest Happy String.java index 145fd638..4af8f747 100644 --- a/Medium/Longest Happy String.java +++ b/Medium/Longest Happy String.java @@ -1,42 +1,42 @@ class Solution { - public String longestDiverseString(int a, int b, int c) { - PriorityQueue priorityQueue = new PriorityQueue<>((o1, o2) -> o2[1] - o1[1]); - if (a > 0) { - priorityQueue.add(new int[]{0, a}); - } - if (b > 0) { - priorityQueue.add(new int[]{1, b}); - } - if (c > 0) { - priorityQueue.add(new int[]{2, c}); - } - StringBuilder sb = new StringBuilder("zz"); - while (!priorityQueue.isEmpty()) { - int[] temp = {-1, -1}; - char peekChar = (char) ('a' + priorityQueue.peek()[0]); - if (peekChar == sb.charAt(sb.length() - 1) && - peekChar == sb.charAt(sb.length() - 2)) { - temp[0] = priorityQueue.peek()[0]; - temp[1] = priorityQueue.peek()[1]; - priorityQueue.poll(); - if (priorityQueue.isEmpty()) { - break; + public String longestDiverseString(int a, int b, int c) { + PriorityQueue pq = + new PriorityQueue<>((p, q) -> q.frequency() - p.frequency()); + if (a > 0) { + pq.add(new LetterFrequencyPair('a', a)); + } + if (b > 0) { + pq.add(new LetterFrequencyPair('b', b)); + } + if (c > 0) { + pq.add(new LetterFrequencyPair('c', c)); } - } - peekChar = (char) ('a' + priorityQueue.peek()[0]); - if (peekChar != sb.charAt(sb.length() - 1) || - peekChar != sb.charAt(sb.length() - 2)) { - int[] removed = priorityQueue.poll(); - sb.append(peekChar); - removed[1]--; - if (removed[1] > 0) { - priorityQueue.add(removed); + StringBuilder sb = new StringBuilder(); + while (!pq.isEmpty()) { + LetterFrequencyPair removed = pq.remove(); + int frequency = removed.frequency(); + int resultLength = sb.length(); + if (resultLength >= 2 && + sb.charAt(resultLength - 1) == removed.letter() && + sb.charAt(resultLength - 2) == removed.letter()) { + if (pq.isEmpty()) { + break; + } + LetterFrequencyPair temp = pq.remove(); + sb.append(temp.letter()); + if (temp.frequency() - 1 > 0) { + pq.add(new LetterFrequencyPair(temp.letter(), temp.frequency() - 1)); + } + } else { + sb.append(removed.letter()); + frequency--; + } + if (frequency > 0) { + pq.add(new LetterFrequencyPair(removed.letter(), frequency)); + } } - } - if (temp[0] != -1) { - priorityQueue.add(temp); - } + return sb.toString(); } - return sb.substring(2).toString(); - } + + private record LetterFrequencyPair(char letter, int frequency) {} } From 45105d882a6f2b03e88fc2198a54990a1b91e620 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 17 Oct 2024 07:04:29 -0700 Subject: [PATCH 113/182] Update Maximum Swap.java --- Medium/Maximum Swap.java | 41 ++++++++++++++++------------------------ 1 file changed, 16 insertions(+), 25 deletions(-) diff --git a/Medium/Maximum Swap.java b/Medium/Maximum Swap.java index 5d30c780..c12fb12e 100644 --- a/Medium/Maximum Swap.java +++ b/Medium/Maximum Swap.java @@ -1,29 +1,20 @@ class Solution { - public int maximumSwap(int num) { - String stringValue = Integer.toString(num); - Map valToIndexMap = new HashMap<>(); - int[] digits = new int[String.valueOf(num).length()]; - for (int i = digits.length - 1; i >= 0; i--) { - int digit = num % 10; - num /= 10; - digits[i] = digit; - valToIndexMap.putIfAbsent(digit, i); - } - for (int i = 0; i < digits.length; i++) { - for (int k = 9; k > digits[i]; k--) { - if (valToIndexMap.getOrDefault(k, -1) > i) { - int swapIndex = valToIndexMap.get(k); - return Integer.parseInt( - stringValue.substring(0, i) // Digits before swap index - + k // Swapped value - + stringValue.substring(i + 1, swapIndex) // Digits after original index(i) and before swappedIndex - + digits[i] // Digit at original index(i) - + ((swapIndex + 1) != stringValue.length() // Check if swapIndex is last digit of num - ? stringValue.substring(swapIndex + 1) // If not then add digits that come after the swapIndex - : "")); // Else add an empty string + public int maximumSwap(int num) { + char[] digits = String.valueOf(num).toCharArray(); + int n = digits.length; + int[] maxRightIdx = new int[n]; + maxRightIdx[n - 1] = n - 1; + for (int i = n - 2; i >= 0; i--) { + maxRightIdx[i] = (digits[i] > digits[maxRightIdx[i + 1]]) ? i : maxRightIdx[i + 1]; + } + for (int i = 0; i < n; i++) { + if (digits[i] < digits[maxRightIdx[i]]) { + char temp = digits[i]; + digits[i] = digits[maxRightIdx[i]]; + digits[maxRightIdx[i]] = temp; + return Integer.parseInt(String.valueOf(digits)); + } } - } + return num; } - return Integer.parseInt(stringValue); - } } From 0190cfd86d0c79f6ba0a2c265aa81086a960ff1c Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 18 Oct 2024 08:15:08 -0700 Subject: [PATCH 114/182] Create Count Number of Maximum Bitwise-OR Subsets.java --- ... Number of Maximum Bitwise-OR Subsets.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Medium/Count Number of Maximum Bitwise-OR Subsets.java diff --git a/Medium/Count Number of Maximum Bitwise-OR Subsets.java b/Medium/Count Number of Maximum Bitwise-OR Subsets.java new file mode 100644 index 00000000..973e1818 --- /dev/null +++ b/Medium/Count Number of Maximum Bitwise-OR Subsets.java @@ -0,0 +1,23 @@ +class Solution { + public int countMaxOrSubsets(int[] nums) { + int n = nums.length; + int maxValue = 0; + for (int num : nums) { + maxValue |= num; + } + Integer[][] dp = new Integer[n][maxValue + 1]; + return countMaxOrSubsets(nums, 0, 0, maxValue, dp); + } + + private int countMaxOrSubsets(int[] nums, int idx, int current, int maxValue, Integer[][] dp) { + if (idx == nums.length) { + return (current == maxValue) ? 1 : 0; + } + if (dp[idx][current] != null) { + return dp[idx][current]; + } + int countWithout = countMaxOrSubsets(nums, idx + 1, current, maxValue, dp); + int countWith = countMaxOrSubsets(nums, idx + 1, current | nums[idx], maxValue, dp); + return dp[idx][current] = countWith + countWithout; + } +} From 3a2e60db99c494d79a72a64121306fb5fed66e9e Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 19 Oct 2024 08:48:07 -0700 Subject: [PATCH 115/182] Create Find Kth Bit in Nth Binary String.java --- Medium/Find Kth Bit in Nth Binary String.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Medium/Find Kth Bit in Nth Binary String.java diff --git a/Medium/Find Kth Bit in Nth Binary String.java b/Medium/Find Kth Bit in Nth Binary String.java new file mode 100644 index 00000000..e98b29c7 --- /dev/null +++ b/Medium/Find Kth Bit in Nth Binary String.java @@ -0,0 +1,22 @@ +class Solution { + public char findKthBit(int n, int k) { + return nthString(n).charAt(k - 1); + } + + private String nthString(int n) { + if (n == 1) { + return "0"; + } + String prevString = nthString(n - 1); + return prevString + "1" + reverseAndInvert(prevString); + } + + private String reverseAndInvert(String s) { + char[] chars = s.toCharArray(); + for (int i = 0; i < s.length(); i++) { + chars[i] = chars[i] == '1' ? '0' : '1'; + } + StringBuilder sb = new StringBuilder(String.valueOf(chars)); + return sb.reverse().toString(); + } +} From a3143e2bc5be251f4b005133f7582b848c52c573 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 20 Oct 2024 09:25:50 -0700 Subject: [PATCH 116/182] Update Parsing A Boolean Expression.java --- Hard/Parsing A Boolean Expression.java | 91 +++++++++----------------- 1 file changed, 31 insertions(+), 60 deletions(-) diff --git a/Hard/Parsing A Boolean Expression.java b/Hard/Parsing A Boolean Expression.java index 2c419aa8..97a56130 100644 --- a/Hard/Parsing A Boolean Expression.java +++ b/Hard/Parsing A Boolean Expression.java @@ -1,72 +1,43 @@ class Solution { public boolean parseBoolExpr(String expression) { - char[] chars = expression.toCharArray(); - Stack operations = new Stack<>(); - Stack boolValues = new Stack<>(); - - for (int i = 0; i < chars.length; i++) { - char c = chars[i]; - if (c == '!' || c == '&' || c == '|') { - operations.push(c); - } - else if (c == '(') { - boolValues.push('#'); - } - else if (c == 't' || c == 'f') { - boolValues.push(chars[i]); - } - else if (c == ',') { - continue; - } - else { - List list = new ArrayList<>(); - while (!boolValues.isEmpty()) { - char temp = boolValues.pop(); - if (temp == '#') { - break; - } - - list.add(temp); + Stack stack = new Stack<>(); + for (char c : expression.toCharArray()) { + if (c == ')') { + List values = new ArrayList<>(); + while (stack.peek() != '(') { + values.add(stack.pop()); } - - boolValues.push(performOperation(list, operations.pop())); + stack.pop(); + char operation = stack.pop(); + char result = evaluate(operation, values); + stack.push(result); + } else if (c != ',') { + stack.push(c); } } - - return boolValues.peek() == 't' ? true : false; + return stack.peek() == 't'; } - private Character performOperation(List list, Character operation) { - if (operation == '|') { - return performOr(list); - } - else if (operation == '&') { - return performAnd(list); + private static char evaluate(char operation, List values) { + if (operation == '!') { + return values.get(0) == 't' ? 'f' : 't'; } - else { - return list.get(0) == 't' ? 'f' : 't'; - } - } - - private Character performAnd(List list) { - boolean val = getBooleanValue(list.get(0)); - for (int i = 1; i < list.size(); i++) { - val &= getBooleanValue(list.get(i)); + if (operation == '&') { + for (char value : values) { + if (value == 'f') { + return 'f'; + } + } + return 't'; } - - return val ? 't' : 'f'; - } - - private Character performOr(List list) { - boolean val = getBooleanValue(list.get(0)); - for (int i = 1; i < list.size(); i++) { - val |= getBooleanValue(list.get(i)); + if (operation == '|') { + for (char value : values) { + if (value == 't') { + return 't'; + } + } + return 'f'; } - - return val ? 't' : 'f'; - } - - private boolean getBooleanValue(Character character) { - return character == 't' ? true : false; + return 'f'; } } From 7b253d794e4f465cb89df85bee72000915f06ad3 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 21 Oct 2024 12:40:07 -0700 Subject: [PATCH 117/182] Create Split a String Into the Max Number of Unique Substrings.java --- ...o the Max Number of Unique Substrings.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Medium/Split a String Into the Max Number of Unique Substrings.java diff --git a/Medium/Split a String Into the Max Number of Unique Substrings.java b/Medium/Split a String Into the Max Number of Unique Substrings.java new file mode 100644 index 00000000..3e418df7 --- /dev/null +++ b/Medium/Split a String Into the Max Number of Unique Substrings.java @@ -0,0 +1,21 @@ +class Solution { + public int maxUniqueSplit(String s) { + Set seen = new HashSet<>(); + return backtrack(s, 0, seen); + } + + private int backtrack(String s, int idx, Set seen) { + if (idx == s.length()) { + return 0; + } + int count = 0; + for (int end = idx + 1; end <= s.length(); end++) { + String substring = s.substring(idx, end); + if (seen.add(substring)) { + count = Math.max(count, 1 + backtrack(s, end, seen)); + seen.remove(substring); + } + } + return count; + } +} From 975d71b3150dcf4772c7b542b8b6765c03f92e90 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 23 Oct 2024 06:42:23 -0700 Subject: [PATCH 118/182] Create Cousins in Binary Tree II.java --- Medium/Cousins in Binary Tree II.java | 44 +++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Medium/Cousins in Binary Tree II.java diff --git a/Medium/Cousins in Binary Tree II.java b/Medium/Cousins in Binary Tree II.java new file mode 100644 index 00000000..ee1b4b21 --- /dev/null +++ b/Medium/Cousins in Binary Tree II.java @@ -0,0 +1,44 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode replaceValueInTree(TreeNode root) { + Queue queue = new LinkedList<>(); + queue.add(root); + int prevLevelSum = root.val; + while (!queue.isEmpty()) { + int size = queue.size(); + int levelSum = 0; + for (int i = 0; i < size; i++) { + TreeNode node = queue.remove(); + node.val = prevLevelSum - node.val; + int siblingSum = (node.left != null ? node.left.val : 0) + + (node.right != null ? node.right.val : 0); + if (node.left != null) { + levelSum += node.left.val; + node.left.val = siblingSum; + queue.add(node.left); + } + if (node.right != null) { + levelSum += node.right.val; + node.right.val = siblingSum; + queue.add(node.right); + } + } + prevLevelSum = levelSum; + } + return root; + } +} From 2dea3e54c58e5a45993f084c75aca141c5ca978f Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 24 Oct 2024 07:18:31 -0700 Subject: [PATCH 119/182] Update Flip Equivalent Binary Trees.java --- Medium/Flip Equivalent Binary Trees.java | 42 ++++++++++++------------ 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/Medium/Flip Equivalent Binary Trees.java b/Medium/Flip Equivalent Binary Trees.java index 7829ff4d..8590505e 100644 --- a/Medium/Flip Equivalent Binary Trees.java +++ b/Medium/Flip Equivalent Binary Trees.java @@ -1,31 +1,31 @@ -i/** +/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; - * TreeNode(int x) { val = x; } + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } * } */ class Solution { - public boolean flipEquiv(TreeNode root1, TreeNode root2) { - if (root1 == null && root2 == null) { - return true; + public boolean flipEquiv(TreeNode root1, TreeNode root2) { + if (root1 == null && root2 == null) { + return true; + } + if (root1 == null || root2 == null) { + return false; + } + if (root1.val != root2.val) { + return false; + } + boolean noSwap = flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right); + boolean swap = flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left); + return noSwap || swap; } - if (root1 == null || root2 == null) { - return false; - } - if (root1.val != root2.val) { - return false; - } - return ( - ( - flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right) - ) || - ( - flipEquiv(root1.left, root2.right) && - flipEquiv(root1.right, root2.left) - ) - ); - } } From 07715d08a8f45047ee39fbc6ed05247406a7d8ce Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 25 Oct 2024 07:34:43 -0700 Subject: [PATCH 120/182] Update Remove Sub-Folders from the Filesystem.java --- ...emove Sub-Folders from the Filesystem.java | 83 ++++++++++++++----- 1 file changed, 63 insertions(+), 20 deletions(-) diff --git a/Medium/Remove Sub-Folders from the Filesystem.java b/Medium/Remove Sub-Folders from the Filesystem.java index 2d91c97e..62f67bcd 100644 --- a/Medium/Remove Sub-Folders from the Filesystem.java +++ b/Medium/Remove Sub-Folders from the Filesystem.java @@ -1,24 +1,67 @@ class Solution { - public List removeSubfolders(String[] folder) { - Set set = new HashSet<>(); - Arrays.sort(folder, new Comparator(){ - public int compare(String s1, String s2) { - return s1.length() - s2.length(); - } - }); - for (String fl : folder) { - String[] files = fl.split("/"); - StringBuilder sb = new StringBuilder(); - for (int i = 1; i < files.length; i++) { - sb.append("/").append(files[i]); - if (set.contains(sb.toString())) { - break; + public List removeSubfolders(String[] folder) { + TrieNode root = new TrieNode(); + for (String file : folder) { + TrieNode curr = root; + String[] splits = file.split("/"); + for (int i = 1; i < splits.length; i++) { + Optional nextNode = curr.getChild(splits[i]); + if (nextNode.isEmpty()) { + TrieNode newNode = curr.addChild(splits[i]); + curr = newNode; + } else { + curr = nextNode.get(); + } + } + curr.markIsFolder(); + } + List result = new ArrayList<>(); + for (String file : folder) { + TrieNode curr = root; + String[] splits = file.split("/"); + boolean isSubfolder = false; + for (int i = 1; i < splits.length; i++) { + TrieNode nextNode = curr.getChild(splits[i]).get(); + if (nextNode.isFolder() && i != splits.length - 1) { + isSubfolder = true; + break; + } + curr = nextNode; + } + if (!isSubfolder) { + result.add(file); + } + } + return result; + } + + class TrieNode { + private boolean isFolder; + private Map children; + + public TrieNode() { + this.children = new HashMap<>(); + } + + public TrieNode addChild(String childKey) { + TrieNode node = new TrieNode(); + children.put(childKey, node); + return node; + } + + public Optional getChild(String childKey) { + if (!children.containsKey(childKey)) { + return Optional.empty(); + } + return Optional.of(children.get(childKey)); + } + + public void markIsFolder() { + isFolder = true; + } + + public boolean isFolder() { + return isFolder; } - } - if (sb.length() > 0) { - set.add(sb.toString()); - } } - return new ArrayList<>(set); - } } From 65583aed6e8c71a04f047c3bb1e8cc03c0249cf0 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 26 Oct 2024 09:22:03 -0700 Subject: [PATCH 121/182] Create Height of Binary Tree After Subtree Removal Queries.java --- ...ry Tree After Subtree Removal Queries.java | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Hard/Height of Binary Tree After Subtree Removal Queries.java diff --git a/Hard/Height of Binary Tree After Subtree Removal Queries.java b/Hard/Height of Binary Tree After Subtree Removal Queries.java new file mode 100644 index 00000000..ebd9acbe --- /dev/null +++ b/Hard/Height of Binary Tree After Subtree Removal Queries.java @@ -0,0 +1,48 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int[] treeQueries(TreeNode root, int[] queries) { + Map result = new HashMap<>(); + Map heightCache = new HashMap<>(); + dfs(root, 0, 0, result, heightCache); + int[] answer = new int[queries.length]; + for (int i = 0; i < queries.length; i++) { + answer[i] = result.get(queries[i]); + } + return answer; + } + + private void dfs(TreeNode node, int depth, int maxDepth, Map result, Map heightCache) { + if (node == null) { + return; + } + result.put(node.val, maxDepth); + dfs(node.left, depth + 1, Math.max(maxDepth, depth + 1 + height(node.right, heightCache)), result, heightCache); + dfs(node.right, depth + 1, Math.max(maxDepth, depth + 1 + height(node.left, heightCache)), result, heightCache); + } + + private int height(TreeNode node, Map heightCache) { + if (node == null) { + return -1; + } + if (heightCache.containsKey(node)) { + return heightCache.get(node); + } + int currHeight = 1 + Math.max(height(node.left, heightCache), height(node.right, heightCache)); + heightCache.put(node, currHeight); + return currHeight; + } +} From 0d68682d23ee31299361af2a5c059f16ac1f224a Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 26 Oct 2024 14:32:07 -0700 Subject: [PATCH 122/182] Create Find the Original Typed String I.java --- Easy/Find the Original Typed String I.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Easy/Find the Original Typed String I.java diff --git a/Easy/Find the Original Typed String I.java b/Easy/Find the Original Typed String I.java new file mode 100644 index 00000000..dd6a5177 --- /dev/null +++ b/Easy/Find the Original Typed String I.java @@ -0,0 +1,17 @@ +class Solution { + public int possibleStringCount(String word) { + int idx = 0; + int result = 1; + while (idx < word.length()) { + int currIdx = idx; + char c = word.charAt(currIdx); + while (currIdx < word.length() && word.charAt(currIdx) == c) { + currIdx++; + } + int segement = currIdx - idx; + result += segement - 1; + idx = currIdx; + } + return result; + } +} From c458cea30a0ff3997b1babb07c871fc154c7eed7 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 28 Oct 2024 07:07:44 -0700 Subject: [PATCH 123/182] Create Longest Square Streak in an Array.java --- Medium/Longest Square Streak in an Array.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Medium/Longest Square Streak in an Array.java diff --git a/Medium/Longest Square Streak in an Array.java b/Medium/Longest Square Streak in an Array.java new file mode 100644 index 00000000..141abdee --- /dev/null +++ b/Medium/Longest Square Streak in an Array.java @@ -0,0 +1,25 @@ +class Solution { + + private static final int LIMIT = 100_000; + + public int longestSquareStreak(int[] nums) { + Set uniqueNums = new HashSet<>(); + for (int num : nums) { + uniqueNums.add(num); + } + int result = 0; + for (int num : nums) { + int currStreak = 0; + long curr = num; + while (uniqueNums.contains((int) curr)) { + currStreak++; + if (curr * curr > LIMIT) { + break; + } + curr *= curr; + } + result = Math.max(result, currStreak); + } + return result < 2 ? -1 : result; + } +} From 65c039985ea998ee26bcce26574385d4146caf26 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 29 Oct 2024 08:02:39 -0700 Subject: [PATCH 124/182] Create Maximum Number of Moves in a Grid.java --- Medium/Maximum Number of Moves in a Grid.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Medium/Maximum Number of Moves in a Grid.java diff --git a/Medium/Maximum Number of Moves in a Grid.java b/Medium/Maximum Number of Moves in a Grid.java new file mode 100644 index 00000000..014425f8 --- /dev/null +++ b/Medium/Maximum Number of Moves in a Grid.java @@ -0,0 +1,40 @@ +class Solution { + + private static final int[] DIRS = {-1, 0, 1}; + + public int maxMoves(int[][] grid) { + int rows = grid.length; + int cols = grid[0].length; + Queue queue = new LinkedList<>(); + boolean[][] visited = new boolean[rows][cols]; + for (int i = 0; i < rows; i++) { + visited[i][0] = true; + queue.add(new int[]{i, 0, 0}); + } + int result = 0; + while (!queue.isEmpty()) { + int size = queue.size(); + while (size-- > 0) { + int[] removed = queue.remove(); + int row = removed[0]; + int col = removed[1]; + int count = removed[2]; + result = Math.max(result, count); + for (int dir : DIRS) { + int nextRow = row + dir; + int nextCol = col + 1; + if (nextRow >= 0 && + nextCol >= 0 && + nextRow < rows && + nextCol < cols && + !visited[nextRow][nextCol] && + grid[row][col] < grid[nextRow][nextCol]) { + visited[nextRow][nextCol] = true; + queue.add(new int[]{nextRow, nextCol, count + 1}); + } + } + } + } + return result; + } +} From 2580a677b3a9c0b6cda1a0f7103c57020472cc3a Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 30 Oct 2024 06:47:27 -0700 Subject: [PATCH 125/182] Create Minimum Number of Removals to Make Mountain Array.java --- ...er of Removals to Make Mountain Array.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Hard/Minimum Number of Removals to Make Mountain Array.java diff --git a/Hard/Minimum Number of Removals to Make Mountain Array.java b/Hard/Minimum Number of Removals to Make Mountain Array.java new file mode 100644 index 00000000..b74f6feb --- /dev/null +++ b/Hard/Minimum Number of Removals to Make Mountain Array.java @@ -0,0 +1,30 @@ +class Solution { + public int minimumMountainRemovals(int[] nums) { + int n = nums.length; + int[] leftIncreasingLength = new int[n]; + int[] rightDecreasingLength = new int[n]; + Arrays.fill(leftIncreasingLength, 1); + Arrays.fill(rightDecreasingLength, 1); + for (int i = 0; i < n; i++) { + for (int j = i - 1; j >= 0; j--) { + if (nums[i] > nums[j]) { + leftIncreasingLength[i] = Math.max(leftIncreasingLength[i], leftIncreasingLength[j] + 1); + } + } + } + for (int i = n - 1; i >= 0; i--) { + for (int j = i + 1; j < n; j++) { + if (nums[i] > nums[j]) { + rightDecreasingLength[i] = Math.max(rightDecreasingLength[i], rightDecreasingLength[j] + 1); + } + } + } + int minRemovals = Integer.MAX_VALUE; + for (int i = 0; i < n; i++) { + if (leftIncreasingLength[i] > 1 && rightDecreasingLength[i] > 1) { + minRemovals = Math.min(minRemovals, n - leftIncreasingLength[i] - rightDecreasingLength[i] + 1); + } + } + return minRemovals; + } +} From aafb2effbd9500cfb5e24ceae7986147ed70d6ee Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 4 Nov 2024 06:35:54 -0800 Subject: [PATCH 126/182] Create String Compression III.java --- Medium/String Compression III.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Medium/String Compression III.java diff --git a/Medium/String Compression III.java b/Medium/String Compression III.java new file mode 100644 index 00000000..03a6737c --- /dev/null +++ b/Medium/String Compression III.java @@ -0,0 +1,16 @@ +class Solution { + public String compressedString(String word) { + StringBuilder sb = new StringBuilder(); + int idx = 0; + while (idx < word.length()) { + char c = word.charAt(idx); + int count = 0; + while (idx < word.length() && word.charAt(idx) == c && count < 9) { + idx++; + count++; + } + sb.append(count).append(c); + } + return sb.toString(); + } +} From 1c1f3cf1277b63af4b230b6dffd3a8f61f7f1497 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 6 Nov 2024 07:25:20 -0800 Subject: [PATCH 127/182] Create Number of Same-End Substrings.java --- Medium/Number of Same-End Substrings.java | 28 +++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Medium/Number of Same-End Substrings.java diff --git a/Medium/Number of Same-End Substrings.java b/Medium/Number of Same-End Substrings.java new file mode 100644 index 00000000..4003737d --- /dev/null +++ b/Medium/Number of Same-End Substrings.java @@ -0,0 +1,28 @@ +class Solution { + public int[] sameEndSubstringCount(String s, int[][] queries) { + int n = s.length(); + int[][] prefixSum = new int[26][n]; + for (int i = 0; i < n; i++) { + prefixSum[s.charAt(i) - 'a'][i]++; + } + for (int i = 0; i < 26; i++) { + for (int j = 1; j < n; j++) { + prefixSum[i][j] += prefixSum[i][j - 1]; + } + } + int[] result = new int[queries.length]; + for (int i = 0; i < queries.length; i++) { + int left = queries[i][0]; + int right = queries[i][1]; + int count = 0; + for (int c = 0; c < 26; c++) { + int leftFreq = left == 0 ? 0 : prefixSum[c][left - 1]; + int rightFreq = prefixSum[c][right]; + int freqInRange = rightFreq - leftFreq; + count += (freqInRange * (freqInRange + 1)) / 2; + } + result[i] = count; + } + return result; + } +} From 5a3795b8956bbe92bbdd5462beae0b5ef2c6abdd Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 7 Nov 2024 08:12:32 -0800 Subject: [PATCH 128/182] Create Largest Combination With Bitwise AND Greater Than Zero.java --- ...tion With Bitwise AND Greater Than Zero.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Medium/Largest Combination With Bitwise AND Greater Than Zero.java diff --git a/Medium/Largest Combination With Bitwise AND Greater Than Zero.java b/Medium/Largest Combination With Bitwise AND Greater Than Zero.java new file mode 100644 index 00000000..1399f1bb --- /dev/null +++ b/Medium/Largest Combination With Bitwise AND Greater Than Zero.java @@ -0,0 +1,17 @@ +class Solution { + public int largestCombination(int[] candidates) { + int[] bitCount = new int[24]; + for (int i = 0; i < 24; i++) { + for (int candidate : candidates) { + if ((candidate & (1 << i)) != 0) { + bitCount[i]++; + } + } + } + int result = 0; + for (int count : bitCount) { + result = Math.max(count, result); + } + return result; + } +} From f1e4d1887ee89e1bcdaf4cb0c6f343bd5c7b6ad1 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 14 Nov 2024 06:35:00 -0800 Subject: [PATCH 129/182] Create Minimized Maximum of Products Distributed to Any Store.java --- ... of Products Distributed to Any Store.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Medium/Minimized Maximum of Products Distributed to Any Store.java diff --git a/Medium/Minimized Maximum of Products Distributed to Any Store.java b/Medium/Minimized Maximum of Products Distributed to Any Store.java new file mode 100644 index 00000000..70a46016 --- /dev/null +++ b/Medium/Minimized Maximum of Products Distributed to Any Store.java @@ -0,0 +1,36 @@ +class Solution { + public int minimizedMaximum(int n, int[] quantities) { + int left = 0; + int right = 0; + for (int quantity : quantities) { + right = Math.max(right, quantity); + } + while (left < right) { + int mid = (left + right) / 2; + if (isPossible(n, mid, quantities)) { + right = mid; + } else { + left = mid + 1; + } + } + return left; + } + + private boolean isPossible(int n, int min, int[] quantities) { + int idx = 0; + int remaining = quantities[idx]; + for (int i = 0; i < n; i++) { + if (remaining <= min) { + idx++; + if (idx == quantities.length) { + return true; + } else { + remaining = quantities[idx]; + } + } else { + remaining -= min; + } + } + return false; + } +} From ceb871f66e65b8cc2655d9891c555781347d9c1a Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 15 Nov 2024 08:05:15 -0800 Subject: [PATCH 130/182] Create Shortest Subarray to be Removed to Make Array Sorted.java --- ...ray to be Removed to Make Array Sorted.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Medium/Shortest Subarray to be Removed to Make Array Sorted.java diff --git a/Medium/Shortest Subarray to be Removed to Make Array Sorted.java b/Medium/Shortest Subarray to be Removed to Make Array Sorted.java new file mode 100644 index 00000000..4ddb25e2 --- /dev/null +++ b/Medium/Shortest Subarray to be Removed to Make Array Sorted.java @@ -0,0 +1,18 @@ +class Solution { + public int findLengthOfShortestSubarray(int[] arr) { + int right = arr.length - 1; + while (right > 0 && arr[right] >= arr[right - 1]) { + right--; + } + int result = right; + int left = 0; + while (left < right && (left == 0 || arr[left - 1] <= arr[left])) { + while (right < arr.length && arr[left] > arr[right]) { + right++; + } + result = Math.min(result, right - left - 1); + left++; + } + return result; + } +} From 5eaf0134b8d8b7eafb7abae9f60e826bcb98b41f Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 17 Nov 2024 06:52:36 -0800 Subject: [PATCH 131/182] Create Adjacent Increasing Subarrays Detection I.java --- ...cent Increasing Subarrays Detection I.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Easy/Adjacent Increasing Subarrays Detection I.java diff --git a/Easy/Adjacent Increasing Subarrays Detection I.java b/Easy/Adjacent Increasing Subarrays Detection I.java new file mode 100644 index 00000000..5be82de7 --- /dev/null +++ b/Easy/Adjacent Increasing Subarrays Detection I.java @@ -0,0 +1,20 @@ +class Solution { + public boolean hasIncreasingSubarrays(List nums, int k) { + int n = nums.size(); + for (int i = 0; i <= n - 2 * k; i++) { + if (isStrictlyIncreasing(nums, i, k) && isStrictlyIncreasing(nums, i + k, k)) { + return true; + } + } + return false; + } + + private boolean isStrictlyIncreasing(List nums, int idx, int k) { + for (int start = idx; start < idx + k - 1; start++) { + if (nums.get(start) >= nums.get(start + 1)) { + return false; + } + } + return true; + } +} From 8738cee338223b3413232342be126e90ac9cf9e2 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 20 Nov 2024 08:28:53 -0800 Subject: [PATCH 132/182] Create Take K of Each Character From Left and Right.java --- ...of Each Character From Left and Right.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Medium/Take K of Each Character From Left and Right.java diff --git a/Medium/Take K of Each Character From Left and Right.java b/Medium/Take K of Each Character From Left and Right.java new file mode 100644 index 00000000..4b878ce0 --- /dev/null +++ b/Medium/Take K of Each Character From Left and Right.java @@ -0,0 +1,27 @@ +class Solution { + public int takeCharacters(String s, int k) { + int[] counter = new int[3]; + int n = s.length(); + for (char c : s.toCharArray()) { + counter[c - 'a']++; + } + for (int i = 0; i < 3; i++) { + if (counter[i] < k) { + return -1; + } + } + int[] window = new int[3]; + int left = 0; + int maxWindow = 0; + for (int right = 0; right < n; right++) { + window[s.charAt(right) - 'a']++; + while (left <= right && + (counter[0] - window[0] < k || counter[1] - window[1] < k || counter[2] - window[2] < k)) { + window[s.charAt(left) - 'a']--; + left++; + } + maxWindow = Math.max(maxWindow, right - left + 1); + } + return n - maxWindow; + } +} From 199a76c4f8b272a7c632841e36959c9aa1c8b46c Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 22 Dec 2024 05:48:36 +0530 Subject: [PATCH 133/182] Create Count Subarrays of Length Three With a Condition.java --- ...nt Subarrays of Length Three With a Condition.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Easy/Count Subarrays of Length Three With a Condition.java diff --git a/Easy/Count Subarrays of Length Three With a Condition.java b/Easy/Count Subarrays of Length Three With a Condition.java new file mode 100644 index 00000000..4694fb65 --- /dev/null +++ b/Easy/Count Subarrays of Length Three With a Condition.java @@ -0,0 +1,11 @@ +class Solution { + public int countSubarrays(int[] nums) { + int count = 0; + for (int i = 0; i < nums.length - 2; i++) { + if (2 * (nums[i] + nums[i + 2]) == nums[i + 1]) { + count++; + } + } + return count; + } +} From 6735f7a0d2bb149726984a53fb48766c43e7e243 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 23 Dec 2024 06:41:01 +0530 Subject: [PATCH 134/182] Create Minimum Number of Operations to Make Elements in Array Distinct.java --- ...ons to Make Elements in Array Distinct.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Easy/Minimum Number of Operations to Make Elements in Array Distinct.java diff --git a/Easy/Minimum Number of Operations to Make Elements in Array Distinct.java b/Easy/Minimum Number of Operations to Make Elements in Array Distinct.java new file mode 100644 index 00000000..a61239e7 --- /dev/null +++ b/Easy/Minimum Number of Operations to Make Elements in Array Distinct.java @@ -0,0 +1,18 @@ +class Solution { + public int minimumOperations(int[] nums) { + Set set = new HashSet<>(); + int index = -1; + for (int i = nums.length - 1; i >= 0; i--) { + if (set.contains(nums[i])) { + index = i; + break; + } + set.add(nums[i]); + } + if (index == -1) { + return 0; + } + index++; + return index % 3 == 0 ? index / 3 : (index / 3) + 1; + } +} From c8ba8359855d7be2aa9f966f0a9d9a3ae3435dff Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 26 Dec 2024 18:27:19 +0530 Subject: [PATCH 135/182] Create Button with Longest Push Time.java --- Easy/Button with Longest Push Time.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Easy/Button with Longest Push Time.java diff --git a/Easy/Button with Longest Push Time.java b/Easy/Button with Longest Push Time.java new file mode 100644 index 00000000..650bb1e4 --- /dev/null +++ b/Easy/Button with Longest Push Time.java @@ -0,0 +1,18 @@ +class Solution { + public int buttonWithLongestTime(int[][] events) { + int maxTime = 0; + int resultIdx = 0; + int prevTime = 0; + for (int i = 0; i < events.length; i++) { + int timePressed = events[i][1] - prevTime; + if (timePressed > maxTime) { + maxTime = timePressed; + resultIdx = events[i][0]; + } else if (timePressed == maxTime && resultIdx > events[i][0]) { + resultIdx = events[i][0]; + } + prevTime = events[i][1]; + } + return resultIdx; + } +} From 9d4036992d100703cb34fecc1183c457bc4d44af Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 12 Jan 2025 12:23:37 -0800 Subject: [PATCH 136/182] Create Check if a Parentheses String Can Be Valid.java --- ... if a Parentheses String Can Be Valid.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Medium/Check if a Parentheses String Can Be Valid.java diff --git a/Medium/Check if a Parentheses String Can Be Valid.java b/Medium/Check if a Parentheses String Can Be Valid.java new file mode 100644 index 00000000..c240176d --- /dev/null +++ b/Medium/Check if a Parentheses String Can Be Valid.java @@ -0,0 +1,30 @@ +class Solution { + public boolean canBeValid(String s, String locked) { + if (s.length() % 2 != 0) { + return false; + } + Stack openBrackets = new Stack<>(); + Stack unlocked = new Stack<>(); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (locked.charAt(i) == '0') { + unlocked.push(i); + } else if (c == '(') { + openBrackets.push(i); + } else if (c == ')') { + if (!openBrackets.isEmpty()) { + openBrackets.pop(); + } else if (!unlocked.isEmpty()) { + unlocked.pop(); + } else { + return false; + } + } + } + while (!openBrackets.isEmpty() && !unlocked.isEmpty() && openBrackets.peek() < unlocked.peek()) { + openBrackets.pop(); + unlocked.pop(); + } + return openBrackets.isEmpty(); + } +} From 0298b447e75aa7ceedb837d55c3790ac0f7073b8 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 14 Jan 2025 06:41:46 -0800 Subject: [PATCH 137/182] Update Find the Prefix Common Array of Two Arrays.java --- ...the Prefix Common Array of Two Arrays.java | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/Medium/Find the Prefix Common Array of Two Arrays.java b/Medium/Find the Prefix Common Array of Two Arrays.java index bd747227..e6312a17 100644 --- a/Medium/Find the Prefix Common Array of Two Arrays.java +++ b/Medium/Find the Prefix Common Array of Two Arrays.java @@ -1,14 +1,17 @@ class Solution { public int[] findThePrefixCommonArray(int[] A, int[] B) { - Map map = new HashMap<>(); int count = 0; - int[] result = new int[A.length]; - for (int i = 0; i < A.length; i++) { - map.put(A[i], map.getOrDefault(A[i], 0) + 1); - map.put(B[i], map.getOrDefault(B[i], 0) + 1); - count += map.get(A[i]) == 2 ? 1 : 0; - if (A[i] != B[i]) { - count += map.get(B[i]) == 2 ? 1 : 0; + int n = A.length; + int[] result = new int[n]; + int[] frequency = new int[n + 1]; + for (int i = 0; i < n; i++) { + frequency[A[i]]++; + if (frequency[A[i]] == 2) { + count++; + } + frequency[B[i]]++; + if (frequency[B[i]] == 2) { + count++; } result[i] = count; } From a03b2709db74206a8efecbc2f878d87b808bfc00 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 15 Jan 2025 07:12:59 -0800 Subject: [PATCH 138/182] Create Minimize XOR.java --- Medium/Minimize XOR.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Medium/Minimize XOR.java diff --git a/Medium/Minimize XOR.java b/Medium/Minimize XOR.java new file mode 100644 index 00000000..cc5e87a3 --- /dev/null +++ b/Medium/Minimize XOR.java @@ -0,0 +1,24 @@ +class Solution { + public int minimizeXor(int num1, int num2) { + int result = 0; + int targetSetBitCount = Integer.bitCount(num2); + int setBitCount = 0; + int currBit = 31; + while (setBitCount < targetSetBitCount) { + if (isSet(num1, currBit) || (targetSetBitCount - setBitCount > currBit)) { + result = setBit(result, currBit); + setBitCount++; + } + currBit--; + } + return result; + } + + private boolean isSet(int x, int bit) { + return (x & (1 << bit)) != 0; + } + + private int setBit(int x, int bit) { + return x | (1 << bit); + } +} From fbb599922e136af4abfa4180c747b50e57fc1060 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 15 Jan 2025 17:37:21 -0800 Subject: [PATCH 139/182] Create Bitwise XOR of All Pairings.java --- Medium/Bitwise XOR of All Pairings.java | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Medium/Bitwise XOR of All Pairings.java diff --git a/Medium/Bitwise XOR of All Pairings.java b/Medium/Bitwise XOR of All Pairings.java new file mode 100644 index 00000000..88dfbd41 --- /dev/null +++ b/Medium/Bitwise XOR of All Pairings.java @@ -0,0 +1,20 @@ +class Solution { + public int xorAllNums(int[] nums1, int[] nums2) { + int m = nums1.length; + int n = nums2.length; + Map freq = new HashMap<>(); + for (int num : nums1) { + freq.put(num, freq.getOrDefault(num, 0) + n); + } + for (int num : nums2) { + freq.put(num, freq.getOrDefault(num, 0) + m); + } + int result = 0; + for (Integer key : freq.keySet()) { + if (freq.get(key) % 2 == 1) { + result ^= key; + } + } + return result; + } +} From e8baf509b7624bb7a17be44df8afd34511d71f4e Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 16 Jan 2025 17:13:07 -0800 Subject: [PATCH 140/182] Create Neighboring Bitwise XOR.java --- Medium/Neighboring Bitwise XOR.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Medium/Neighboring Bitwise XOR.java diff --git a/Medium/Neighboring Bitwise XOR.java b/Medium/Neighboring Bitwise XOR.java new file mode 100644 index 00000000..6e46025c --- /dev/null +++ b/Medium/Neighboring Bitwise XOR.java @@ -0,0 +1,16 @@ +class Solution { + public boolean doesValidArrayExist(int[] derived) { + int n = derived.length; + int[] original = new int[n + 1]; + for (int i = 0; i < derived.length; i++) { + original[i + 1] = derived[i] ^ original[i]; + } + boolean checkForZero = (original[0] == original[n]); + original[0] = 1; + for (int i = 0; i < n; i++) { + original[i + 1] = derived[i] ^ original[i]; + } + boolean checkForOne = (original[0] == original[n]); + return checkForZero || checkForOne; + } +} From 72a77c98c7d75ee9a5de805aa885158e8478f12e Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 20 Jan 2025 09:55:45 -0800 Subject: [PATCH 141/182] Create Sum of Variable Length Subarrays.java --- Easy/Sum of Variable Length Subarrays.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Easy/Sum of Variable Length Subarrays.java diff --git a/Easy/Sum of Variable Length Subarrays.java b/Easy/Sum of Variable Length Subarrays.java new file mode 100644 index 00000000..5dc7d585 --- /dev/null +++ b/Easy/Sum of Variable Length Subarrays.java @@ -0,0 +1,19 @@ +class Solution { + public int subarraySum(int[] nums) { + int n = nums.length; + int[] prefixSum = new int[n]; + int sum = 0; + int result = 0; + for (int i = 0; i < n; i++) { + sum += nums[i]; + prefixSum[i] = sum; + int start = Math.max(0, i - nums[i]); + int subarraySum = prefixSum[i]; + if (start > 0) { + subarraySum -= prefixSum[start - 1]; + } + result += subarraySum; + } + return result; + } +} From d6786b2ff3c8a07e513860428dd3aabbfc08cf20 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 26 Jan 2025 12:00:18 -0800 Subject: [PATCH 142/182] Create Count Partitions with Even Sum Difference.java --- ...unt Partitions with Even Sum Difference.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Easy/Count Partitions with Even Sum Difference.java diff --git a/Easy/Count Partitions with Even Sum Difference.java b/Easy/Count Partitions with Even Sum Difference.java new file mode 100644 index 00000000..0390a5a1 --- /dev/null +++ b/Easy/Count Partitions with Even Sum Difference.java @@ -0,0 +1,17 @@ +class Solution { + public int countPartitions(int[] nums) { + int n = nums.length; + int[] prefixSum = new int[n]; + for (int i = 0; i < n; i++) { + prefixSum[i] = nums[i]; + prefixSum[i] += i == 0 ? 0 : prefixSum[i - 1]; + } + int partitions = 0; + for (int i = 0; i < n - 1; i++) { + int leftSum = prefixSum[i]; + int rightSum = prefixSum[n - 1] - prefixSum[i]; + partitions += (rightSum - leftSum) % 2 == 0 ? 1 : 0; + } + return partitions; + } +} From 4c9aa9825459d2daa31037fc023d74417964b321 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 31 Jan 2025 08:19:14 -0800 Subject: [PATCH 143/182] Create Count Mentions Per User.java --- Medium/Count Mentions Per User.java | 61 +++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Medium/Count Mentions Per User.java diff --git a/Medium/Count Mentions Per User.java b/Medium/Count Mentions Per User.java new file mode 100644 index 00000000..7fa42668 --- /dev/null +++ b/Medium/Count Mentions Per User.java @@ -0,0 +1,61 @@ +class Solution { + public int[] countMentions(int numberOfUsers, List> eventLog) { + List events = eventLog.stream() + .map(Event::buildEvent) + .sorted() + .collect(Collectors.toList()); + Map offlineUsers = new HashMap<>(); + int[] mentions = new int[numberOfUsers]; + for (Event event : events) { + if (event.message().equals("OFFLINE")) { + offlineUsers.put(Integer.parseInt(event.mentionString()), event.timestamp()); + } else { + int timestamp = event.timestamp(); + List onlineUsers = offlineUsers.entrySet() + .stream() + .filter(t -> timestamp - t.getValue() >= 60) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); + onlineUsers.forEach(offlineUsers::remove); + String mentionString = event.mentionString(); + if (mentionString.equals("ALL")) { + for (int i = 0; i < numberOfUsers; i++) { + mentions[i]++; + } + } else if (mentionString.equals("HERE")) { + for (int i = 0; i < numberOfUsers; i++) { + if (!offlineUsers.containsKey(i)) { + mentions[i]++; + } + } + } else { + String[] usersMentioned = mentionString.split(" "); + for (String user : usersMentioned) { + int userId = Integer.parseInt(user.substring(2)); + mentions[userId]++; + } + } + } + } + return mentions; + } + + private record Event(String message, int timestamp, String mentionString) implements Comparable { + + public static Event buildEvent(List event) { + String message = event.get(0); + int timestamp = Integer.parseInt(event.get(1)); + String mentionString = event.get(2); + return new Event(message, timestamp, mentionString); + } + + @Override + public int compareTo(Event o) { + int c = this.timestamp - o.timestamp; + if (c != 0) { + return c; + } + return o.message().compareTo(this.message()); + } + } +} From d8afeb208d59a04ec1360c090fa2090b6bc5ceb3 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 2 Feb 2025 10:50:47 -0800 Subject: [PATCH 144/182] Create Maximum Difference Between Even and Odd Frequency I.java --- ...ence Between Even and Odd Frequency I.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Easy/Maximum Difference Between Even and Odd Frequency I.java diff --git a/Easy/Maximum Difference Between Even and Odd Frequency I.java b/Easy/Maximum Difference Between Even and Odd Frequency I.java new file mode 100644 index 00000000..ec68c06f --- /dev/null +++ b/Easy/Maximum Difference Between Even and Odd Frequency I.java @@ -0,0 +1,19 @@ +class Solution { + public int maxDifference(String s) { + Map map = new HashMap<>(); + for (char c : s.toCharArray()) { + map.put(c, map.getOrDefault(c, 0) + 1); + } + int maxOdd = Integer.MIN_VALUE; + int minEven = Integer.MAX_VALUE; + for (Character key : map.keySet()) { + Integer value = map.get(key); + if (value % 2 == 0) { + minEven = Math.min(minEven, value); + } else { + maxOdd = Math.max(maxOdd, value); + } + } + return maxOdd - minEven; + } +} From 540318b7d9293dc1da5c063a50b6f05cd6730edc Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 3 Feb 2025 09:25:47 -0800 Subject: [PATCH 145/182] Create Longest Strictly Increasing or Strictly Decreasing Subarray.java --- ...asing or Strictly Decreasing Subarray.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Easy/Longest Strictly Increasing or Strictly Decreasing Subarray.java diff --git a/Easy/Longest Strictly Increasing or Strictly Decreasing Subarray.java b/Easy/Longest Strictly Increasing or Strictly Decreasing Subarray.java new file mode 100644 index 00000000..c1ed1c36 --- /dev/null +++ b/Easy/Longest Strictly Increasing or Strictly Decreasing Subarray.java @@ -0,0 +1,22 @@ +class Solution { + public int longestMonotonicSubarray(int[] nums) { + int max = 1; + int idx = 0; + int n = nums.length; + while (idx < n) { + if (idx == n - 1 || nums[idx + 1] == nums[idx]) { + idx++; + continue; + } + boolean increase = nums[idx + 1] > nums[idx]; + int start = idx; + while (idx + 1 < n && ( + (increase && nums[idx + 1] > nums[idx]) || + (!increase && nums[idx + 1] < nums[idx]))) { + idx++; + } + max = Math.max(max, idx - start + 1); + } + return max; + } +} From c259c7ab846d08dcc0fc9d3cd4d07ac1c901a2e6 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 3 Feb 2025 17:35:11 -0800 Subject: [PATCH 146/182] Update Maximum Ascending Subarray Sum.java --- Easy/Maximum Ascending Subarray Sum.java | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/Easy/Maximum Ascending Subarray Sum.java b/Easy/Maximum Ascending Subarray Sum.java index fb436414..fd64c04c 100644 --- a/Easy/Maximum Ascending Subarray Sum.java +++ b/Easy/Maximum Ascending Subarray Sum.java @@ -1,14 +1,15 @@ class Solution { - public int maxAscendingSum(int[] nums) { - int maximumSum = 0; - int idx = 0; - while (idx < nums.length) { - int currSum = nums[idx++]; - while (idx < nums.length && nums[idx] > nums[idx - 1]) { - currSum += nums[idx++]; - } - maximumSum = Math.max(maximumSum, currSum); + public int maxAscendingSum(int[] nums) { + int maxSum = 0; + int idx = 0; + int n = nums.length; + while (idx < n) { + int currSum = nums[idx++]; + while (idx < n && nums[idx] > nums[idx - 1]) { + currSum += nums[idx++]; + } + maxSum = Math.max(maxSum, currSum); + } + return maxSum; } - return maximumSum; - } } From d9a05d959355c1e27adb0d404872b4d3bafe5763 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 5 Feb 2025 07:54:25 -0800 Subject: [PATCH 147/182] Update Check if One String Swap Can Make Strings Equal.java --- ...ne String Swap Can Make Strings Equal.java | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/Easy/Check if One String Swap Can Make Strings Equal.java b/Easy/Check if One String Swap Can Make Strings Equal.java index 3f26dac9..fca6fc9d 100644 --- a/Easy/Check if One String Swap Can Make Strings Equal.java +++ b/Easy/Check if One String Swap Can Make Strings Equal.java @@ -1,16 +1,21 @@ class Solution { - public boolean areAlmostEqual(String s1, String s2) { - int mismatchIdx = -1; - for (int i = 0; i < s1.length(); i++) { - if (s1.charAt(i) != s2.charAt(i)) { - if (mismatchIdx != -1) { - return s1.charAt(mismatchIdx) == s2.charAt(i) && - s1.charAt(i) == s2.charAt(mismatchIdx) && - s1.substring(i + 1).equals(s2.substring(i + 1)); + public boolean areAlmostEqual(String s1, String s2) { + int swapIdx = -1; + boolean swapped = false; + for (int i = 0; i < s1.length(); i++) { + if (s1.charAt(i) != s2.charAt(i)) { + if (swapped) { + return false; + } + if (swapIdx != -1) { + if (!(s1.charAt(swapIdx) == s2.charAt(i) && s1.charAt(i) == s2.charAt(swapIdx))) { + return false; + } + swapped = true; + } + swapIdx = i; + } } - mismatchIdx = i; - } + return swapIdx == -1 || (swapIdx != -1 && swapped); } - return mismatchIdx == -1; - } } From 70d1c410af8e9fb0177e1494d24adffca1d7f7cb Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 7 Feb 2025 06:58:14 -0800 Subject: [PATCH 148/182] Create Find the Number of Distinct Colors Among the Balls.java --- ...er of Distinct Colors Among the Balls.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Medium/Find the Number of Distinct Colors Among the Balls.java diff --git a/Medium/Find the Number of Distinct Colors Among the Balls.java b/Medium/Find the Number of Distinct Colors Among the Balls.java new file mode 100644 index 00000000..428e5406 --- /dev/null +++ b/Medium/Find the Number of Distinct Colors Among the Balls.java @@ -0,0 +1,23 @@ +class Solution { + public int[] queryResults(int limit, int[][] queries) { + Map ballToColor = new HashMap<>(); + Map colorToBallCount = new HashMap<>(); + int n = queries.length; + int[] result = new int[n]; + for (int i = 0; i < queries.length; i++) { + int ball = queries[i][0]; + int color = queries[i][1]; + if (ballToColor.containsKey(ball)) { + int prevColor = ballToColor.get(ball); + colorToBallCount.put(prevColor, colorToBallCount.get(prevColor) - 1); + if (colorToBallCount.get(prevColor) == 0) { + colorToBallCount.remove(prevColor); + } + } + ballToColor.put(ball, color); + colorToBallCount.put(color, colorToBallCount.getOrDefault(color, 0) + 1); + result[i] = colorToBallCount.size(); + } + return result; + } +} From aa8154baf0afb55c54055d44e5af4b7df0455f82 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 8 Feb 2025 11:35:50 -0800 Subject: [PATCH 149/182] Create Design a Number Container System.java --- Medium/Design a Number Container System.java | 34 ++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Medium/Design a Number Container System.java diff --git a/Medium/Design a Number Container System.java b/Medium/Design a Number Container System.java new file mode 100644 index 00000000..26a3e843 --- /dev/null +++ b/Medium/Design a Number Container System.java @@ -0,0 +1,34 @@ +class NumberContainers { + + private final Map> numberToIndex; + private final Map indexToNumber; + + public NumberContainers() { + this.numberToIndex = new HashMap<>(); + this.indexToNumber = new HashMap<>(); + } + + public void change(int index, int number) { + if (indexToNumber.containsKey(index)) { + int prevNumber = indexToNumber.get(index); + numberToIndex.get(prevNumber).remove(index); + } + indexToNumber.put(index, number); + numberToIndex.computeIfAbsent(number, k -> new TreeSet<>()).add(index); + } + + public int find(int number) { + TreeSet indices = numberToIndex.getOrDefault(number, new TreeSet<>()); + if (indices.isEmpty()) { + return -1; + } + return indices.first(); + } +} + +/** + * Your NumberContainers object will be instantiated and called as such: + * NumberContainers obj = new NumberContainers(); + * obj.change(index,number); + * int param_2 = obj.find(number); + */ From 583c210c39e1ecb62cde8460bcd55f23f2123f66 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 11 Feb 2025 07:07:35 -0800 Subject: [PATCH 150/182] Update Remove All Occurrences of a Substring.java --- ...Remove All Occurrences of a Substring.java | 38 ++++++++++++++----- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/Medium/Remove All Occurrences of a Substring.java b/Medium/Remove All Occurrences of a Substring.java index 08fa1f78..e46ad3f2 100644 --- a/Medium/Remove All Occurrences of a Substring.java +++ b/Medium/Remove All Occurrences of a Substring.java @@ -1,12 +1,32 @@ class Solution { - public String removeOccurrences(String s, String part) { - while (true) { - int idx = s.indexOf(part); - if (idx == -1) { - break; - } - s = s.substring(0, idx) + s.substring(idx + part.length()); + public String removeOccurrences(String s, String part) { + Stack stack = new Stack<>(); + int n = s.length(); + int partLength = part.length(); + for (int i = 0; i < n; i++) { + stack.push(s.charAt(i)); + if (stack.size() >= partLength && check(stack, part, partLength)) { + for (int j = 0; j < partLength; j++) { + stack.pop(); + } + } + } + StringBuilder sb = new StringBuilder(); + while (!stack.isEmpty()) { + sb.append(stack.pop()); + } + return sb.reverse().toString(); + } + + private boolean check(Stack stack, String part, int partLength) { + Stack temp = new Stack<>(); + temp.addAll(stack); + for (int i = partLength - 1; i >= 0; i--) { + if (temp.isEmpty() || temp.peek() != part.charAt(i)) { + return false; + } + temp.pop(); + } + return true; } - return s; - } } From 2daac9d705fcc126adceb388263b9c526b9961c3 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 11 Feb 2025 17:29:01 -0800 Subject: [PATCH 151/182] Update Max Sum of a Pair With Equal Sum of Digits.java --- ...um of a Pair With Equal Sum of Digits.java | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/Medium/Max Sum of a Pair With Equal Sum of Digits.java b/Medium/Max Sum of a Pair With Equal Sum of Digits.java index 597e0658..1d8d89ae 100644 --- a/Medium/Max Sum of a Pair With Equal Sum of Digits.java +++ b/Medium/Max Sum of a Pair With Equal Sum of Digits.java @@ -1,25 +1,25 @@ class Solution { - public int maximumSum(int[] nums) { - int maxSum = -1; - Map map = new HashMap<>(); - for (int num : nums) { - int digitSum = getDigitSum(num); - if (map.containsKey(digitSum)) { - maxSum = Math.max(maxSum, map.get(digitSum) + num); - map.put(digitSum, Math.max(map.get(digitSum), num)); - } else { - map.put(digitSum, num); - } + public int maximumSum(int[] nums) { + Map map = new HashMap<>(); + int maxSum = -1; + for (int num : nums) { + int digitSum = calculateDigitSum(num); + if (map.containsKey(digitSum)) { + maxSum = Math.max(maxSum, map.get(digitSum) + num); + map.put(digitSum, Math.max(map.get(digitSum), num)); + } else { + map.put(digitSum, num); + } + } + return maxSum; } - return maxSum; - } - - private int getDigitSum(int num) { - int sum = 0; - while (num > 0) { - sum += num % 10; - num /= 10; + + private int calculateDigitSum(int num) { + int sum = 0; + while (num > 0) { + sum += num % 10; + num /= 10; + } + return sum; } - return sum; - } } From 30f21710052e766d53c921aceb97d2b09d79e4a4 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 12 Feb 2025 17:40:13 -0800 Subject: [PATCH 152/182] Create Minimum Operations to Exceed Threshold Value II.java --- ...Operations to Exceed Threshold Value II.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Medium/Minimum Operations to Exceed Threshold Value II.java diff --git a/Medium/Minimum Operations to Exceed Threshold Value II.java b/Medium/Minimum Operations to Exceed Threshold Value II.java new file mode 100644 index 00000000..9a6c2b09 --- /dev/null +++ b/Medium/Minimum Operations to Exceed Threshold Value II.java @@ -0,0 +1,17 @@ +class Solution { + public int minOperations(int[] nums, int k) { + PriorityQueue pq = new PriorityQueue<>(); + for (int num : nums) { + pq.add((long) num); + } + int operations = 0; + while (pq.peek() < k) { + long smallest = pq.poll(); + long secondSmallest = pq.poll(); + long newValue = Math.min(smallest, secondSmallest) * 2 + Math.max(smallest, secondSmallest); + pq.add(newValue); + operations++; + } + return operations; + } +} From 04175b684ba89a52fedb9b8a5ccd9989c2a21c95 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 19 Feb 2025 07:32:27 -0800 Subject: [PATCH 153/182] Create Construct Smallest Number From DI String.java --- .../Construct Smallest Number From DI String.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Medium/Construct Smallest Number From DI String.java diff --git a/Medium/Construct Smallest Number From DI String.java b/Medium/Construct Smallest Number From DI String.java new file mode 100644 index 00000000..64e39262 --- /dev/null +++ b/Medium/Construct Smallest Number From DI String.java @@ -0,0 +1,15 @@ +class Solution { + public String smallestNumber(String pattern) { + StringBuilder result = new StringBuilder(); + Stack stack = new Stack<>(); + for (int i = 0; i <= pattern.length(); i++) { + stack.push(i + 1); + if (i == pattern.length() || pattern.charAt(i) == 'I') { + while (!stack.isEmpty()) { + result.append(stack.pop()); + } + } + } + return result.toString(); + } +} From 5fb999c033b967a78437f39cbb7a09fb302db94b Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 19 Feb 2025 07:37:28 -0800 Subject: [PATCH 154/182] Create The k-th Lexicographical String of All Happy Strings of Length n.java --- ...ring of All Happy Strings of Length n.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Medium/The k-th Lexicographical String of All Happy Strings of Length n.java diff --git a/Medium/The k-th Lexicographical String of All Happy Strings of Length n.java b/Medium/The k-th Lexicographical String of All Happy Strings of Length n.java new file mode 100644 index 00000000..413b67d5 --- /dev/null +++ b/Medium/The k-th Lexicographical String of All Happy Strings of Length n.java @@ -0,0 +1,28 @@ +class Solution { + private static final char[] CHARS = {'a', 'b', 'c'}; + + public String getHappyString(int n, int k) { + Set set = new HashSet<>(); + backtrack(set, new StringBuilder(), n); + if (set.size() < k) { + return ""; + } + List list = new ArrayList<>(set); + Collections.sort(list); + return list.get(k - 1); + } + + private void backtrack(Set set, StringBuilder sb, int n) { + if (sb.length() == n) { + set.add(sb.toString()); + return; + } + for (char c : CHARS) { + if (sb.isEmpty() || sb.charAt(sb.length() - 1) != c) { + sb.append(c); + backtrack(set, sb, n); + sb.deleteCharAt(sb.length() - 1); + } + } + } +} From 50b0cb2ebb75524dc7241d8bc89c8c065ed739e3 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 20 Feb 2025 09:03:42 -0800 Subject: [PATCH 155/182] Create Find Unique Binary String.java --- Medium/Find Unique Binary String.java | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Medium/Find Unique Binary String.java diff --git a/Medium/Find Unique Binary String.java b/Medium/Find Unique Binary String.java new file mode 100644 index 00000000..80cdfa9e --- /dev/null +++ b/Medium/Find Unique Binary String.java @@ -0,0 +1,25 @@ +class Solution { + + private static final char[] BINARY_CHARS = {'1', '0'}; + + public String findDifferentBinaryString(String[] nums) { + int n = nums.length; + Set binaryStrings = new HashSet<>(); + backtrack(new StringBuilder(), n, binaryStrings); + Set binaryStringsPresent = Arrays.stream(nums).collect(Collectors.toSet()); + binaryStrings.removeAll(binaryStringsPresent); + return binaryStrings.isEmpty() ? "" : binaryStrings.iterator().next(); + } + + private void backtrack(StringBuilder sb, int n, Set binaryStrings) { + if (sb.length() == n) { + binaryStrings.add(sb.toString()); + return; + } + for (char c : BINARY_CHARS) { + sb.append(c); + backtrack(sb, n, binaryStrings); + sb.deleteCharAt(sb.length() - 1); + } + } +} From c1ff60a4007603b312912ca49122646f8daa8cf3 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 22 Feb 2025 07:33:11 -0800 Subject: [PATCH 156/182] Update Recover a Tree From Preorder Traversal.java --- ...ecover a Tree From Preorder Traversal.java | 56 ++++++++++--------- 1 file changed, 30 insertions(+), 26 deletions(-) diff --git a/Hard/Recover a Tree From Preorder Traversal.java b/Hard/Recover a Tree From Preorder Traversal.java index 69f3fe55..b851ca44 100644 --- a/Hard/Recover a Tree From Preorder Traversal.java +++ b/Hard/Recover a Tree From Preorder Traversal.java @@ -4,41 +4,45 @@ * int val; * TreeNode left; * TreeNode right; - * TreeNode(int x) { val = x; } + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } * } */ class Solution { - public TreeNode recoverFromPreorder(String S) { - Map map = new HashMap<>(); + public TreeNode recoverFromPreorder(String traversal) { + Stack stack = new Stack<>(); int idx = 0; - int n = S.length(); - - while (idx < n) { - int level = 0; - StringBuilder sb = new StringBuilder(); - - while (idx < n && S.charAt(idx) == '-') { - level++; + while (idx < traversal.length()) { + int depth = 0; + while (idx < traversal.length() && traversal.charAt(idx) == '-') { + depth++; idx++; } - - while (idx < n && Character.isDigit(S.charAt(idx))) { - sb.append(S.charAt(idx++)); + int value = 0; + while (idx < traversal.length() && Character.isDigit(traversal.charAt(idx))) { + value = value * 10 + Character.getNumericValue(traversal.charAt(idx++)); } - - TreeNode currNode = new TreeNode(Integer.parseInt(sb.toString())); - map.put(level, currNode); - if (level > 0) { - TreeNode parent = map.get(level - 1); - if (parent.left == null) { - parent.left = currNode; - } - else { - parent.right = currNode; + TreeNode node = new TreeNode(value); + while (stack.size() > depth) { + stack.pop(); + } + if (!stack.isEmpty()) { + if (stack.peek().left == null) { + stack.peek().left = node; + } else { + stack.peek().right = node; } } + stack.push(node); + } + while (stack.size() > 1) { + stack.pop(); } - - return map.get(0); + return stack.peek(); } } From c25f01b2f86ae67c45d919b9174559184e163564 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 23 Feb 2025 10:38:59 -0800 Subject: [PATCH 157/182] Create Construct Binary Tree from Preorder and Postorder Traversal.java --- ...from Preorder and Postorder Traversal.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Medium/Construct Binary Tree from Preorder and Postorder Traversal.java diff --git a/Medium/Construct Binary Tree from Preorder and Postorder Traversal.java b/Medium/Construct Binary Tree from Preorder and Postorder Traversal.java new file mode 100644 index 00000000..ca7aa35d --- /dev/null +++ b/Medium/Construct Binary Tree from Preorder and Postorder Traversal.java @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode constructFromPrePost(int[] preorder, int[] postorder) { + int n = preorder.length; + Map postorderIndex = new HashMap<>(); + for (int i = 0; i < n; i++) { + postorderIndex.put(postorder[i], i); + } + return constructTree(0, n - 1, 0, preorder, postorderIndex); + } + + private TreeNode constructTree(int preStart, int preEnd, int postStart, int[] preorder, Map postorderIndex) { + if (preStart > preEnd) { + return null; + } + if (preStart == preEnd) { + return new TreeNode(preorder[preStart]); + } + int leftRoot = preorder[preStart + 1]; + int leftCount = postorderIndex.get(leftRoot) - postStart + 1; + TreeNode root = new TreeNode(preorder[preStart]); + root.left = constructTree(preStart + 1, preStart + leftCount, postStart, preorder, postorderIndex); + root.right = constructTree(preStart + leftCount + 1, preEnd, postStart + leftCount, preorder, postorderIndex); + return root; + } +} From 88ecb654b06441c1414888c2b0994fa092cd693e Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 1 Mar 2025 09:10:57 -0800 Subject: [PATCH 158/182] Update Apply Operations to an Array.java --- Easy/Apply Operations to an Array.java | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/Easy/Apply Operations to an Array.java b/Easy/Apply Operations to an Array.java index b0a663a2..3b2bca86 100644 --- a/Easy/Apply Operations to an Array.java +++ b/Easy/Apply Operations to an Array.java @@ -1,21 +1,20 @@ class Solution { public int[] applyOperations(int[] nums) { - for (int i = 0; i < nums.length - 1; i++) { + int n = nums.length; + for (int i = 0; i < n - 1; i++) { if (nums[i] == nums[i + 1]) { nums[i] *= 2; nums[i + 1] = 0; } } - int startIdx = 0; - int endIdx = 0; - while (endIdx < nums.length) { - if (nums[endIdx] != 0) { - nums[startIdx++] = nums[endIdx]; + int start = 0; + for (int i = 0; i < n; i++) { + if (nums[i] != 0) { + nums[start++] = nums[i]; } - endIdx++; } - while (startIdx < nums.length) { - nums[startIdx++] = 0; + while (start < n) { + nums[start++] = 0; } return nums; } From 7e86b13cd7f4381cde89fb4c4302b48cd9ca336b Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 5 Mar 2025 09:49:51 -0800 Subject: [PATCH 159/182] Create Count Total Number of Colored Cells.java --- Medium/Count Total Number of Colored Cells.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Medium/Count Total Number of Colored Cells.java diff --git a/Medium/Count Total Number of Colored Cells.java b/Medium/Count Total Number of Colored Cells.java new file mode 100644 index 00000000..81c10a8c --- /dev/null +++ b/Medium/Count Total Number of Colored Cells.java @@ -0,0 +1,11 @@ +class Solution { + public long coloredCells(int n) { + long count = 1; + int increment = 4; + while (n-- > 1) { + count += increment; + increment += 4; + } + return count; + } +} From 72f877e6ebf35519842c65e03815c4a3ae74274c Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 9 Mar 2025 12:03:46 -0700 Subject: [PATCH 160/182] Create Fruits Into Baskets II.java --- Easy/Fruits Into Baskets II.java | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Easy/Fruits Into Baskets II.java diff --git a/Easy/Fruits Into Baskets II.java b/Easy/Fruits Into Baskets II.java new file mode 100644 index 00000000..e0afa848 --- /dev/null +++ b/Easy/Fruits Into Baskets II.java @@ -0,0 +1,20 @@ +class Solution { + public int numOfUnplacedFruits(int[] fruits, int[] baskets) { + int count = 0; + for (int fruit : fruits) { + int idx = -1; + for (int i = 0; i < baskets.length; i++) { + if (baskets[i] >= fruit) { + idx = i; + break; + } + } + if (idx == -1) { + count++; + } else { + baskets[idx] = -1; + } + } + return count; + } +} From 8ed8a35ed86218a68f9211ab2c2495a20c951a68 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 19 Mar 2025 06:48:37 -0700 Subject: [PATCH 161/182] Create Maximum Unique Subarray Sum After Deletion.java --- ...imum Unique Subarray Sum After Deletion.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Easy/Maximum Unique Subarray Sum After Deletion.java diff --git a/Easy/Maximum Unique Subarray Sum After Deletion.java b/Easy/Maximum Unique Subarray Sum After Deletion.java new file mode 100644 index 00000000..e0a6a2ae --- /dev/null +++ b/Easy/Maximum Unique Subarray Sum After Deletion.java @@ -0,0 +1,17 @@ +class Solution { + public int maxSum(int[] nums) { + int max = nums[0]; + int sum = 0; + Set set = new HashSet<>(); + for (int num : nums) { + max = Math.max(num, max); + if (num > 0 && set.add(num)) { + sum += num; + } + } + if (max < 0) { + return max; + } + return sum; + } +} From f70a266f0ed726909b5228b54184c48081e4b6ee Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 20 Mar 2025 07:48:37 -0700 Subject: [PATCH 162/182] Create Design Spreadsheet.java --- Medium/Design Spreadsheet.java | 47 ++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Medium/Design Spreadsheet.java diff --git a/Medium/Design Spreadsheet.java b/Medium/Design Spreadsheet.java new file mode 100644 index 00000000..e41fc142 --- /dev/null +++ b/Medium/Design Spreadsheet.java @@ -0,0 +1,47 @@ +class Spreadsheet { + + private final Map> sheet; + + public Spreadsheet(int rows) { + sheet = new HashMap<>(); + for (char c = 'A'; c <= 'Z'; c++) { + sheet.put(c, new HashMap<>()); + } + } + + public void setCell(String cell, int value) { + char column = cell.charAt(0); + int rowNumber = Integer.parseInt(cell.substring(1)); + Map row = sheet.get(column); + row.put(rowNumber, value); + } + + public void resetCell(String cell) { + setCell(cell, 0); + } + + public int getValue(String formula) { + String[] split = formula.split("\\+"); + String cellOne = split[0].substring(1); + String cellTwo = split[1]; + return getCellValue(cellOne) + getCellValue(cellTwo); + } + + private int getCellValue(String cell) { + if (!Character.isLetter(cell.charAt(0))) { + return Integer.parseInt(cell); + } + char column = cell.charAt(0); + int rowNumber = Integer.parseInt(cell.substring(1)); + Map row = sheet.get(column); + return row.getOrDefault(rowNumber, 0); + } +} + +/** + * Your Spreadsheet object will be instantiated and called as such: + * Spreadsheet obj = new Spreadsheet(rows); + * obj.setCell(cell,value); + * obj.resetCell(cell); + * int param_3 = obj.getValue(formula); + */ From 79fab170a7e6dbe64afb009018de192c97e49dc2 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 22 Mar 2025 16:51:49 -0700 Subject: [PATCH 163/182] Create Count the Number of Complete Components.java --- ...unt the Number of Complete Components.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Medium/Count the Number of Complete Components.java diff --git a/Medium/Count the Number of Complete Components.java b/Medium/Count the Number of Complete Components.java new file mode 100644 index 00000000..d198b0b2 --- /dev/null +++ b/Medium/Count the Number of Complete Components.java @@ -0,0 +1,38 @@ +class Solution { + public int countCompleteComponents(int n, int[][] edges) { + Map> graph = new HashMap<>(); + for (int[] edge : edges) { + int nodeOne = edge[0]; + int nodeTwo = edge[1]; + graph.computeIfAbsent(nodeOne, k -> new HashSet<>()).add(nodeTwo); + graph.computeIfAbsent(nodeTwo, k -> new HashSet<>()).add(nodeOne); + } + int count = 0; + Set visited = new HashSet<>(); + for (int i = 0; i < n; i++) { + if (visited.add(i)) { + int[] componentInfo = new int[2]; + dfs(i, graph, visited, componentInfo); + if (componentInfo[0] * (componentInfo[0] - 1) == componentInfo[1]) { + count++; + } + } + } + return count; + } + + private void dfs( + int node, + Map> graph, + Set visited, + int[] componentInfo) { + componentInfo[0]++; + Set connections = graph.getOrDefault(node, new HashSet<>()); + componentInfo[1] += connections.size(); + for (Integer conn : connections) { + if (visited.add(conn)) { + dfs(conn, graph, visited, componentInfo); + } + } + } +} From f09b6a6dcfc4bbd1cb3fe614078cd8141ac05a02 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 23 Mar 2025 08:14:49 -0700 Subject: [PATCH 164/182] Create Maximum Containers on a Ship.java --- Easy/Maximum Containers on a Ship.java | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Easy/Maximum Containers on a Ship.java diff --git a/Easy/Maximum Containers on a Ship.java b/Easy/Maximum Containers on a Ship.java new file mode 100644 index 00000000..e113027d --- /dev/null +++ b/Easy/Maximum Containers on a Ship.java @@ -0,0 +1,8 @@ +class Solution { + public int maxContainers(int n, int w, int maxWeight) { + if (n * n * w <= maxWeight) { + return n * n; + } + return maxWeight / w; + } +} From 0343dfd31a1cc8309b3ea10ed1315c1287b594c5 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 29 Mar 2025 08:02:00 -0700 Subject: [PATCH 165/182] Create Count Days Without Meetings.java --- Medium/Count Days Without Meetings.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Medium/Count Days Without Meetings.java diff --git a/Medium/Count Days Without Meetings.java b/Medium/Count Days Without Meetings.java new file mode 100644 index 00000000..1630e6df --- /dev/null +++ b/Medium/Count Days Without Meetings.java @@ -0,0 +1,24 @@ +class Solution { + public int countDays(int days, int[][] meetings) { + Arrays.sort(meetings, (o1, o2) -> { + int c = Integer.compare(o1[0], o2[0]); + if (c != 0) { + return c; + } + return Integer.compare(o2[1], o1[1]); + }); + int meetingDays = 0; + int idx = 0; + while (idx < meetings.length) { + int start = meetings[idx][0]; + int end = meetings[idx][1]; + idx++; + while (idx < meetings.length && meetings[idx][0] <= end) { + end = Math.max(end, meetings[idx][1]); + idx++; + } + meetingDays += (end - start + 1); + } + return days - meetingDays; + } +} From e6687a6c142a52bdee850192a39b13c70a8e6785 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 30 Mar 2025 07:04:57 -0700 Subject: [PATCH 166/182] Create Reverse Degree of a String.java --- Easy/Reverse Degree of a String.java | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Easy/Reverse Degree of a String.java diff --git a/Easy/Reverse Degree of a String.java b/Easy/Reverse Degree of a String.java new file mode 100644 index 00000000..db8f4e91 --- /dev/null +++ b/Easy/Reverse Degree of a String.java @@ -0,0 +1,9 @@ +class Solution { + public int reverseDegree(String s) { + int result = 0; + for (int i = 0; i < s.length(); i++) { + result += (i + 1) * (26 - (s.charAt(i) - 'a')); + } + return result; + } +} From 6c82d5e37dfb702b58b177185123e545799b0b3f Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 30 Mar 2025 07:15:26 -0700 Subject: [PATCH 167/182] Create Minimum Cost to Reach Every Position.java --- Easy/Minimum Cost to Reach Every Position.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Easy/Minimum Cost to Reach Every Position.java diff --git a/Easy/Minimum Cost to Reach Every Position.java b/Easy/Minimum Cost to Reach Every Position.java new file mode 100644 index 00000000..1b142d2c --- /dev/null +++ b/Easy/Minimum Cost to Reach Every Position.java @@ -0,0 +1,13 @@ +class Solution { + public int[] minCosts(int[] cost) { + int n = cost.length; + int[] result = new int[n]; + int minCost = Integer.MAX_VALUE; + for (int i = 0; i < n; i++) { + int curr = cost[i]; + minCost = Math.min(minCost, curr); + result[i] = minCost; + } + return result; + } +} From d607cf25ba1d4a4f13c5a7a8ad2e709571352bbe Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 13 Apr 2025 11:12:22 -0700 Subject: [PATCH 168/182] Create Find Closest Person.java --- Easy/Find Closest Person.java | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Easy/Find Closest Person.java diff --git a/Easy/Find Closest Person.java b/Easy/Find Closest Person.java new file mode 100644 index 00000000..0d178230 --- /dev/null +++ b/Easy/Find Closest Person.java @@ -0,0 +1,7 @@ +class Solution { + public int findClosest(int x, int y, int z) { + int diffOne = Math.abs(x - z); + int diffTwo = Math.abs(y - z); + return diffOne == diffTwo ? 0 : (diffOne < diffTwo ? 1 : 2); + } +} From f0117cca3526851eaf7192572f6ba92415fbddac Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sun, 13 Apr 2025 11:13:49 -0700 Subject: [PATCH 169/182] Create Minimum Operations to Make Array Sum Divisible by K.java --- ...imum Operations to Make Array Sum Divisible by K.java | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Easy/Minimum Operations to Make Array Sum Divisible by K.java diff --git a/Easy/Minimum Operations to Make Array Sum Divisible by K.java b/Easy/Minimum Operations to Make Array Sum Divisible by K.java new file mode 100644 index 00000000..c941b50a --- /dev/null +++ b/Easy/Minimum Operations to Make Array Sum Divisible by K.java @@ -0,0 +1,9 @@ +class Solution { + public int minOperations(int[] nums, int k) { + int sum = 0; + for (int num : nums) { + sum += num; + } + return sum % k; + } +} From 4a81fa982c607d1d900c5f988599219cc82e8ad3 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 15 Apr 2025 07:17:29 -0700 Subject: [PATCH 170/182] Update Count Symmetric Integers.java --- Easy/Count Symmetric Integers.java | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/Easy/Count Symmetric Integers.java b/Easy/Count Symmetric Integers.java index f32301e1..8ae9c320 100644 --- a/Easy/Count Symmetric Integers.java +++ b/Easy/Count Symmetric Integers.java @@ -1,17 +1,27 @@ class Solution { public int countSymmetricIntegers(int low, int high) { - int result = 0; + int count = 0; for (int i = low; i <= high; i++) { - String s = String.valueOf(i); - int diff = 0; - int n = s.length(); - for (int j = 0; j < n / 2; j++) { - diff += s.charAt(j) - s.charAt(n - j - 1); - } - if (n % 2 == 0 && diff == 0) { - result++; + if (isSymmetric(i)) { + count++; } } - return result; + return count; + } + + private static boolean isSymmetric(int num) { + String s = String.valueOf(num); + int n = s.length(); + if (n % 2 != 0) { + return false; + } + int sum = 0; + for (int i = 0; i < n / 2; i++) { + sum += Character.getNumericValue(s.charAt(i)); + } + for (int i = n / 2; i < n; i++) { + sum -= Character.getNumericValue(s.charAt(i)); + } + return sum == 0; } } From f37ed97923b5e909813df92781a15828b1386986 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 26 Apr 2025 08:55:01 -0700 Subject: [PATCH 171/182] Create Calculate Score After Performing Instructions.java --- ...e Score After Performing Instructions.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Medium/Calculate Score After Performing Instructions.java diff --git a/Medium/Calculate Score After Performing Instructions.java b/Medium/Calculate Score After Performing Instructions.java new file mode 100644 index 00000000..789e5669 --- /dev/null +++ b/Medium/Calculate Score After Performing Instructions.java @@ -0,0 +1,19 @@ +class Solution { + public long calculateScore(String[] instructions, int[] values) { + long result = 0; + int n = values.length; + int idx = 0; + Set executed = new HashSet<>(); + while (idx < n && idx >= 0) { + if (!executed.add(idx)) { + break; + } + if (instructions[idx].equals("add")) { + result += values[idx++]; + } else { + idx += values[idx]; + } + } + return result; + } +} From 96a5d01cded0218a8c4c9e97d1fd5230ce1e23ef Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 7 May 2025 06:01:01 -0700 Subject: [PATCH 172/182] Create Find Minimum Time to Reach Last Room I.java --- ...ind Minimum Time to Reach Last Room I.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Medium/Find Minimum Time to Reach Last Room I.java diff --git a/Medium/Find Minimum Time to Reach Last Room I.java b/Medium/Find Minimum Time to Reach Last Room I.java new file mode 100644 index 00000000..0247baa4 --- /dev/null +++ b/Medium/Find Minimum Time to Reach Last Room I.java @@ -0,0 +1,36 @@ +class Solution { + + private static final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; + + public int minTimeToReach(int[][] moveTime) { + int n = moveTime.length; + int m = moveTime[0].length; + boolean[][] visited = new boolean[n][m]; + Integer[][] minTime = new Integer[n][m]; + minTime[0][0] = 0; + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[2] - b[2]); + pq.add(new int[]{0, 0, 0}); + while (!pq.isEmpty()) { + int[] removed = pq.remove(); + int x = removed[0]; + int y = removed[1]; + if (visited[x][y]) { + continue; + } + visited[x][y] = true; + for (int[] dir : DIRS) { + int newX = x + dir[0]; + int newY = y + dir[1]; + if (newX >= 0 && newY >= 0 && newX < n && newY < m) { + int distance = Math.max(minTime[x][y], moveTime[newX][newY]) + 1; + int currMinTime = minTime[newX][newY] == null ? Integer.MAX_VALUE : minTime[newX][newY]; + if (currMinTime > distance) { + minTime[newX][newY] = distance; + pq.add(new int[]{newX, newY, distance}); + } + } + } + } + return minTime[n - 1][m - 1]; + } +} From c7c43dc18b8be8ebbc54ebd7a1f528e83aab85eb Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 8 May 2025 07:06:50 -0700 Subject: [PATCH 173/182] Create Maximum Product of Two Digits.java --- Easy/Maximum Product of Two Digits.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Easy/Maximum Product of Two Digits.java diff --git a/Easy/Maximum Product of Two Digits.java b/Easy/Maximum Product of Two Digits.java new file mode 100644 index 00000000..c61f3c3a --- /dev/null +++ b/Easy/Maximum Product of Two Digits.java @@ -0,0 +1,17 @@ +class Solution { + public int maxProduct(int n) { + int maximum = Integer.MIN_VALUE; + int secondMaximum = Integer.MIN_VALUE; + while (n > 0) { + int num = n % 10; + n /= 10; + if (num > maximum) { + secondMaximum = maximum; + maximum = num; + } else if (num > secondMaximum) { + secondMaximum = num; + } + } + return maximum * secondMaximum; + } +} From 0209afb33cd40797aa03707328030e2b0a8d9f5f Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 14 May 2025 06:24:41 -0700 Subject: [PATCH 174/182] Create Total Characters in String After Transformations I.java --- ...ers in String After Transformations I.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Medium/Total Characters in String After Transformations I.java diff --git a/Medium/Total Characters in String After Transformations I.java b/Medium/Total Characters in String After Transformations I.java new file mode 100644 index 00000000..3751ab7e --- /dev/null +++ b/Medium/Total Characters in String After Transformations I.java @@ -0,0 +1,25 @@ +class Solution { + + private static final int MOD = 1000_0000_07; + + public int lengthAfterTransformations(String s, int t) { + int[] frequency = new int[26]; + for (char c : s.toCharArray()) { + frequency[c - 'a']++; + } + for (int round = 0; round < t; round++) { + int[] next = new int[26]; + next[0] = frequency[25]; // Transformation from 'z' + next[1] = (frequency[25] + frequency[0]) % MOD; // Transformation from either 'z' or 'a' + for (int i = 2; i < 26; i++) { + next[i] = frequency[i - 1]; // Transformation for next character + } + frequency = next; + } + int result = 0; + for (int i = 0; i < 26; i++) { + result = (result + frequency[i]) % MOD; + } + return result; + } +} From 52620f41b903dc8c26ca32aa1e7877eec199dd8b Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 20 May 2025 07:15:08 -0700 Subject: [PATCH 175/182] Create Zero Array Transformation I.java --- Medium/Zero Array Transformation I.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Medium/Zero Array Transformation I.java diff --git a/Medium/Zero Array Transformation I.java b/Medium/Zero Array Transformation I.java new file mode 100644 index 00000000..2b9ab602 --- /dev/null +++ b/Medium/Zero Array Transformation I.java @@ -0,0 +1,24 @@ +class Solution { + public boolean isZeroArray(int[] nums, int[][] queries) { + int n = nums.length; + int[] diff = new int[n + 1]; + for (int[] query : queries) { + int left = query[0]; + int right = query[1]; + diff[left] += 1; + diff[right + 1] -= 1; + } + int[] operation = new int[n + 1]; + int currOperation = 0; + for (int i = 0; i < n + 1; i++) { + currOperation += diff[i]; + operation[i] = currOperation; + } + for (int i = 0; i < n; i++) { + if (operation[i] < nums[i]) { + return false; + } + } + return true; + } +} From 96489b1a30e6f271468b065dd0d439aaef04e679 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Mon, 2 Jun 2025 07:06:56 -0700 Subject: [PATCH 176/182] Create Distribute Candies Among Children II.java --- Medium/Distribute Candies Among Children II.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Medium/Distribute Candies Among Children II.java diff --git a/Medium/Distribute Candies Among Children II.java b/Medium/Distribute Candies Among Children II.java new file mode 100644 index 00000000..aa9648f2 --- /dev/null +++ b/Medium/Distribute Candies Among Children II.java @@ -0,0 +1,14 @@ +class Solution { + public long distributeCandies(int n, int limit) { + long result = 0; + for (int i = 0; i <= Math.min(limit, n); i++) { + // distribution not possible as we will have to allocate at least one child with + // more than limit candies + if (n - i > 2 * limit) { + continue; + } + result += Math.min(n - i, limit) - Math.max(0, n - i - limit) + 1; + } + return result; + } +} From 78832b33f37b1fc3b850ec08f957e069868ae80f Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 3 Jun 2025 07:21:58 -0700 Subject: [PATCH 177/182] Create Find Minimum Log Transportation Cost.java --- Easy/Find Minimum Log Transportation Cost.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Easy/Find Minimum Log Transportation Cost.java diff --git a/Easy/Find Minimum Log Transportation Cost.java b/Easy/Find Minimum Log Transportation Cost.java new file mode 100644 index 00000000..3820474e --- /dev/null +++ b/Easy/Find Minimum Log Transportation Cost.java @@ -0,0 +1,12 @@ +class Solution { + public long minCuttingCost(int n, int m, int k) { + long cost = 0; + if (n > k) { + cost += ((long) (n - k)) * (k); + } + if (m > k) { + cost += ((long) (m - k)) * (k); + } + return cost; + } +} From a15f0c915355221f247be1e23057c46a10ad29e7 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 3 Jun 2025 07:30:09 -0700 Subject: [PATCH 178/182] Create Resulting String After Adjacent Removals.java --- ...ulting String After Adjacent Removals.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Medium/Resulting String After Adjacent Removals.java diff --git a/Medium/Resulting String After Adjacent Removals.java b/Medium/Resulting String After Adjacent Removals.java new file mode 100644 index 00000000..efa43bf6 --- /dev/null +++ b/Medium/Resulting String After Adjacent Removals.java @@ -0,0 +1,21 @@ +class Solution { + public String resultingString(String s) { + Stack stack = new Stack<>(); + for (char c : s.toCharArray()) { + if (!stack.isEmpty() && isAdjacent(stack.peek(), c)) { + stack.pop(); + } else { + stack.push(c); + } + } + StringBuilder result = new StringBuilder(); + for (char c : stack) { + result.append(c); + } + return result.toString(); + } + + private static boolean isAdjacent(char first, char second) { + return Math.abs(first - second) == 1 || (first == 'a' && second == 'z') || (first == 'z' && second == 'a'); + } +} From 89afcc3436620718196217d9f17e04054350c692 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 4 Jun 2025 10:06:43 -0700 Subject: [PATCH 179/182] Create Find the Lexicographically Largest String From the Box I.java --- ...raphically Largest String From the Box I.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Medium/Find the Lexicographically Largest String From the Box I.java diff --git a/Medium/Find the Lexicographically Largest String From the Box I.java b/Medium/Find the Lexicographically Largest String From the Box I.java new file mode 100644 index 00000000..1133cb93 --- /dev/null +++ b/Medium/Find the Lexicographically Largest String From the Box I.java @@ -0,0 +1,16 @@ +class Solution { + public String answerString(String word, int numFriends) { + if (numFriends == 1) { + return word; + } + int n = word.length(); + String result = ""; + for (int i = 0; i < n; i++) { + String curr = word.substring(i, Math.min(i + n - numFriends + 1, n)); + if (result.compareTo(curr) <= 0) { + result = curr; + } + } + return result; + } +} From b962419d92bbd2d824f9c3a624416d0ff4ed6ff6 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 5 Jun 2025 06:20:55 -0700 Subject: [PATCH 180/182] Update Lexicographically Smallest Equivalent String.java --- ...raphically Smallest Equivalent String.java | 69 +++++++++++-------- 1 file changed, 42 insertions(+), 27 deletions(-) diff --git a/Medium/Lexicographically Smallest Equivalent String.java b/Medium/Lexicographically Smallest Equivalent String.java index c5856615..f4d01c21 100644 --- a/Medium/Lexicographically Smallest Equivalent String.java +++ b/Medium/Lexicographically Smallest Equivalent String.java @@ -1,31 +1,46 @@ class Solution { - public String smallestEquivalentString(String s1, String s2, String baseStr) { - int[] graph = new int[26]; - for (int i = 0; i < 26; i++) { - graph[i] = i; + public String smallestEquivalentString(String s1, String s2, String baseStr) { + UnionFind unionFind = new UnionFind(26); + for (int i = 0; i < s1.length(); i++) { + char c1 = s1.charAt(i); + char c2 = s2.charAt(i); + unionFind.union(c1 - 'a', c2 - 'a'); + } + StringBuilder result = new StringBuilder(); + for (char c : baseStr.toCharArray()) { + result.append((char) (unionFind.find(c - 'a') + 'a')); + } + return result.toString(); } - for (int i = 0; i < s1.length(); i++) { - int idxOne = s1.charAt(i) - 'a'; - int idxTwo = s2.charAt(i) - 'a'; - int parentOne = find(graph, idxOne); - int parentTwo = find(graph, idxTwo); - if(parentOne < parentTwo) { - graph[parentTwo] = parentOne; - } else { - graph[parentOne] = parentTwo; - } + + class UnionFind { + private int[] parent; + + public UnionFind(int n) { + parent = new int[n]; + for (int i = 0; i < n; i++) { + parent[i] = i; + } + } + + public int find(int node) { + if (parent[node] == node) { + return node; + } + parent[node] = find(parent[node]); + return parent[node]; + } + + public void union(int nodeOne, int nodeTwo) { + int parentOne = find(nodeOne); + int parentTwo = find(nodeTwo); + if (parentOne != parentTwo) { + if (parentOne < parentTwo) { + parent[parentTwo] = parentOne; + } else { + parent[parentOne] = parentTwo; + } + } + } } - StringBuilder sb = new StringBuilder(); - for (char c : baseStr.toCharArray()) { - sb.append((char) ('a' + find(graph, c - 'a'))); - } - return sb.toString(); - } - - private int find(int[] graph, int idx) { - while(graph[idx] != idx) { - idx = graph[idx]; - } - return idx; - } } From da789bdd18417daf8dae61d377cfcd0b751d9ad3 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 6 Jun 2025 10:27:44 -0700 Subject: [PATCH 181/182] Create Using a Robot to Print the Lexicographically Smallest String.java --- ...the Lexicographically Smallest String.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Medium/Using a Robot to Print the Lexicographically Smallest String.java diff --git a/Medium/Using a Robot to Print the Lexicographically Smallest String.java b/Medium/Using a Robot to Print the Lexicographically Smallest String.java new file mode 100644 index 00000000..8d9c2064 --- /dev/null +++ b/Medium/Using a Robot to Print the Lexicographically Smallest String.java @@ -0,0 +1,31 @@ +class Solution { + public String robotWithString(String s) { + int[] counter = new int[26]; + for (char c : s.toCharArray()) { + counter[c - 'a']++; + } + Stack stack = new Stack<>(); + StringBuilder sb = new StringBuilder(); + for (char c : s.toCharArray()) { + stack.push(c); + counter[c - 'a']--; + while (!stack.isEmpty() && isSmallest(stack.peek(), counter)) { + sb.append(stack.pop()); + } + } + while (!stack.isEmpty()) { + sb.append(stack.pop()); + } + return sb.toString(); + } + + private boolean isSmallest(char c, int[] counter) { + int limit = c - 'a'; + for (int i = 0; i < limit; i++) { + if (counter[i] > 0) { + return false; + } + } + return true; + } +} From c91e3403fb904d4f4a127e339adb252849377872 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Sat, 7 Jun 2025 06:22:41 -0700 Subject: [PATCH 182/182] Create Lexicographically Minimum String After Removing Stars.java --- ...y Minimum String After Removing Stars.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Medium/Lexicographically Minimum String After Removing Stars.java diff --git a/Medium/Lexicographically Minimum String After Removing Stars.java b/Medium/Lexicographically Minimum String After Removing Stars.java new file mode 100644 index 00000000..794ee712 --- /dev/null +++ b/Medium/Lexicographically Minimum String After Removing Stars.java @@ -0,0 +1,28 @@ +class Solution { + public String clearStars(String s) { + Deque[] count = new Deque[26]; + for (int i = 0; i < 26; i++) { + count[i] = new ArrayDeque<>(); + } + char[] letters = s.toCharArray(); + for (int i = 0; i < letters.length; i++) { + if (letters[i] != '*') { + count[letters[i] - 'a'].push(i); + } else { + for (int j = 0; j < 26; j++) { + if (!count[j].isEmpty()) { + letters[count[j].pop()] = '*'; + break; + } + } + } + } + StringBuilder sb = new StringBuilder(); + for (char c : letters) { + if (c != '*') { + sb.append(c); + } + } + return sb.toString(); + } +}