├── 0001-two-sum ├── 0001-two-sum.cpp ├── 0001-two-sum.java ├── 0001-two-sum.js ├── 0001-two-sum.py └── README.md ├── 0003-longest-substring-without-repeating-characters ├── 0003-longest-substring-without-repeating-characters.cpp ├── 0003-longest-substring-without-repeating-characters.java ├── 0003-longest-substring-without-repeating-characters.js ├── 0003-longest-substring-without-repeating-characters.py └── README.md ├── 0005-longest-palindromic-substring ├── 0005-longest-palindromic-substring.cpp ├── 0005-longest-palindromic-substring.java ├── 0005-longest-palindromic-substring.js ├── 0005-longest-palindromic-substring.py └── README.md ├── 0011-container-with-most-water ├── 0011-container-with-most-water.cpp ├── 0011-container-with-most-water.java ├── 0011-container-with-most-water.js ├── 0011-container-with-most-water.py └── README.md ├── 0015-3sum ├── 0015-3sum.cpp ├── 0015-3sum.java ├── 0015-3sum.js ├── 0015-3sum.py └── README.md ├── 0019-remove-nth-node-from-end-of-list ├── 0019-remove-nth-node-from-end-of-list.cpp ├── 0019-remove-nth-node-from-end-of-list.java ├── 0019-remove-nth-node-from-end-of-list.js ├── 0019-remove-nth-node-from-end-of-list.py └── README.md ├── 0020-valid-parentheses ├── 0020-valid-parentheses.cpp ├── 0020-valid-parentheses.java ├── 0020-valid-parentheses.js ├── 0020-valid-parentheses.py └── README.md ├── 0021-merge-two-sorted-lists ├── 0021-merge-two-sorted-lists.cpp ├── 0021-merge-two-sorted-lists.java ├── 0021-merge-two-sorted-lists.js ├── 0021-merge-two-sorted-lists.py └── README.md ├── 0023-merge-k-sorted-lists ├── 0023-merge-k-sorted-lists.cpp ├── 0023-merge-k-sorted-lists.java ├── 0023-merge-k-sorted-lists.js ├── 0023-merge-k-sorted-lists.py └── README.md ├── 0033-search-in-rotated-sorted-array ├── 0033-search-in-rotated-sorted-array.cpp ├── 0033-search-in-rotated-sorted-array.java ├── 0033-search-in-rotated-sorted-array.js ├── 0033-search-in-rotated-sorted-array.py └── README.md ├── 0039-combination-sum ├── 0039-combination-sum.cpp ├── 0039-combination-sum.java ├── 0039-combination-sum.js ├── 0039-combination-sum.py └── README.md ├── 0048-rotate-image ├── 0048-rotate-image.cpp ├── 0048-rotate-image.java ├── 0048-rotate-image.js ├── 0048-rotate-image.py └── README.md ├── 0049-group-anagrams ├── 0049-group-anagrams.cpp ├── 0049-group-anagrams.java ├── 0049-group-anagrams.js ├── 0049-group-anagrams.py └── README.md ├── 0053-maximum-subarray ├── 0053-maximum-subarray.cpp ├── 0053-maximum-subarray.java ├── 0053-maximum-subarray.js ├── 0053-maximum-subarray.py └── README.md ├── 0054-spiral-matrix ├── 0054-spiral-matrix.cpp ├── 0054-spiral-matrix.java ├── 0054-spiral-matrix.js ├── 0054-spiral-matrix.py └── README.md ├── 0055-jump-game ├── 0055-jump-game.cpp ├── 0055-jump-game.java ├── 0055-jump-game.js ├── 0055-jump-game.py └── README.md ├── 0056-merge-intervals ├── 0056-merge-intervals.cpp ├── 0056-merge-intervals.java ├── 0056-merge-intervals.js ├── 0056-merge-intervals.py └── README.md ├── 0057-insert-interval ├── 0057-insert-interval.cpp ├── 0057-insert-interval.java ├── 0057-insert-interval.js ├── 0057-insert-interval.py └── README.md ├── 0062-unique-paths ├── 0062-unique-paths.cpp ├── 0062-unique-paths.java ├── 0062-unique-paths.js ├── 0062-unique-paths.py └── README.md ├── 0070-climbing-stairs ├── 0070-climbing-stairs.cpp ├── 0070-climbing-stairs.java ├── 0070-climbing-stairs.js ├── 0070-climbing-stairs.py └── README.md ├── 0073-set-matrix-zeroes ├── 0073-set-matrix-zeroes.cpp ├── 0073-set-matrix-zeroes.java ├── 0073-set-matrix-zeroes.js ├── 0073-set-matrix-zeroes.py └── README.md ├── 0076-minimum-window-substring ├── 0076-minimum-window-substring.cpp ├── 0076-minimum-window-substring.java ├── 0076-minimum-window-substring.js ├── 0076-minimum-window-substring.py └── README.md ├── 0079-word-search ├── 0079-word-search.cpp ├── 0079-word-search.java ├── 0079-word-search.js ├── 0079-word-search.py └── README.md ├── 0091-decode-ways ├── 0091-decode-ways.cpp ├── 0091-decode-ways.java ├── 0091-decode-ways.js ├── 0091-decode-ways.py └── README.md ├── 0098-validate-binary-search-tree ├── 0098-validate-binary-search-tree.cpp ├── 0098-validate-binary-search-tree.java ├── 0098-validate-binary-search-tree.js ├── 0098-validate-binary-search-tree.py └── README.md ├── 0100-same-tree ├── 100-same-tree.cpp ├── 100-same-tree.java ├── 100-same-tree.js ├── 100-same-tree.py └── README.md ├── 0102-binary-tree-level-order-traversal ├── 0102-binary-tree-level-order-traversal.cpp ├── 0102-binary-tree-level-order-traversal.java ├── 0102-binary-tree-level-order-traversal.js ├── 0102-binary-tree-level-order-traversal.py └── README.md ├── 0104-maximum-depth-of-binary-tree ├── 0104-maximum-depth-of-binary-tree.cpp ├── 0104-maximum-depth-of-binary-tree.java ├── 0104-maximum-depth-of-binary-tree.js ├── 0104-maximum-depth-of-binary-tree.py └── README.md ├── 0105-construct-binary-tree-from-preorder-and-inorder-traversal ├── 0105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp ├── 0105-construct-binary-tree-from-preorder-and-inorder-traversal.java ├── 0105-construct-binary-tree-from-preorder-and-inorder-traversal.js ├── 0105-construct-binary-tree-from-preorder-and-inorder-traversal.py └── README.md ├── 0121-best-time-to-buy-and-sell-stock ├── 0121-best-time-to-buy-and-sell-stock.cpp ├── 0121-best-time-to-buy-and-sell-stock.java ├── 0121-best-time-to-buy-and-sell-stock.js ├── 0121-best-time-to-buy-and-sell-stock.py └── README.md ├── 0124-binary-tree-maximum-path-sum ├── 0124-binary-tree-maximum-path-sum.cpp ├── 0124-binary-tree-maximum-path-sum.java ├── 0124-binary-tree-maximum-path-sum.js ├── 0124-binary-tree-maximum-path-sum.py └── README.md ├── 0125-valid-palindrome ├── 0125-valid-palindrome.cpp ├── 0125-valid-palindrome.java ├── 0125-valid-palindrome.js ├── 0125-valid-palindrome.py └── README.md ├── 0128-longest-consecutive-sequence ├── 0128-longest-consecutive-sequence.cpp ├── 0128-longest-consecutive-sequence.java ├── 0128-longest-consecutive-sequence.js ├── 0128-longest-consecutive-sequence.py └── README.md ├── 0133-clone-graph ├── 0133-clone-graph.cpp ├── 0133-clone-graph.java ├── 0133-clone-graph.js ├── 0133-clone-graph.py └── README.md ├── 0139-word-break ├── 0139-word-break.cpp ├── 0139-word-break.java ├── 0139-word-break.js ├── 0139-word-break.py └── README.md ├── 0141-linked-list-cycle ├── 0141-linked-list-cycle.cpp ├── 0141-linked-list-cycle.java ├── 0141-linked-list-cycle.js ├── 0141-linked-list-cycle.py └── README.md ├── 0142-linked-list-cycle-ii ├── 0142-linked-list-cycle-ii.cpp ├── 0142-linked-list-cycle-ii.java ├── 0142-linked-list-cycle-ii.js ├── 0142-linked-list-cycle-ii.py └── README.md ├── 0143-reorder-list ├── 0143-reorder-list.cpp ├── 0143-reorder-list.java ├── 0143-reorder-list.js ├── 0143-reorder-list.py └── README.md ├── 0152-maximum-product-subarray ├── 0152-maximum-product-subarray.cpp ├── 0152-maximum-product-subarray.java ├── 0152-maximum-product-subarray.js ├── 0152-maximum-product-subarray.py └── README.md ├── 0153-find-minimum-in-rotated-sorted-array ├── 0153-find-minimum-in-rotated-sorted-array.cpp ├── 0153-find-minimum-in-rotated-sorted-array.java ├── 0153-find-minimum-in-rotated-sorted-array.js ├── 0153-find-minimum-in-rotated-sorted-array.py └── README.md ├── 0167-two-sum-ii-input-array-is-sorted ├── 0167-two-sum-ii-input-array-is-sorted.cpp ├── 0167-two-sum-ii-input-array-is-sorted.java ├── 0167-two-sum-ii-input-array-is-sorted.js ├── 0167-two-sum-ii-input-array-is-sorted.py └── README.md ├── 0190-reverse-bits ├── 0190-reverse-bits.cpp ├── 0190-reverse-bits.java ├── 0190-reverse-bits.js ├── 0190-reverse-bits.py └── README.md ├── 0191-number-of-1-bits ├── 0191-number-of-1-bits.cpp ├── 0191-number-of-1-bits.java ├── 0191-number-of-1-bits.js ├── 0191-number-of-1-bits.py └── README.md ├── 0198-house-robber ├── 0198-house-robber.cpp ├── 0198-house-robber.java ├── 0198-house-robber.js ├── 0198-house-robber.py └── README.md ├── 0200-number-of-islands ├── 0200-number-of-islands.cpp ├── 0200-number-of-islands.java ├── 0200-number-of-islands.js ├── 0200-number-of-islands.py └── README.md ├── 0206-reverse-linked-list ├── 0206-reverse-linked-list.cpp ├── 0206-reverse-linked-list.java ├── 0206-reverse-linked-list.js ├── 0206-reverse-linked-list.py └── README.md ├── 0207-course-schedule ├── 0207-course-schedule.cpp ├── 0207-course-schedule.java ├── 0207-course-schedule.js ├── 0207-course-schedule.py └── README.md ├── 0208-implement-trie-prefix-tree ├── 0208-implement-trie-prefix-tree.cpp ├── 0208-implement-trie-prefix-tree.java ├── 0208-implement-trie-prefix-tree.js ├── 0208-implement-trie-prefix-tree.py └── README.md ├── 0211-design-add-and-search-words-data-structure ├── 0211-design-add-and-search-words-data-structure.cpp ├── 0211-design-add-and-search-words-data-structure.java ├── 0211-design-add-and-search-words-data-structure.js ├── 0211-design-add-and-search-words-data-structure.py └── README.md ├── 0212-word-search-ii ├── 0212-word-search-ii.cpp ├── 0212-word-search-ii.java ├── 0212-word-search-ii.js ├── 0212-word-search-ii.py └── README.md ├── 0213-house-robber-ii ├── 0213-house-robber-ii.cpp ├── 0213-house-robber-ii.java ├── 0213-house-robber-ii.js ├── 0213-house-robber-ii.py └── README.md ├── 0217-contains-duplicate ├── 0217-contains-duplicate.cpp ├── 0217-contains-duplicate.java ├── 0217-contains-duplicate.js ├── 0217-contains-duplicate.py └── README.md ├── 0226-invert-binary-tree ├── 0226-invert-binary-tree.cpp ├── 0226-invert-binary-tree.java ├── 0226-invert-binary-tree.js ├── 0226-invert-binary-tree.py └── README.md ├── 0230-kth-smallest-element-in-a-bst ├── 0230-kth-smallest-element-in-a-bst.cpp ├── 0230-kth-smallest-element-in-a-bst.java ├── 0230-kth-smallest-element-in-a-bst.js ├── 0230-kth-smallest-element-in-a-bst.py └── README.md ├── 0235-lowest-common-ancestor-of-a-binary-search-tree ├── 0235-lowest-common-ancestor-of-a-binary-search-tree.cpp ├── 0235-lowest-common-ancestor-of-a-binary-search-tree.java ├── 0235-lowest-common-ancestor-of-a-binary-search-tree.js ├── 0235-lowest-common-ancestor-of-a-binary-search-tree.py └── README.md ├── 0238-product-of-array-except-self ├── 0238-product-of-array-except-self.cpp ├── 0238-product-of-array-except-self.java ├── 0238-product-of-array-except-self.js ├── 0238-product-of-array-except-self.py └── README.md ├── 0242-valid-anagram ├── 0242-valid-anagram.cpp ├── 0242-valid-anagram.java ├── 0242-valid-anagram.js ├── 0242-valid-anagram.py └── README.md ├── 0252-meeting-rooms ├── 0252-meeting-rooms.cpp ├── 0252-meeting-rooms.java ├── 0252-meeting-rooms.js ├── 0252-meeting-rooms.py └── README.md ├── 0253-meeting-rooms-ii ├── 0253-meeting-rooms-ii.cpp ├── 0253-meeting-rooms-ii.java ├── 0253-meeting-rooms-ii.js ├── 0253-meeting-rooms-ii.py └── README.md ├── 0261-graph-valid-tree ├── 0261-graph-valid-tree.cpp ├── 0261-graph-valid-tree.java ├── 0261-graph-valid-tree.js ├── 0261-graph-valid-tree.py └── README.md ├── 0268-missing-number ├── 0268-missing-number.cpp ├── 0268-missing-number.java ├── 0268-missing-number.js ├── 0268-missing-number.py └── README.md ├── 0269-alien-dictionary ├── 0269-alien-dictionary.cpp ├── 0269-alien-dictionary.java ├── 0269-alien-dictionary.js ├── 0269-alien-dictionary.py └── README.md ├── 0295-find-median-from-data-stream ├── 0295-find-median-from-data-stream.cpp ├── 0295-find-median-from-data-stream.java ├── 0295-find-median-from-data-stream.js ├── 0295-find-median-from-data-stream.py └── README.md ├── 0297-serialize-and-deserialize-binary-tree ├── 0297-serialize-and-deserialize-binary-tree.cpp ├── 0297-serialize-and-deserialize-binary-tree.java ├── 0297-serialize-and-deserialize-binary-tree.js ├── 0297-serialize-and-deserialize-binary-tree.py └── README.md ├── 0300-longest-increasing-subsequence ├── 0300-longest-increasing-subsequence.cpp ├── 0300-longest-increasing-subsequence.java ├── 0300-longest-increasing-subsequence.js ├── 0300-longest-increasing-subsequence.py └── README.md ├── 0322-coin-change ├── 0322-coin-change.cpp ├── 0322-coin-change.java ├── 0322-coin-change.js ├── 0322-coin-change.py └── README.md ├── 0323-number-of-connected-components-in-an-undirected-graph ├── 0323-number-of-connected-components-in-an-undirected-graph.cpp ├── 0323-number-of-connected-components-in-an-undirected-graph.java ├── 0323-number-of-connected-components-in-an-undirected-graph.js ├── 0323-number-of-connected-components-in-an-undirected-graph.py └── README.md ├── 0338-counting-bits ├── 0338-counting-bits.cpp ├── 0338-counting-bits.java ├── 0338-counting-bits.js ├── 0338-counting-bits.py └── README.md ├── 0347-top-k-frequent-elements ├── 0347-top-k-frequent-elements.cpp ├── 0347-top-k-frequent-elements.java ├── 0347-top-k-frequent-elements.js ├── 0347-top-k-frequent-elements.py └── README.md ├── 0371-sum-of-two-integers ├── 0371-sum-of-two-integers.cpp ├── 0371-sum-of-two-integers.java ├── 0371-sum-of-two-integers.js ├── 0371-sum-of-two-integers.py └── README.md ├── 0392-is-subsequence ├── 0392-is-subsequence.cpp ├── 0392-is-subsequence.java ├── 0392-is-subsequence.js ├── 0392-is-subsequence.py └── README.md ├── 0417-pacific-atlantic-water-flow ├── 0417-pacific-atlantic-water-flow.cpp ├── 0417-pacific-atlantic-water-flow.java ├── 0417-pacific-atlantic-water-flow.js ├── 0417-pacific-atlantic-water-flow.py └── README.md ├── 0424-longest-repeating-character-replacement ├── 0424-longest-repeating-character-replacement.cpp ├── 0424-longest-repeating-character-replacement.java ├── 0424-longest-repeating-character-replacement.js ├── 0424-longest-repeating-character-replacement.py └── README.md ├── 0435-non-overlapping-intervals ├── 0435-non-overlapping-intervals.py ├── NonOverlappingIntervals.java ├── README.md ├── nonOverlappingIntervals.cpp └── nonOverlappingIntervals.js ├── 0509-fibonacci-number ├── 0509-fibonacci-number.cpp ├── 0509-fibonacci-number.java ├── 0509-fibonacci-number.js ├── 0509-fibonacci-number.py └── README.md ├── 0572-subtree-of-another-tree ├── 0572-subtree-of-another-tree.cpp ├── 0572-subtree-of-another-tree.java ├── 0572-subtree-of-another-tree.js ├── 0572-subtree-of-another-tree.py └── README.md ├── 0643-maximum-average-subarray-i ├── 0643-maximum-average-subarray-i.cpp ├── 0643-maximum-average-subarray-i.java ├── 0643-maximum-average-subarray-i.js ├── 0643-maximum-average-subarray-i.py └── README.md ├── 0647-palindromic-substrings ├── 0647-palindromic-substrings.cpp ├── 0647-palindromic-substrings.java ├── 0647-palindromic-substrings.js ├── 0647-palindromic-substrings.py └── README.md ├── 0704-binary-search ├── 0704-binary-search.cpp ├── 0704-binary-search.java ├── 0704-binary-search.js ├── 0704-binary-search.py └── README.md ├── 0739-daily-temperatures ├── 0739-daily-temperatures.cpp ├── 0739-daily-temperatures.java ├── 0739-daily-temperatures.js ├── 0739-daily-temperatures.py └── README.md ├── 0876-middle-of-the-linked-list ├── 0876-middle-of-the-linked-list.cpp ├── 0876-middle-of-the-linked-list.java ├── 0876-middle-of-the-linked-list.js ├── 0876-middle-of-the-linked-list.py └── README.md ├── 0881-boats-to-save-people ├── 0881-boats-to-save-people.cpp ├── 0881-boats-to-save-people.java ├── 0881-boats-to-save-people.js ├── 0881-boats-to-save-people.py └── README.md ├── 1143-longest-common-subsequence ├── 1143-longest-common-subsequence.cpp ├── 1143-longest-common-subsequence.java ├── 1143-longest-common-subsequence.js ├── 1143-longest-common-subsequence.py └── README.md └── README.md /0001-two-sum/0001-two-sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | vector twoSum(vector& nums, int target) { 10 | unordered_map hashmap; 11 | 12 | for (int i = 0; i < nums.size(); i++) { 13 | int complement = target - nums[i]; 14 | 15 | if (hashmap.find(complement) != hashmap.end()) { 16 | return {hashmap[complement], i}; 17 | } 18 | 19 | hashmap[nums[i]] = i; 20 | } 21 | throw runtime_error("No two sum solution"); 22 | } 23 | }; 24 | 25 | // Question: https://leetcode.com/problems/two-sum 26 | // Blog: https://blog.unwiredlearning.com/two-sum -------------------------------------------------------------------------------- /0001-two-sum/0001-two-sum.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class Solution { 5 | public int[] twoSum(int[] nums, int target) { 6 | Map hashmap = new HashMap<>(); 7 | 8 | for (int i = 0; i < nums.length; i++) { 9 | int complement = target - nums[i]; 10 | 11 | if (hashmap.containsKey(complement)) { 12 | return new int[] {hashmap.get(complement), i}; 13 | } 14 | 15 | hashmap.put(nums[i], i); 16 | } 17 | throw new IllegalArgumentException("No two sum solution"); 18 | } 19 | } 20 | 21 | // Question: https://leetcode.com/problems/two-sum 22 | // Blog: https://blog.unwiredlearning.com/two-sum -------------------------------------------------------------------------------- /0001-two-sum/0001-two-sum.js: -------------------------------------------------------------------------------- 1 | function twoSum(nums, target) { 2 | const hashmap = new Map(); 3 | 4 | for (let i = 0; i < nums.length; i++) { 5 | const complement = target - nums[i]; 6 | 7 | if (hashmap.has(complement)) { 8 | return [hashmap.get(complement), i]; 9 | } 10 | 11 | hashmap.set(nums[i], i); 12 | } 13 | throw new Error("No two sum solution"); 14 | } 15 | 16 | // Question: https://leetcode.com/problems/two-sum 17 | // Blog: https://blog.unwiredlearning.com/two-sum -------------------------------------------------------------------------------- /0001-two-sum/0001-two-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | hashmap = {} 4 | 5 | for i in range(len(nums)): 6 | complement = target - nums[i] 7 | 8 | if complement in hashmap: 9 | return [hashmap[complement], i] 10 | 11 | hashmap[nums[i]] = i 12 | 13 | 14 | #Question: https://leetcode.com/problems/two-sum 15 | #Blog: https://blog.unwiredlearning.com/two-sum -------------------------------------------------------------------------------- /0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int lengthOfLongestSubstring(string s) { 9 | unordered_map charIndexMap; 10 | int maxLength = 0, left = 0; 11 | 12 | for (int right = 0; right < s.length(); ++right) { 13 | char currentChar = s[right]; 14 | if (charIndexMap.find(currentChar) != charIndexMap.end() && charIndexMap[currentChar] >= left) { 15 | left = charIndexMap[currentChar] + 1; 16 | } 17 | charIndexMap[currentChar] = right; 18 | maxLength = max(maxLength, right - left + 1); 19 | } 20 | 21 | return maxLength; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int lengthOfLongestSubstring(String s) { 3 | Map charIndexMap = new HashMap<>(); 4 | int maxLength = 0, left = 0; 5 | 6 | for (int right = 0; right < s.length(); right++) { 7 | char currentChar = s.charAt(right); 8 | if (charIndexMap.containsKey(currentChar) && charIndexMap.get(currentChar) >= left) { 9 | left = charIndexMap.get(currentChar) + 1; 10 | } 11 | charIndexMap.put(currentChar, right); 12 | maxLength = Math.max(maxLength, right - left + 1); 13 | } 14 | 15 | return maxLength; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.js: -------------------------------------------------------------------------------- 1 | function lengthOfLongestSubstring(s) { 2 | let charIndexMap = new Map(); 3 | let maxLength = 0; 4 | let left = 0; 5 | 6 | for (let right = 0; right < s.length; right++) { 7 | if (charIndexMap.has(s[right]) && charIndexMap.get(s[right]) >= left) { 8 | left = charIndexMap.get(s[right]) + 1; 9 | } 10 | charIndexMap.set(s[right], right); 11 | maxLength = Math.max(maxLength, right - left + 1); 12 | } 13 | 14 | return maxLength; 15 | } 16 | -------------------------------------------------------------------------------- /0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | 4 | # Initialize the pointers and the set 5 | start, end, maxLength = 0, 0, 0 6 | charSet = set() 7 | 8 | while end < len(s): 9 | if s[end] not in charSet: 10 | charSet.add(s[end]) 11 | maxLength = max(maxLength, end - start + 1) 12 | end += 1 13 | else: 14 | charSet.remove(s[start]) 15 | start += 1 16 | 17 | return maxLength 18 | 19 | 20 | #Question: https://leetcode.com/problems/longest-substring-without-repeating-characters 21 | #Blog: https://blog.unwiredlearning.com/longest-substring-without-repeating-characters -------------------------------------------------------------------------------- /0005-longest-palindromic-substring/0005-longest-palindromic-substring.js: -------------------------------------------------------------------------------- 1 | 2 | function longestPalindrome(s) { 3 | const n = s.length; 4 | if (n < 2) { 5 | return s; 6 | } 7 | const dp = Array.from({ length: n }, () => Array(n).fill(false)); 8 | 9 | // Initialize start position and max length of the palindrome 10 | let start = 0, maxLength = 1; 11 | 12 | // Base case: single character palindromes 13 | for (let i = 0; i < n; i++) { 14 | dp[i][i] = true; 15 | } 16 | 17 | // Base case: two-character palindromes 18 | for (let i = 0; i < n - 1; i++) { 19 | if (s[i] === s[i + 1]) { 20 | dp[i][i + 1] = true; 21 | start = i; 22 | maxLength = 2; 23 | } 24 | } 25 | 26 | // General case 27 | for (let length = 3; length <= n; length++) { 28 | for (let i = 0; i < n - length + 1; i++) { 29 | let j = i + length - 1; 30 | if (s[i] === s[j] && dp[i + 1][j - 1]) { 31 | dp[i][j] = true; 32 | start = i; 33 | maxLength = length; 34 | } 35 | } 36 | } 37 | 38 | return s.substring(start, start + maxLength); 39 | } 40 | -------------------------------------------------------------------------------- /0011-container-with-most-water/0011-container-with-most-water.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int maxArea(const std::vector& height) { 6 | int left = 0; 7 | int right = height.size() - 1; 8 | int maxArea = 0; 9 | 10 | while (left < right) { 11 | int area = std::min(height[left], height[right]) * (right - left); 12 | maxArea = std::max(maxArea, area); 13 | 14 | if (height[left] < height[right]) { 15 | left++; 16 | } else { 17 | right--; 18 | } 19 | } 20 | 21 | return maxArea; 22 | } 23 | 24 | int main() { 25 | std::vector height = {1, 8, 6, 2, 5, 4, 8, 3, 7}; 26 | std::cout << "Maximum Area: " << maxArea(height) << std::endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /0011-container-with-most-water/0011-container-with-most-water.java: -------------------------------------------------------------------------------- 1 | public class ContainerWithMostWater { 2 | public static int maxArea(int[] height) { 3 | int left = 0; 4 | int right = height.length - 1; 5 | int maxArea = 0; 6 | 7 | while (left < right) { 8 | int area = Math.min(height[left], height[right]) * (right - left); 9 | maxArea = Math.max(maxArea, area); 10 | 11 | if (height[left] < height[right]) { 12 | left++; 13 | } else { 14 | right--; 15 | } 16 | } 17 | 18 | return maxArea; 19 | } 20 | 21 | public static void main(String[] args) { 22 | int[] height = {1, 8, 6, 2, 5, 4, 8, 3, 7}; 23 | System.out.println("Maximum Area: " + maxArea(height)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /0011-container-with-most-water/0011-container-with-most-water.js: -------------------------------------------------------------------------------- 1 | function maxArea(height) { 2 | let left = 0; 3 | let right = height.length - 1; 4 | let maxArea = 0; 5 | 6 | while (left < right) { 7 | const area = Math.min(height[left], height[right]) * (right - left); 8 | maxArea = Math.max(maxArea, area); 9 | 10 | if (height[left] < height[right]) { 11 | left++; 12 | } else { 13 | right--; 14 | } 15 | } 16 | 17 | return maxArea; 18 | } 19 | 20 | const height = [1, 8, 6, 2, 5, 4, 8, 3, 7]; 21 | console.log("Maximum Area:", maxArea(height)); 22 | -------------------------------------------------------------------------------- /0011-container-with-most-water/0011-container-with-most-water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, height: List[int]) -> int: 3 | left = 0 4 | right = len(height) - 1 5 | maxArea = 0 6 | 7 | # Loop until the left pointer is less than the right pointer 8 | while left < right: 9 | area = min(height[left], height[right]) * (right - left) 10 | maxArea = max(area, maxArea) 11 | 12 | # Move the pointer pointing to the shorter height towards the middle 13 | if height[left] < height[right]: 14 | left += 1 15 | else: 16 | right -= 1 17 | 18 | return maxArea 19 | 20 | 21 | #Question: https://leetcode.com/problems/container-with-most-water 22 | #Blog: https://blog.unwiredlearning.com/container-with-most-water -------------------------------------------------------------------------------- /0015-3sum/0015-3sum.js: -------------------------------------------------------------------------------- 1 | function threeSum(nums) { 2 | nums.sort((a, b) => a - b); 3 | const result = []; 4 | 5 | for (let i = 0; i < nums.length - 2; i++) { 6 | if (i > 0 && nums[i] === nums[i - 1]) { 7 | continue; // Skip duplicates for the first number 8 | } 9 | 10 | let left = i + 1; 11 | let right = nums.length - 1; 12 | 13 | while (left < right) { 14 | const total = nums[i] + nums[left] + nums[right]; 15 | if (total === 0) { 16 | result.push([nums[i], nums[left], nums[right]]); 17 | 18 | while (left < right && nums[left] === nums[left + 1]) { 19 | left++; // Skip duplicates for the second number 20 | } 21 | while (left < right && nums[right] === nums[right - 1]) { 22 | right--; // Skip duplicates for the third number 23 | } 24 | 25 | left++; 26 | right--; 27 | } else if (total < 0) { 28 | left++; 29 | } else { 30 | right--; 31 | } 32 | } 33 | } 34 | 35 | return result; 36 | } -------------------------------------------------------------------------------- /0019-remove-nth-node-from-end-of-list/0019-remove-nth-node-from-end-of-list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct ListNode { 5 | int val; 6 | ListNode* next; 7 | ListNode(int x) : val(x), next(nullptr) {} 8 | }; 9 | 10 | class Solution { 11 | public: 12 | ListNode* removeNthFromEnd(ListNode* head, int n) { 13 | ListNode* dummy = new ListNode(0); 14 | dummy->next = head; 15 | ListNode* slow = dummy; 16 | ListNode* fast = head; 17 | 18 | // Move fast pointer so that the gap between slow and fast is n nodes apart 19 | for (int i = 0; i < n; i++) { 20 | fast = fast->next; 21 | } 22 | 23 | // Move fast to the end, maintaining the gap 24 | while (fast != nullptr) { 25 | fast = fast->next; 26 | slow = slow->next; 27 | } 28 | 29 | // Skip the desired node 30 | slow->next = slow->next->next; 31 | 32 | return dummy->next; 33 | } 34 | }; -------------------------------------------------------------------------------- /0019-remove-nth-node-from-end-of-list/0019-remove-nth-node-from-end-of-list.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | ListNode(int val) { 5 | this.val = val; 6 | } 7 | } 8 | 9 | class Solution { 10 | public ListNode removeNthFromEnd(ListNode head, int n) { 11 | ListNode dummy = new ListNode(0); 12 | dummy.next = head; 13 | ListNode slow = dummy; 14 | ListNode fast = head; 15 | 16 | // Move fast pointer so that the gap between slow and fast is n nodes apart 17 | for (int i = 0; i < n; i++) { 18 | fast = fast.next; 19 | } 20 | 21 | // Move fast to the end, maintaining the gap 22 | while (fast != null) { 23 | fast = fast.next; 24 | slow = slow.next; 25 | } 26 | 27 | // Skip the desired node 28 | slow.next = slow.next.next; 29 | 30 | return dummy.next; 31 | } 32 | } -------------------------------------------------------------------------------- /0019-remove-nth-node-from-end-of-list/0019-remove-nth-node-from-end-of-list.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor(val, next = null) { 3 | this.val = val; 4 | this.next = next; 5 | } 6 | } 7 | 8 | function removeNthFromEnd(head, n) { 9 | let dummy = new ListNode(0); 10 | dummy.next = head; 11 | let slow = dummy; 12 | let fast = head; 13 | 14 | // Move fast pointer so that the gap between slow and fast is n nodes apart 15 | for (let i = 0; i < n; i++) { 16 | fast = fast.next; 17 | } 18 | 19 | // Move fast to the end, maintaining the gap 20 | while (fast !== null) { 21 | fast = fast.next; 22 | slow = slow.next; 23 | } 24 | 25 | // Skip the desired node 26 | slow.next = slow.next.next; 27 | 28 | return dummy.next; 29 | } -------------------------------------------------------------------------------- /0019-remove-nth-node-from-end-of-list/0019-remove-nth-node-from-end-of-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | 7 | class Solution: 8 | def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: 9 | dummy = ListNode(0) # Create a dummy node to simplify edge cases 10 | dummy.next = head 11 | slow, fast = dummy, head 12 | 13 | # Move fast pointer so that the gap between slow and fast is n nodes apart 14 | for _ in range(n): 15 | fast = fast.next 16 | 17 | # Move fast to the end, maintaining the gap 18 | while fast: 19 | fast = fast.next 20 | slow = slow.next 21 | 22 | # Skip the desired node 23 | slow.next = slow.next.next 24 | 25 | # Return head of the modified list 26 | return dummy.next 27 | 28 | 29 | #Question: https://leetcode.com/problems/remove-nth-node-from-end-of-list 30 | #Blog: https://blog.unwiredlearning.com/remove-nth-node-from-end-of-list -------------------------------------------------------------------------------- /0020-valid-parentheses/0020-valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | class Solution { 6 | public: 7 | bool isValid(std::string s) { 8 | std::stack stack; 9 | for (char c : s) { 10 | if (c == '(' || c == '[' || c == '{') { 11 | stack.push(c); 12 | } else if (!stack.empty() && ((c == ')' && stack.top() == '(') || 13 | (c == ']' && stack.top() == '[') || 14 | (c == '}' && stack.top() == '{'))) { 15 | stack.pop(); 16 | } else { 17 | return false; 18 | } 19 | } 20 | return stack.empty(); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /0020-valid-parentheses/0020-valid-parentheses.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Stack; 3 | 4 | class Solution { 5 | public boolean isValid(String s) { 6 | Stack stack = new Stack<>(); 7 | for (char c : s.toCharArray()) { 8 | if (c == '(' || c == '[' || c == '{') { 9 | stack.push(c); 10 | } else if (c == ')' && !stack.isEmpty() && stack.peek() == '(') { 11 | stack.pop(); 12 | } else if (c == ']' && !stack.isEmpty() && stack.peek() == '[') { 13 | stack.pop(); 14 | } else if (c == '}' && !stack.isEmpty() && stack.peek() == '{') { 15 | stack.pop(); 16 | } else { 17 | return false; 18 | } 19 | } 20 | return stack.isEmpty(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /0020-valid-parentheses/0020-valid-parentheses.js: -------------------------------------------------------------------------------- 1 | 2 | function isValid(s) { 3 | const stack = []; 4 | const bracketMap = { 5 | ')': '(', 6 | ']': '[', 7 | '}': '{' 8 | }; 9 | 10 | for (let char of s) { 11 | if (bracketMap[char]) { 12 | if (stack.length > 0 && stack[stack.length - 1] === bracketMap[char]) { 13 | stack.pop(); 14 | } else { 15 | return false; 16 | } 17 | } else { 18 | stack.push(char); 19 | } 20 | } 21 | 22 | return stack.length === 0; 23 | } 24 | -------------------------------------------------------------------------------- /0020-valid-parentheses/0020-valid-parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | # Initialize an empty stack to keep track of opening brackets 4 | stack = [] 5 | 6 | # A mapping of closing brackets to their corresponding opening brackets 7 | bracket_map = {")": "(", "]": "[", "}": "{"} 8 | 9 | # Iterate through each character in the string 10 | for character in s: 11 | if character in bracket_map: 12 | # If stack is not empty and the top of the stack matches the corresponding opening bracket 13 | if stack and stack[-1] == bracket_map[character]: 14 | stack.pop() 15 | else: 16 | return False 17 | else: 18 | # If the character is an opening bracket, push it onto the stack 19 | stack.append(character) 20 | 21 | # After processing all characters, 22 | # return True if the stack is empty (all brackets matched), else False 23 | return not stack 24 | 25 | 26 | #Question: https://leetcode.com/problems/valid-parentheses 27 | #Blog: https://blog.unwiredlearning.com/valid-parentheses -------------------------------------------------------------------------------- /0021-merge-two-sorted-lists/0021-merge-two-sorted-lists.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct ListNode { 5 | int val; 6 | ListNode* next; 7 | ListNode() : val(0), next(nullptr) {} 8 | ListNode(int x) : val(x), next(nullptr) {} 9 | ListNode(int x, ListNode* next) : val(x), next(next) {} 10 | }; 11 | 12 | class Solution { 13 | public: 14 | ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { 15 | ListNode dummy; // Initialize a dummy node 16 | ListNode* node = &dummy; 17 | 18 | // Traverse both lists and attach the smaller node 19 | while (list1 != nullptr && list2 != nullptr) { 20 | if (list1->val < list2->val) { 21 | node->next = list1; 22 | list1 = list1->next; 23 | } else { 24 | node->next = list2; 25 | list2 = list2->next; 26 | } 27 | node = node->next; 28 | } 29 | 30 | // Attach any remaining nodes 31 | if (list1 != nullptr) { 32 | node->next = list1; 33 | } else { 34 | node->next = list2; 35 | } 36 | 37 | return dummy.next; // Return the merged list 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /0021-merge-two-sorted-lists/0021-merge-two-sorted-lists.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | ListNode() {} 5 | ListNode(int val) { this.val = val; } 6 | ListNode(int val, ListNode next) { this.val = val; this.next = next; } 7 | } 8 | 9 | class Solution { 10 | public ListNode mergeTwoLists(ListNode list1, ListNode list2) { 11 | ListNode dummy = new ListNode(); // Initialize a dummy node 12 | ListNode node = dummy; 13 | 14 | // Traverse both lists and attach the smaller node 15 | while (list1 != null && list2 != null) { 16 | if (list1.val < list2.val) { 17 | node.next = list1; 18 | list1 = list1.next; 19 | } else { 20 | node.next = list2; 21 | list2 = list2.next; 22 | } 23 | node = node.next; 24 | } 25 | 26 | // Attach any remaining nodes 27 | if (list1 != null) { 28 | node.next = list1; 29 | } else { 30 | node.next = list2; 31 | } 32 | 33 | return dummy.next; // Return the merged list 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /0021-merge-two-sorted-lists/0021-merge-two-sorted-lists.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor(val = 0, next = null) { 3 | this.val = val; 4 | this.next = next; 5 | } 6 | } 7 | 8 | function mergeTwoLists(list1, list2) { 9 | let dummy = new ListNode(); // Initialize a dummy node 10 | let node = dummy; 11 | 12 | // Traverse both lists and attach the smaller node 13 | while (list1 !== null && list2 !== null) { 14 | if (list1.val < list2.val) { 15 | node.next = list1; 16 | list1 = list1.next; 17 | } else { 18 | node.next = list2; 19 | list2 = list2.next; 20 | } 21 | node = node.next; 22 | } 23 | 24 | // Attach any remaining nodes 25 | node.next = list1 !== null ? list1 : list2; 26 | 27 | return dummy.next; // Return the merged list 28 | } 29 | -------------------------------------------------------------------------------- /0021-merge-two-sorted-lists/0021-merge-two-sorted-lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | 7 | class Solution: 8 | def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: 9 | dummy = ListNode() # Initialize a dummy node 10 | node = dummy 11 | 12 | # Traverse both lists and attach the smaller node 13 | while list1 and list2: 14 | if list1.val < list2.val: 15 | node.next = list1 16 | list1 = list1.next 17 | else: 18 | node.next = list2 19 | list2 = list2.next 20 | node = node.next 21 | 22 | # Attach any remaining nodes 23 | if list1 is not None: 24 | node.next = list1 25 | else: 26 | node.next = list2 27 | 28 | return dummy.next # Return the merged list 29 | 30 | 31 | #Question: https://leetcode.com/problems/merge-two-sorted-lists 32 | #Blog: https://blog.unwiredlearning.com/merge-two-sorted-lists -------------------------------------------------------------------------------- /0023-merge-k-sorted-lists/0023-merge-k-sorted-lists.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor(val = 0, next = null) { 3 | this.val = val; 4 | this.next = next; 5 | } 6 | } 7 | 8 | class Solution { 9 | mergeKLists(lists) { 10 | if (!lists || lists.length === 0) { 11 | return null; 12 | } 13 | if (lists.length === 1) { 14 | return lists[0]; 15 | } 16 | 17 | const mid = Math.floor(lists.length / 2); 18 | const left = this.mergeKLists(lists.slice(0, mid)); 19 | const right = this.mergeKLists(lists.slice(mid)); 20 | 21 | return this.mergeTwoLists(left, right); 22 | } 23 | 24 | mergeTwoLists(l1, l2) { 25 | const dummy = new ListNode(); 26 | let node = dummy; 27 | 28 | while (l1 && l2) { 29 | if (l1.val < l2.val) { 30 | node.next = l1; 31 | l1 = l1.next; 32 | } else { 33 | node.next = l2; 34 | l2 = l2.next; 35 | } 36 | node = node.next; 37 | } 38 | 39 | node.next = l1 || l2; 40 | return dummy.next; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /0033-search-in-rotated-sorted-array/0033-search-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int search(vector& nums, int target) { 7 | int left = 0, right = nums.size() - 1; 8 | 9 | while (left <= right) { 10 | int mid = left + (right - left) / 2; 11 | 12 | if (nums[mid] == target) { 13 | return mid; 14 | } 15 | 16 | // If the left half is sorted 17 | if (nums[mid] >= nums[left]) { 18 | if (nums[left] <= target && target < nums[mid]) { 19 | right = mid - 1; 20 | } else { 21 | left = mid + 1; 22 | } 23 | } else { 24 | // If the right half is sorted 25 | if (nums[mid] < target && target <= nums[right]) { 26 | left = mid + 1; 27 | } else { 28 | right = mid - 1; 29 | } 30 | } 31 | } 32 | 33 | return -1; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /0033-search-in-rotated-sorted-array/0033-search-in-rotated-sorted-array.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int search(int[] nums, int target) { 3 | int left = 0, right = nums.length - 1; 4 | 5 | while (left <= right) { 6 | int mid = left + (right - left) / 2; 7 | 8 | if (nums[mid] == target) { 9 | return mid; 10 | } 11 | 12 | // If the left half is sorted 13 | if (nums[mid] >= nums[left]) { 14 | if (nums[left] <= target && target < nums[mid]) { 15 | right = mid - 1; 16 | } else { 17 | left = mid + 1; 18 | } 19 | } else { 20 | // If the right half is sorted 21 | if (nums[mid] < target && target <= nums[right]) { 22 | left = mid + 1; 23 | } else { 24 | right = mid - 1; 25 | } 26 | } 27 | } 28 | 29 | return -1; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /0033-search-in-rotated-sorted-array/0033-search-in-rotated-sorted-array.js: -------------------------------------------------------------------------------- 1 | function search(nums, target) { 2 | let left = 0, right = nums.length - 1; 3 | 4 | while (left <= right) { 5 | let mid = Math.floor(left + (right - left) / 2); 6 | 7 | if (nums[mid] === target) { 8 | return mid; 9 | } 10 | 11 | // If the left half is sorted 12 | if (nums[mid] >= nums[left]) { 13 | if (nums[left] <= target && target < nums[mid]) { 14 | right = mid - 1; 15 | } else { 16 | left = mid + 1; 17 | } 18 | } else { 19 | // If the right half is sorted 20 | if (nums[mid] < target && target <= nums[right]) { 21 | left = mid + 1; 22 | } else { 23 | right = mid - 1; 24 | } 25 | } 26 | } 27 | 28 | return -1; 29 | } 30 | -------------------------------------------------------------------------------- /0039-combination-sum/0039-combination-sum.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector> combinationSum(vector& candidates, int target) { 8 | vector> allCombinations; 9 | vector currentCombination; 10 | dfs(candidates, 0, target, currentCombination, allCombinations); 11 | return allCombinations; 12 | } 13 | 14 | private: 15 | void dfs(vector& candidates, int index, int target, vector& currentCombination, vector>& allCombinations) { 16 | if (target == 0) { 17 | allCombinations.push_back(currentCombination); 18 | return; 19 | } 20 | 21 | if (index >= candidates.size() || target < 0) { 22 | return; 23 | } 24 | 25 | // Include the current candidate 26 | currentCombination.push_back(candidates[index]); 27 | dfs(candidates, index, target - candidates[index], currentCombination, allCombinations); 28 | currentCombination.pop_back(); 29 | 30 | // Move to the next candidate without including the current one 31 | dfs(candidates, index + 1, target, currentCombination, allCombinations); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /0039-combination-sum/0039-combination-sum.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | class Solution { 6 | public List> combinationSum(int[] candidates, int target) { 7 | List> allCombinations = new ArrayList<>(); 8 | dfs(candidates, 0, target, new ArrayList<>(), allCombinations); 9 | return allCombinations; 10 | } 11 | 12 | private void dfs(int[] candidates, int index, int target, List currentCombination, List> allCombinations) { 13 | if (target == 0) { 14 | allCombinations.add(new ArrayList<>(currentCombination)); 15 | return; 16 | } 17 | 18 | if (index >= candidates.length || target < 0) { 19 | return; 20 | } 21 | 22 | // Include the current candidate 23 | currentCombination.add(candidates[index]); 24 | dfs(candidates, index, target - candidates[index], currentCombination, allCombinations); 25 | currentCombination.remove(currentCombination.size() - 1); 26 | 27 | // Move to the next candidate without including the current one 28 | dfs(candidates, index + 1, target, currentCombination, allCombinations); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /0039-combination-sum/0039-combination-sum.js: -------------------------------------------------------------------------------- 1 | 2 | function combinationSum(candidates, target) { 3 | let allCombinations = []; 4 | 5 | function dfs(index, currentCombination, currentSum) { 6 | if (currentSum === target) { 7 | allCombinations.push([...currentCombination]); 8 | return; 9 | } 10 | 11 | if (index >= candidates.length || currentSum > target) { 12 | return; 13 | } 14 | 15 | // Include the current candidate 16 | currentCombination.push(candidates[index]); 17 | dfs(index, currentCombination, currentSum + candidates[index]); 18 | currentCombination.pop(); 19 | 20 | // Move to the next candidate without including the current one 21 | dfs(index + 1, currentCombination, currentSum); 22 | } 23 | 24 | dfs(0, [], 0); 25 | return allCombinations; 26 | } 27 | -------------------------------------------------------------------------------- /0039-combination-sum/0039-combination-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 3 | all_combinations = [] 4 | 5 | def dfs(index, current_combination, current_sum): 6 | 7 | # If the current sum equals the target, we've found a valid combination. 8 | if current_sum == target: 9 | all_combinations.append(current_combination) 10 | return 11 | 12 | # If we've considered all candidates or the current sum exceeds the target, backtrack. 13 | if index >= len(candidates) or current_sum > target: 14 | return 15 | 16 | dfs(index, current_combination + [candidates[index]], current_sum + candidates[index]) 17 | dfs(index + 1, current_combination, current_sum) 18 | 19 | # Start the DFS with an empty combination and a sum of 0. 20 | dfs(0, [], 0) 21 | return all_combinations 22 | 23 | 24 | #Question: https://leetcode.com/problems/combination-sum 25 | #Blog: https://blog.unwiredlearning.com/combination-sum -------------------------------------------------------------------------------- /0048-rotate-image/0048-rotate-image.js: -------------------------------------------------------------------------------- 1 | 2 | function rotate(matrix) { 3 | let n = matrix.length; 4 | 5 | // Iterate over each layer of the matrix 6 | for (let i = 0; i < Math.floor(n / 2); i++) { 7 | for (let j = i; j < n - i - 1; j++) { 8 | // Save the temp element 9 | let temp = matrix[i][j]; 10 | 11 | // Move bottom-left element to top-left 12 | matrix[i][j] = matrix[n - j - 1][i]; 13 | 14 | // Move bottom-right element to bottom-left 15 | matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]; 16 | 17 | // Move top-right element to bottom-right 18 | matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1]; 19 | 20 | // Assign temp element to top-right 21 | matrix[j][n - i - 1] = temp; 22 | } 23 | } 24 | } 25 | 26 | // Example usage: 27 | let matrix = [ 28 | [1, 2, 3], 29 | [4, 5, 6], 30 | [7, 8, 9] 31 | ]; 32 | 33 | rotate(matrix); 34 | console.log(matrix); 35 | -------------------------------------------------------------------------------- /0048-rotate-image/0048-rotate-image.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, matrix: List[List[int]]) -> None: 3 | n = len(matrix) 4 | 5 | # Iterate over each layer of the matrix 6 | for i in range(n // 2): 7 | for j in range(i, n - i - 1): 8 | # Save the temp element 9 | temp = matrix[i][j] 10 | 11 | # Move bottom-left element to top-left 12 | matrix[i][j] = matrix[n - j - 1][i] 13 | 14 | # Move bottom-right element to bottom-left 15 | matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1] 16 | 17 | # Move top-right element to bottom-right 18 | matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1] 19 | 20 | # Assign temp element to top-right 21 | matrix[j][n - i - 1] = temp 22 | 23 | 24 | #Question: https://leetcode.com/problems/rotate-image 25 | #Blog: https://blog.unwiredlearning.com/rotate-image -------------------------------------------------------------------------------- /0049-group-anagrams/0049-group-anagrams.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of group anagrams 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | vector> groupAnagrams(vector& strs) { 9 | unordered_map> anagramMap; 10 | 11 | for (string word : strs) { 12 | vector count(26, 0); 13 | for (char c : word) { 14 | count[c - 'a']++; 15 | } 16 | string key; 17 | for (int i = 0; i < 26; ++i) { 18 | key += string(1, count[i] + '0'); 19 | } 20 | anagramMap[key].push_back(word); 21 | } 22 | 23 | vector> result; 24 | for (auto& pair : anagramMap) { 25 | result.push_back(pair.second); 26 | } 27 | return result; 28 | } 29 | 30 | int main() { 31 | vector strs = {"eat", "tea", "tan", "ate", "nat", "bat"}; 32 | vector> result = groupAnagrams(strs); 33 | for (const auto& group : result) { 34 | for (const auto& word : group) { 35 | cout << word << " "; 36 | } 37 | cout << endl; 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /0049-group-anagrams/0049-group-anagrams.java: -------------------------------------------------------------------------------- 1 | // Java implementation of group anagrams 2 | import java.util.*; 3 | 4 | public class GroupAnagrams { 5 | public static List> groupAnagrams(String[] strs) { 6 | Map> anagramMap = new HashMap<>(); 7 | 8 | for (String word : strs) { 9 | char[] count = new char[26]; 10 | for (char c : word.toCharArray()) { 11 | count[c - 'a']++; 12 | } 13 | String key = String.valueOf(count); 14 | anagramMap.computeIfAbsent(key, k -> new ArrayList<>()).add(word); 15 | } 16 | 17 | return new ArrayList<>(anagramMap.values()); 18 | } 19 | 20 | public static void main(String[] args) { 21 | String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"}; 22 | List> result = groupAnagrams(strs); 23 | System.out.println(result); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /0049-group-anagrams/0049-group-anagrams.js: -------------------------------------------------------------------------------- 1 | // JavaScript implementation of group anagrams 2 | function groupAnagrams(strs) { 3 | let anagramMap = new Map(); 4 | 5 | strs.forEach(word => { 6 | let count = new Array(26).fill(0); 7 | for (let i = 0; i < word.length; i++) { 8 | count[word.charCodeAt(i) - 'a'.charCodeAt(0)]++; 9 | } 10 | let key = count.join('#'); 11 | if (!anagramMap.has(key)) { 12 | anagramMap.set(key, []); 13 | } 14 | anagramMap.get(key).push(word); 15 | }); 16 | 17 | return Array.from(anagramMap.values()); 18 | } 19 | 20 | const strs = ["eat", "tea", "tan", "ate", "nat", "bat"]; 21 | console.log(groupAnagrams(strs)); 22 | -------------------------------------------------------------------------------- /0053-maximum-subarray/0053-maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Solution { 5 | public: 6 | int maxSubArray(std::vector& nums) { 7 | int currentSum = nums[0]; 8 | int maxSum = nums[0]; 9 | 10 | for (int i = 1; i < nums.size(); ++i) { 11 | currentSum = std::max(nums[i], currentSum + nums[i]); 12 | maxSum = std::max(maxSum, currentSum); 13 | } 14 | 15 | return maxSum; 16 | } 17 | }; -------------------------------------------------------------------------------- /0053-maximum-subarray/0053-maximum-subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSubArray(int[] nums) { 3 | int currentSum = nums[0]; 4 | int maxSum = nums[0]; 5 | 6 | for (int i = 1; i < nums.length; i++) { 7 | currentSum = Math.max(nums[i], currentSum + nums[i]); 8 | maxSum = Math.max(maxSum, currentSum); 9 | } 10 | 11 | return maxSum; 12 | } 13 | } -------------------------------------------------------------------------------- /0053-maximum-subarray/0053-maximum-subarray.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | maxSubArray(nums) { 3 | let currentSum = nums[0]; 4 | let maxSum = nums[0]; 5 | 6 | for (let i = 1; i < nums.length; i++) { 7 | currentSum = Math.max(nums[i], currentSum + nums[i]); 8 | maxSum = Math.max(maxSum, currentSum); 9 | } 10 | 11 | return maxSum; 12 | } 13 | } -------------------------------------------------------------------------------- /0053-maximum-subarray/0053-maximum-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | # the sum of the subarray ending at the current index 4 | current_sum = nums[0] 5 | 6 | # This will store the maximum sum found so far 7 | max_sum = nums[0] 8 | 9 | # Iterate through the array starting from the second element 10 | for i in range(1, len(nums)): 11 | # Update current_sum to be the maximum of: 12 | # 1. The current element itself (which means starting a new subarray) 13 | # 2. The current element + current_sum (which means extending the existing subarray) 14 | current_sum = max(nums[i], current_sum + nums[i]) 15 | 16 | # Update max_sum to be the maximum of max_sum and current_sum 17 | # This ensures max_sum always holds the highest sum encountered 18 | max_sum = max(max_sum, current_sum) 19 | 20 | # Return the maximum sum found 21 | return max_sum 22 | 23 | 24 | #Question: https://leetcode.com/problems/maximum-subarray 25 | #Blog: https://blog.unwiredlearning.com/maximum-subarray -------------------------------------------------------------------------------- /0054-spiral-matrix/0054-spiral-matrix.js: -------------------------------------------------------------------------------- 1 | 2 | function spiralOrder(matrix) { 3 | let result = []; 4 | if (!matrix || matrix.length === 0) return result; 5 | 6 | let rowBegin = 0, rowEnd = matrix.length - 1; 7 | let colBegin = 0, colEnd = matrix[0].length - 1; 8 | 9 | while (rowBegin <= rowEnd && colBegin <= colEnd) { 10 | for (let i = colBegin; i <= colEnd; i++) { 11 | result.push(matrix[rowBegin][i]); 12 | } 13 | rowBegin++; 14 | 15 | for (let i = rowBegin; i <= rowEnd; i++) { 16 | result.push(matrix[i][colEnd]); 17 | } 18 | colEnd--; 19 | 20 | if (rowBegin <= rowEnd) { 21 | for (let i = colEnd; i >= colBegin; i--) { 22 | result.push(matrix[rowEnd][i]); 23 | } 24 | rowEnd--; 25 | } 26 | 27 | if (colBegin <= colEnd) { 28 | for (let i = rowEnd; i >= rowBegin; i--) { 29 | result.push(matrix[i][colBegin]); 30 | } 31 | colBegin++; 32 | } 33 | } 34 | 35 | return result; 36 | } 37 | 38 | // Example usage: 39 | let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; 40 | console.log(spiralOrder(matrix)); 41 | -------------------------------------------------------------------------------- /0055-jump-game/0055-jump-game.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool canJump(vector& nums) { 8 | int maxReach = 0; 9 | for (int i = 0; i < nums.size(); i++) { 10 | if (i > maxReach) { 11 | return false; 12 | } 13 | maxReach = max(maxReach, i + nums[i]); 14 | } 15 | return maxReach >= nums.size() - 1; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /0055-jump-game/0055-jump-game.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | class Solution { 4 | public boolean canJump(int[] nums) { 5 | int maxReach = 0; 6 | for (int i = 0; i < nums.length; i++) { 7 | if (i > maxReach) { 8 | return false; 9 | } 10 | maxReach = Math.max(maxReach, i + nums[i]); 11 | } 12 | return maxReach >= nums.length - 1; 13 | } 14 | } -------------------------------------------------------------------------------- /0055-jump-game/0055-jump-game.js: -------------------------------------------------------------------------------- 1 | 2 | function canJump(nums) { 3 | let maxReach = 0; 4 | for (let i = 0; i < nums.length; i++) { 5 | if (i > maxReach) { 6 | return false; 7 | } 8 | maxReach = Math.max(maxReach, i + nums[i]); 9 | } 10 | return maxReach >= nums.length - 1; 11 | } 12 | -------------------------------------------------------------------------------- /0055-jump-game/0055-jump-game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | # stores the farthest index we can reach 4 | maxReach = 0 5 | 6 | # Iterate through each index in the array 7 | for i in range(len(nums)): 8 | # If the current index is greater than the farthest we can reach, 9 | # it means we cannot reach this index, hence return False 10 | if i > maxReach: 11 | return False 12 | 13 | # Update maxReach to be the maximum of its current value 14 | # and the farthest index we can reach from the current index 15 | maxReach = max(maxReach, i + nums[i]) 16 | 17 | # If we have iterated through the array and maxReach is at least the last index, 18 | # it means we can reach the end, hence return True 19 | result = maxReach >= len(nums) - 1 20 | return result 21 | 22 | 23 | #Question: https://leetcode.com/problems/jump-game 24 | #Blog: https://blog.unwiredlearning.com/jump-game -------------------------------------------------------------------------------- /0056-merge-intervals/0056-merge-intervals.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | vector> merge(vector>& intervals) { 9 | sort(intervals.begin(), intervals.end()); 10 | vector> merged; 11 | merged.push_back(intervals[0]); 12 | 13 | for (int i = 1; i < intervals.size(); i++) { 14 | if (intervals[i][0] <= merged.back()[1]) { 15 | merged.back()[1] = max(merged.back()[1], intervals[i][1]); 16 | } else { 17 | merged.push_back(intervals[i]); 18 | } 19 | } 20 | 21 | return merged; 22 | } 23 | 24 | int main() { 25 | vector> intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}}; 26 | vector> result = merge(intervals); 27 | 28 | for (auto& interval : result) { 29 | cout << "[" << interval[0] << ", " << interval[1] << "]" << endl; 30 | } 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /0056-merge-intervals/0056-merge-intervals.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public class MergeIntervals { 7 | public static List merge(int[][] intervals) { 8 | Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); 9 | List merged = new ArrayList<>(); 10 | merged.add(intervals[0]); 11 | 12 | for (int i = 1; i < intervals.length; i++) { 13 | int[] lastInterval = merged.get(merged.size() - 1); 14 | if (intervals[i][0] <= lastInterval[1]) { 15 | lastInterval[1] = Math.max(lastInterval[1], intervals[i][1]); 16 | } else { 17 | merged.add(intervals[i]); 18 | } 19 | } 20 | 21 | return merged; 22 | } 23 | 24 | public static void main(String[] args) { 25 | int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}}; 26 | List result = merge(intervals); 27 | for (int[] interval : result) { 28 | System.out.println("[" + interval[0] + ", " + interval[1] + "]"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /0056-merge-intervals/0056-merge-intervals.js: -------------------------------------------------------------------------------- 1 | 2 | function merge(intervals) { 3 | intervals.sort((a, b) => a[0] - b[0]); 4 | let merged = [intervals[0]]; 5 | 6 | for (let i = 1; i < intervals.length; i++) { 7 | let lastInterval = merged[merged.length - 1]; 8 | if (intervals[i][0] <= lastInterval[1]) { 9 | lastInterval[1] = Math.max(lastInterval[1], intervals[i][1]); 10 | } else { 11 | merged.push(intervals[i]); 12 | } 13 | } 14 | 15 | return merged; 16 | } 17 | 18 | // Example usage: 19 | let intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]; 20 | console.log(merge(intervals)); 21 | -------------------------------------------------------------------------------- /0056-merge-intervals/0056-merge-intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 3 | 4 | # Step 1: Sort the intervals by the start time 5 | intervals.sort() 6 | 7 | # Step 2: Initialize the result array with the first interval 8 | merged = [intervals[0]] 9 | 10 | # Step 3: Iterate over the intervals and merge when necessary 11 | for i in range(1, len(intervals)): 12 | if intervals[i][0] <= merged[-1][1]: 13 | merged[-1][1] = max(merged[-1][1], intervals[i][1]) 14 | else: 15 | merged.append(intervals[i]) 16 | 17 | return merged 18 | 19 | 20 | #Question: https://leetcode.com/problems/merge-intervals 21 | #Blog: https://blog.unwiredlearning.com/merge-intervals -------------------------------------------------------------------------------- /0057-insert-interval/0057-insert-interval.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | vector> insert(vector>& intervals, vector& newInterval) { 8 | vector> left, right; 9 | int start = newInterval[0], end = newInterval[1]; 10 | 11 | for (auto& i : intervals) { 12 | if (i[1] < start) { 13 | left.push_back(i); 14 | } else if (i[0] > end) { 15 | right.push_back(i); 16 | } else { 17 | start = min(start, i[0]); 18 | end = max(end, i[1]); 19 | } 20 | } 21 | 22 | left.push_back({start, end}); 23 | left.insert(left.end(), right.begin(), right.end()); 24 | 25 | return left; 26 | } 27 | 28 | int main() { 29 | vector> intervals = {{1, 3}, {6, 9}}; 30 | vector newInterval = {2, 5}; 31 | vector> result = insert(intervals, newInterval); 32 | 33 | for (auto& interval : result) { 34 | cout << "[" << interval[0] << ", " << interval[1] << "]" << endl; 35 | } 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /0057-insert-interval/0057-insert-interval.js: -------------------------------------------------------------------------------- 1 | 2 | function insert(intervals, newInterval) { 3 | let left = [], right = []; 4 | let [start, end] = newInterval; 5 | 6 | for (let i of intervals) { 7 | if (i[1] < start) { 8 | left.push(i); 9 | } else if (i[0] > end) { 10 | right.push(i); 11 | } else { 12 | start = Math.min(start, i[0]); 13 | end = Math.max(end, i[1]); 14 | } 15 | } 16 | 17 | return [...left, [start, end], ...right]; 18 | } 19 | 20 | // Example usage: 21 | let intervals = [[1, 3], [6, 9]]; 22 | let newInterval = [2, 5]; 23 | console.log(insert(intervals, newInterval)); 24 | -------------------------------------------------------------------------------- /0057-insert-interval/0057-insert-interval.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def insert(self, intervals, newInterval) -> List[List[int]]: 3 | left, right = [], [] 4 | start, end = newInterval 5 | 6 | for i in intervals: 7 | # i ends before new_interval starts 8 | if i[1] < start: 9 | left.append(i) 10 | 11 | # i starts after new_interval ends 12 | elif i[0] > end: 13 | right.append(i) 14 | 15 | # i overlaps with new_interval 16 | else: 17 | start = min(start, i[0]) 18 | end = max(end, i[1]) 19 | 20 | return left + [[start, end]] + right 21 | 22 | 23 | #Question: https://leetcode.com/problems/insert-interval 24 | #Blog: https://blog.unwiredlearning.com/insert-interval -------------------------------------------------------------------------------- /0062-unique-paths/0062-unique-paths.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | int uniquePaths(int m, int n) { 5 | vector> dp(m, vector(n, 1)); 6 | 7 | for (int i = 1; i < m; i++) { 8 | for (int j = 1; j < n; j++) { 9 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 10 | } 11 | } 12 | 13 | return dp[m - 1][n - 1]; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /0062-unique-paths/0062-unique-paths.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public int uniquePaths(int m, int n) { 4 | int[][] dp = new int[m][n]; 5 | 6 | // Initialize DP array with 1s 7 | for (int i = 0; i < m; i++) { 8 | for (int j = 0; j < n; j++) { 9 | if (i == 0 || j == 0) { 10 | dp[i][j] = 1; 11 | } else { 12 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 13 | } 14 | } 15 | } 16 | 17 | // Return the result from the bottom-right cell 18 | return dp[m - 1][n - 1]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /0062-unique-paths/0062-unique-paths.js: -------------------------------------------------------------------------------- 1 | 2 | var uniquePaths = function(m, n) { 3 | let dp = Array.from({ length: m }, () => Array(n).fill(1)); 4 | 5 | for (let i = 1; i < m; i++) { 6 | for (let j = 1; j < n; j++) { 7 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 8 | } 9 | } 10 | 11 | return dp[m - 1][n - 1]; 12 | }; 13 | -------------------------------------------------------------------------------- /0062-unique-paths/0062-unique-paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m: int, n: int) -> int: 3 | # Step 1 and 2: Initialize DP array with 1s 4 | dp = [[1]*n for _ in range(m)] 5 | 6 | # Step 2: Fill in the dp with unique paths to each cell 7 | for i in range(1, m): 8 | for j in range(1, n): 9 | dp[i][j] = dp[i-1][j] + dp[i][j-1] 10 | 11 | # Step 3: Return the result from the bottom-right cell 12 | return dp[m-1][n-1] 13 | 14 | 15 | #Question: https://leetcode.com/problems/unique-paths 16 | #Blog: https://blog.unwiredlearning.com/unique-paths -------------------------------------------------------------------------------- /0070-climbing-stairs/0070-climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Solution { 4 | public: 5 | int climbStairs(int n) { 6 | // Base case: if n is 1, there's only one way. 7 | if (n == 1) { 8 | return n; 9 | } 10 | 11 | // Initialize a vector to store the number of ways to reach each step. 12 | std::vector dp(n + 1, 0); 13 | dp[1] = 1; 14 | dp[2] = 2; 15 | 16 | // Start calculating from the 3rd step up to the nth step. 17 | for (int i = 3; i <= n; i++) { 18 | dp[i] = dp[i - 1] + dp[i - 2]; 19 | } 20 | 21 | // dp[n] contains the total number of ways to climb n stairs. 22 | return dp[n]; 23 | } 24 | }; -------------------------------------------------------------------------------- /0070-climbing-stairs/0070-climbing-stairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int climbStairs(int n) { 3 | // Base case: if n is 1, there's only one way. 4 | if (n == 1) { 5 | return n; 6 | } 7 | 8 | // Initialize an array to store the number of ways to reach each step. 9 | int[] dp = new int[n + 1]; 10 | dp[1] = 1; 11 | dp[2] = 2; 12 | 13 | // Start calculating from the 3rd step up to the nth step. 14 | for (int i = 3; i <= n; i++) { 15 | dp[i] = dp[i - 1] + dp[i - 2]; 16 | } 17 | 18 | // dp[n] contains the total number of ways to climb n stairs. 19 | return dp[n]; 20 | } 21 | } -------------------------------------------------------------------------------- /0070-climbing-stairs/0070-climbing-stairs.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | climbStairs(n) { 3 | // Base case: if n is 1, there's only one way. 4 | if (n === 1) { 5 | return n; 6 | } 7 | 8 | // Initialize an array to store the number of ways to reach each step. 9 | const dp = new Array(n + 1).fill(0); 10 | dp[1] = 1; 11 | dp[2] = 2; 12 | 13 | // Start calculating from the 3rd step up to the nth step. 14 | for (let i = 3; i <= n; i++) { 15 | dp[i] = dp[i - 1] + dp[i - 2]; 16 | } 17 | 18 | // dp[n] contains the total number of ways to climb n stairs. 19 | return dp[n]; 20 | } 21 | } -------------------------------------------------------------------------------- /0070-climbing-stairs/0070-climbing-stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | # Base case: if n is 1, there's only one way. 4 | if n == 1: 5 | return n 6 | 7 | # Initialize a list to store the number of ways to reach each step. 8 | dp = [0] * (n + 1) 9 | dp[1], dp[2] = 1, 2 10 | 11 | # Start calculating from the 3rd step up to the nth step. 12 | for i in range(3, n + 1): 13 | dp[i] = dp[i - 1] + dp[i - 2] 14 | 15 | # dp[n] contains the total number of ways to climb n stairs. 16 | return dp[n] 17 | 18 | 19 | #Question: https://leetcode.com/problems/climbing-stairs 20 | #Blog: https://blog.unwiredlearning.com/climbing-stairs -------------------------------------------------------------------------------- /0079-word-search/0079-word-search.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | bool exist(vector>& board, string word) { 5 | for (int i = 0; i < board.size(); i++) { 6 | for (int j = 0; j < board[0].size(); j++) { 7 | if (board[i][j] == word[0] && dfs(board, word, i, j, 0)) { 8 | return true; 9 | } 10 | } 11 | } 12 | return false; 13 | } 14 | 15 | bool dfs(vector>& board, string word, int i, int j, int k) { 16 | if (k == word.length()) { 17 | return true; 18 | } 19 | if (i < 0 || i >= board.size() || j < 0 || j >= board[0].size() || board[i][j] != word[k]) { 20 | return false; 21 | } 22 | char tmp = board[i][j]; 23 | board[i][j] = '/'; 24 | bool result = dfs(board, word, i + 1, j, k + 1) || 25 | dfs(board, word, i - 1, j, k + 1) || 26 | dfs(board, word, i, j + 1, k + 1) || 27 | dfs(board, word, i, j - 1, k + 1); 28 | board[i][j] = tmp; 29 | return result; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /0079-word-search/0079-word-search.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public boolean exist(char[][] board, String word) { 4 | for (int i = 0; i < board.length; i++) { 5 | for (int j = 0; j < board[0].length; j++) { 6 | if (board[i][j] == word.charAt(0) && dfs(board, word, i, j, 0)) { 7 | return true; 8 | } 9 | } 10 | } 11 | return false; 12 | } 13 | 14 | private boolean dfs(char[][] board, String word, int i, int j, int k) { 15 | if (k == word.length()) { 16 | return true; 17 | } 18 | if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(k)) { 19 | return false; 20 | } 21 | char tmp = board[i][j]; 22 | board[i][j] = '/'; 23 | boolean result = dfs(board, word, i + 1, j, k + 1) || 24 | dfs(board, word, i - 1, j, k + 1) || 25 | dfs(board, word, i, j + 1, k + 1) || 26 | dfs(board, word, i, j - 1, k + 1); 27 | board[i][j] = tmp; 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /0079-word-search/0079-word-search.js: -------------------------------------------------------------------------------- 1 | 2 | var exist = function(board, word) { 3 | for (let i = 0; i < board.length; i++) { 4 | for (let j = 0; j < board[0].length; j++) { 5 | if (board[i][j] === word[0] && dfs(board, word, i, j, 0)) { 6 | return true; 7 | } 8 | } 9 | } 10 | return false; 11 | }; 12 | 13 | function dfs(board, word, i, j, k) { 14 | if (k === word.length) { 15 | return true; 16 | } 17 | if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] !== word[k]) { 18 | return false; 19 | } 20 | let temp = board[i][j]; 21 | board[i][j] = '/'; 22 | let result = dfs(board, word, i + 1, j, k + 1) || 23 | dfs(board, word, i - 1, j, k + 1) || 24 | dfs(board, word, i, j + 1, k + 1) || 25 | dfs(board, word, i, j - 1, k + 1); 26 | board[i][j] = temp; 27 | return result; 28 | } 29 | -------------------------------------------------------------------------------- /0079-word-search/0079-word-search.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def exist(self, board: List[List[str]], word: str) -> bool: 3 | 4 | # DFS function to search for the word starting from cell (i, j) 5 | def dfs(i, j, k): 6 | 7 | if k == len(word): 8 | return True 9 | 10 | if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[k]: 11 | return False 12 | 13 | tmp, board[i][j] = board[i][j], '/' 14 | result = dfs(i+1, j, k+1) or dfs(i-1, j, k+1) or dfs(i, j+1, k+1) or dfs(i, j-1, k+1) 15 | board[i][j] = tmp 16 | 17 | return result 18 | 19 | # Iterate over each cell in the board 20 | for i in range(len(board)): 21 | for j in range(len(board[0])): 22 | if board[i][j] == word[0]: 23 | if dfs(i, j, 0): 24 | return True 25 | 26 | # If no path matches the word, return False 27 | return False 28 | 29 | 30 | #Question: https://leetcode.com/problems/word-search 31 | #Blog: https://blog.unwiredlearning.com/word-search -------------------------------------------------------------------------------- /0091-decode-ways/0091-decode-ways.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | class Solution { 6 | public: 7 | int numDecodings(const std::string &s) { 8 | if (s.empty() || s[0] == '0') { 9 | return 0; 10 | } 11 | 12 | int n = s.length(); 13 | std::vector dp(n + 1, 0); 14 | 15 | // Base cases 16 | dp[0] = 1; 17 | dp[1] = 1; 18 | 19 | for (int i = 2; i <= n; i++) { 20 | // Single digit decode 21 | if (s[i - 1] != '0') { 22 | dp[i] += dp[i - 1]; 23 | } 24 | // Two digit decode 25 | int twoDigit = std::stoi(s.substr(i - 2, 2)); 26 | if (twoDigit >= 10 && twoDigit <= 26) { 27 | dp[i] += dp[i - 2]; 28 | } 29 | } 30 | 31 | return dp[n]; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /0091-decode-ways/0091-decode-ways.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public int numDecodings(String s) { 4 | if (s == null || s.length() == 0 || s.charAt(0) == '0') { 5 | return 0; 6 | } 7 | 8 | int n = s.length(); 9 | int[] dp = new int[n + 1]; 10 | 11 | // Base cases 12 | dp[0] = 1; 13 | dp[1] = 1; 14 | 15 | for (int i = 2; i <= n; i++) { 16 | // Single digit decode 17 | if (s.charAt(i - 1) != '0') { 18 | dp[i] += dp[i - 1]; 19 | } 20 | // Two digit decode 21 | int twoDigit = Integer.parseInt(s.substring(i - 2, i)); 22 | if (twoDigit >= 10 && twoDigit <= 26) { 23 | dp[i] += dp[i - 2]; 24 | } 25 | } 26 | 27 | return dp[n]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /0091-decode-ways/0091-decode-ways.js: -------------------------------------------------------------------------------- 1 | 2 | function numDecodings(s) { 3 | if (!s || s[0] === '0') { 4 | return 0; 5 | } 6 | 7 | const n = s.length; 8 | const dp = new Array(n + 1).fill(0); 9 | 10 | // Base cases 11 | dp[0] = 1; 12 | dp[1] = 1; 13 | 14 | for (let i = 2; i <= n; i++) { 15 | // Single digit decode 16 | if (s[i - 1] !== '0') { 17 | dp[i] += dp[i - 1]; 18 | } 19 | // Two digit decode 20 | const twoDigit = parseInt(s.substring(i - 2, i), 10); 21 | if (twoDigit >= 10 && twoDigit <= 26) { 22 | dp[i] += dp[i - 2]; 23 | } 24 | } 25 | 26 | return dp[n]; 27 | } 28 | -------------------------------------------------------------------------------- /0091-decode-ways/0091-decode-ways.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numDecodings(self, s: str) -> int: 3 | if not s or s[0] == '0': 4 | return 0 5 | 6 | n = len(s) 7 | dp = [0] * (n + 1) 8 | 9 | # Base cases 10 | dp[0], dp[1] = 1, 1 11 | 12 | for i in range(2, n + 1): 13 | # Single digit decodec 14 | if 1 <= int(s[i-1:i]) <= 9: 15 | dp[i] += dp[i-1] 16 | 17 | # Two digit decode 18 | if 10 <= int(s[i-2:i]) <= 26: 19 | dp[i] += dp[i-2] 20 | 21 | return dp[n] 22 | 23 | 24 | #Question: https://leetcode.com/problems/decode-ways 25 | #Blog: https://blog.unwiredlearning.com/decode-ways -------------------------------------------------------------------------------- /0098-validate-binary-search-tree/0098-validate-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct TreeNode { 5 | int val; 6 | TreeNode* left; 7 | TreeNode* right; 8 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | bool isValidBST(TreeNode* root) { 14 | vector ioList; 15 | helper(root, ioList); 16 | 17 | bool isBST = true; 18 | int prev = ioList[0]; 19 | 20 | for (int i = 1; i < ioList.size(); i++) { 21 | if (ioList[i] <= prev) { 22 | isBST = false; 23 | } 24 | prev = ioList[i]; 25 | } 26 | 27 | return isBST; 28 | } 29 | 30 | private: 31 | void helper(TreeNode* node, vector& ioList) { 32 | if (node == nullptr) return; 33 | 34 | helper(node->left, ioList); 35 | ioList.push_back(node->val); 36 | helper(node->right, ioList); 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /0098-validate-binary-search-tree/0098-validate-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | TreeNode(int val) { 6 | this.val = val; 7 | } 8 | } 9 | 10 | public class Solution { 11 | public boolean isValidBST(TreeNode root) { 12 | List ioList = new ArrayList<>(); 13 | helper(root, ioList); 14 | 15 | boolean isBST = true; 16 | int prev = ioList.get(0); 17 | 18 | for (int i = 1; i < ioList.size(); i++) { 19 | if (ioList.get(i) <= prev) { 20 | isBST = false; 21 | } 22 | prev = ioList.get(i); 23 | } 24 | 25 | return isBST; 26 | } 27 | 28 | private void helper(TreeNode node, List ioList) { 29 | if (node == null) return; 30 | 31 | helper(node.left, ioList); 32 | ioList.add(node.val); 33 | helper(node.right, ioList); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /0098-validate-binary-search-tree/0098-validate-binary-search-tree.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val = 0, left = null, right = null) { 3 | this.val = val; 4 | this.left = left; 5 | this.right = right; 6 | } 7 | } 8 | 9 | class Solution { 10 | isValidBST(root) { 11 | let ioList = []; 12 | this.helper(root, ioList); 13 | 14 | let isBST = true; 15 | let prev = ioList[0]; 16 | 17 | for (let i = 1; i < ioList.length; i++) { 18 | if (ioList[i] <= prev) { 19 | isBST = false; 20 | } 21 | prev = ioList[i]; 22 | } 23 | 24 | return isBST; 25 | } 26 | 27 | helper(node, ioList) { 28 | if (node === null) return; 29 | 30 | this.helper(node.left, ioList); 31 | ioList.push(node.val); 32 | this.helper(node.right, ioList); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /0100-same-tree/100-same-tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 9 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 10 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 11 | }; 12 | 13 | class Solution { 14 | public: 15 | bool isSameTree(TreeNode* p, TreeNode* q) { 16 | if (p == nullptr && q == nullptr) { 17 | return true; 18 | } 19 | if (p == nullptr || q == nullptr || p->val != q->val) { 20 | return false; 21 | } 22 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /0100-same-tree/100-same-tree.java: -------------------------------------------------------------------------------- 1 | 2 | class TreeNode { 3 | int val; 4 | TreeNode left; 5 | TreeNode right; 6 | TreeNode() {} 7 | TreeNode(int val) { this.val = val; } 8 | TreeNode(int val, TreeNode left, TreeNode right) { 9 | this.val = val; 10 | this.left = left; 11 | this.right = right; 12 | } 13 | } 14 | 15 | class Solution { 16 | public boolean isSameTree(TreeNode p, TreeNode q) { 17 | if (p == null && q == null) { 18 | return true; 19 | } 20 | if (p == null || q == null || p.val != q.val) { 21 | return false; 22 | } 23 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /0100-same-tree/100-same-tree.js: -------------------------------------------------------------------------------- 1 | 2 | function TreeNode(val, left, right) { 3 | this.val = (val === undefined ? 0 : val); 4 | this.left = (left === undefined ? null : left); 5 | this.right = (right === undefined ? null : right); 6 | } 7 | 8 | function isSameTree(p, q) { 9 | if (p === null && q === null) { 10 | return true; 11 | } 12 | if (p === null || q === null || p.val !== q.val) { 13 | return false; 14 | } 15 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 16 | } 17 | -------------------------------------------------------------------------------- /0100-same-tree/100-same-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | 8 | class Solution: 9 | def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: 10 | # Base case: if both trees are empty 11 | if p == None and q == None: 12 | return True 13 | 14 | # Trees are not the same if either of them is empty or values are different 15 | if p == None or q == None or p.val != q.val: 16 | return False 17 | 18 | # Check recursively for left and right subtrees 19 | left_compare = self.isSameTree(p.left, q.left) 20 | right_compare = self.isSameTree(p.right, q.right) 21 | 22 | return left_compare and right_compare 23 | 24 | 25 | #Question: https://leetcode.com/problems/same-tree 26 | #Blog: https://blog.unwiredlearning.com/same-tree -------------------------------------------------------------------------------- /0102-binary-tree-level-order-traversal/0102-binary-tree-level-order-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct TreeNode { 8 | int val; 9 | TreeNode *left; 10 | TreeNode *right; 11 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 12 | }; 13 | 14 | class Solution { 15 | public: 16 | vector> levelOrder(TreeNode* root) { 17 | vector> result; 18 | if (!root) { 19 | return result; 20 | } 21 | 22 | queue q; 23 | q.push(root); 24 | 25 | while (!q.empty()) { 26 | int levelSize = q.size(); 27 | vector level; 28 | 29 | for (int i = 0; i < levelSize; ++i) { 30 | TreeNode* node = q.front(); 31 | q.pop(); 32 | level.push_back(node->val); 33 | if (node->left) { 34 | q.push(node->left); 35 | } 36 | if (node->right) { 37 | q.push(node->right); 38 | } 39 | } 40 | 41 | result.push_back(level); 42 | } 43 | 44 | return result; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /0102-binary-tree-level-order-traversal/0102-binary-tree-level-order-traversal.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val, left = null, right = null) { 3 | this.val = val; 4 | this.left = left; 5 | this.right = right; 6 | } 7 | } 8 | 9 | class Solution { 10 | levelOrder(root) { 11 | if (!root) { 12 | return []; 13 | } 14 | 15 | const result = []; 16 | const queue = [root]; 17 | 18 | while (queue.length > 0) { 19 | const levelSize = queue.length; 20 | const level = []; 21 | 22 | for (let i = 0; i < levelSize; i++) { 23 | const node = queue.shift(); 24 | level.push(node.val); 25 | if (node.left) { 26 | queue.push(node.left); 27 | } 28 | if (node.right) { 29 | queue.push(node.right); 30 | } 31 | } 32 | 33 | result.push(level); 34 | } 35 | 36 | return result; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /0104-maximum-depth-of-binary-tree/0104-maximum-depth-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | struct TreeNode { 6 | int val; 7 | TreeNode *left; 8 | TreeNode *right; 9 | 10 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | }; 12 | 13 | class Solution { 14 | public: 15 | int maxDepth(TreeNode* root) { 16 | if (root == nullptr) { 17 | return 0; 18 | } 19 | 20 | int maxDepth = 0; 21 | std::stack> stack; 22 | stack.push({root, 1}); 23 | 24 | while (!stack.empty()) { 25 | auto [node, depth] = stack.top(); 26 | stack.pop(); 27 | 28 | if (node) { 29 | maxDepth = std::max(maxDepth, depth); 30 | if (node->left) { 31 | stack.push({node->left, depth + 1}); 32 | } 33 | if (node->right) { 34 | stack.push({node->right, depth + 1}); 35 | } 36 | } 37 | } 38 | 39 | return maxDepth; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /0104-maximum-depth-of-binary-tree/0104-maximum-depth-of-binary-tree.js: -------------------------------------------------------------------------------- 1 | 2 | class TreeNode { 3 | constructor(val) { 4 | this.val = val; 5 | this.left = null; 6 | this.right = null; 7 | } 8 | } 9 | 10 | function maxDepth(root) { 11 | if (root === null) { 12 | return 0; 13 | } 14 | 15 | let maxDepth = 0; 16 | const stack = [{ node: root, depth: 1 }]; 17 | 18 | while (stack.length > 0) { 19 | const { node, depth } = stack.pop(); 20 | 21 | if (node) { 22 | maxDepth = Math.max(maxDepth, depth); 23 | if (node.left) { 24 | stack.push({ node: node.left, depth: depth + 1 }); 25 | } 26 | if (node.right) { 27 | stack.push({ node: node.right, depth: depth + 1 }); 28 | } 29 | } 30 | } 31 | 32 | return maxDepth; 33 | } 34 | -------------------------------------------------------------------------------- /0104-maximum-depth-of-binary-tree/0104-maximum-depth-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | 8 | class Solution: 9 | def maxDepth(self, root: Optional[TreeNode]) -> int: 10 | if not root: 11 | return 0 12 | 13 | max_depth = 0 14 | 15 | # Stack of (node, depth) pairs 16 | stack = [(root, 1)] 17 | 18 | while stack: 19 | node, depth = stack.pop() 20 | 21 | if node: 22 | max_depth = max(max_depth, depth) 23 | if node.left: 24 | stack.append((node.left, depth + 1)) 25 | if node.right: 26 | stack.append((node.right, depth + 1)) 27 | 28 | return max_depth 29 | 30 | 31 | #Question: https://leetcode.com/problems/maximum-depth-of-binary-tree 32 | #Blog: https://blog.unwiredlearning.com/maximum-depth-of-binary-tree -------------------------------------------------------------------------------- /0121-best-time-to-buy-and-sell-stock/0121-best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Solution { 5 | public: 6 | int maxProfit(std::vector& prices) { 7 | int buyPrice = prices[0]; 8 | int profit = 0; 9 | 10 | for (int i = 1; i < prices.size(); i++) { 11 | if (prices[i] < buyPrice) { 12 | buyPrice = prices[i]; 13 | } else { 14 | int currentProfit = prices[i] - buyPrice; 15 | profit = std::max(profit, currentProfit); 16 | } 17 | } 18 | 19 | return profit; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /0121-best-time-to-buy-and-sell-stock/0121-best-time-to-buy-and-sell-stock.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public int maxProfit(int[] prices) { 5 | int buyPrice = prices[0]; 6 | int profit = 0; 7 | 8 | for (int i = 1; i < prices.length; i++) { 9 | if (prices[i] < buyPrice) { 10 | buyPrice = prices[i]; 11 | } else { 12 | int currentProfit = prices[i] - buyPrice; 13 | profit = Math.max(profit, currentProfit); 14 | } 15 | } 16 | 17 | return profit; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /0121-best-time-to-buy-and-sell-stock/0121-best-time-to-buy-and-sell-stock.js: -------------------------------------------------------------------------------- 1 | function maxProfit(prices) { 2 | let buyPrice = prices[0]; 3 | let profit = 0; 4 | 5 | for (let i = 1; i < prices.length; i++) { 6 | if (prices[i] < buyPrice) { 7 | buyPrice = prices[i]; 8 | } else { 9 | let currentProfit = prices[i] - buyPrice; 10 | profit = Math.max(profit, currentProfit); 11 | } 12 | } 13 | 14 | return profit; 15 | } 16 | -------------------------------------------------------------------------------- /0121-best-time-to-buy-and-sell-stock/0121-best-time-to-buy-and-sell-stock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | # minimum buy price is the first price 4 | buy_price = prices[0] 5 | 6 | # the minimum profit is zero 7 | profit = 0 8 | 9 | for i in range(1, len(prices)): 10 | 11 | # if the current price is less, update the buy_price 12 | if prices[i] < buy_price: 13 | buy_price = prices[i] 14 | else: 15 | # else check if we can get a better profit 16 | current_profit = prices[i] - buy_price 17 | profit = max(current_profit, profit) 18 | 19 | return profit 20 | 21 | 22 | #Question: https://leetcode.com/problems/best-time-to-buy-and-sell-stock 23 | #Blog: https://blog.unwiredlearning.com/best-time-to-buy-and-sell-stock -------------------------------------------------------------------------------- /0124-binary-tree-maximum-path-sum/0124-binary-tree-maximum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | int maxPathSum(TreeNode* root) { 14 | int maxSum = INT_MIN; 15 | dfs(root, maxSum); 16 | return maxSum; 17 | } 18 | 19 | private: 20 | int dfs(TreeNode* node, int& maxSum) { 21 | if (node == nullptr) { 22 | return 0; 23 | } 24 | 25 | int leftGain = std::max(dfs(node->left, maxSum), 0); 26 | int rightGain = std::max(dfs(node->right, maxSum), 0); 27 | 28 | int priceNewPath = node->val + leftGain + rightGain; 29 | maxSum = std::max(maxSum, priceNewPath); 30 | 31 | return node->val + std::max(leftGain, rightGain); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /0124-binary-tree-maximum-path-sum/0124-binary-tree-maximum-path-sum.java: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | TreeNode(int x) { val = x; } 6 | } 7 | 8 | class Solution { 9 | private int maxSum = Integer.MIN_VALUE; 10 | 11 | public int maxPathSum(TreeNode root) { 12 | dfs(root); 13 | return maxSum; 14 | } 15 | 16 | private int dfs(TreeNode node) { 17 | if (node == null) { 18 | return 0; 19 | } 20 | 21 | int leftGain = Math.max(dfs(node.left), 0); 22 | int rightGain = Math.max(dfs(node.right), 0); 23 | 24 | int priceNewPath = node.val + leftGain + rightGain; 25 | maxSum = Math.max(maxSum, priceNewPath); 26 | 27 | return node.val + Math.max(leftGain, rightGain); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /0124-binary-tree-maximum-path-sum/0124-binary-tree-maximum-path-sum.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val, left = null, right = null) { 3 | this.val = val; 4 | this.left = left; 5 | this.right = right; 6 | } 7 | } 8 | 9 | class Solution { 10 | constructor() { 11 | this.maxSum = -Infinity; 12 | } 13 | 14 | maxPathSum(root) { 15 | this.dfs(root); 16 | return this.maxSum; 17 | } 18 | 19 | dfs(node) { 20 | if (node === null) { 21 | return 0; 22 | } 23 | 24 | const leftGain = Math.max(this.dfs(node.left), 0); 25 | const rightGain = Math.max(this.dfs(node.right), 0); 26 | 27 | const priceNewPath = node.val + leftGain + rightGain; 28 | this.maxSum = Math.max(this.maxSum, priceNewPath); 29 | 30 | return node.val + Math.max(leftGain, rightGain); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /0124-binary-tree-maximum-path-sum/0124-binary-tree-maximum-path-sum.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | 8 | class Solution: 9 | def maxPathSum(self, root: Optional[TreeNode]) -> int: 10 | max_sum = float('-inf') 11 | 12 | def dfs(node): 13 | if not node: 14 | return 0 15 | 16 | # Recursive call on left and right child 17 | left_gain = max(dfs(node.left), 0) 18 | right_gain = max(dfs(node.right), 0) 19 | 20 | # Update max_sum if it's better to start a new path 21 | price_newpath = node.val + left_gain + right_gain 22 | max_sum = max(max_sum, price_newpath) 23 | 24 | # For recursion return the max gain if continue the same path 25 | return node.val + max(left_gain, right_gain) 26 | 27 | dfs(root) 28 | return max_sum 29 | 30 | 31 | #Question: https://leetcode.com/problems/binary-tree-maximum-path-sum 32 | #Blog: https://blog.unwiredlearning.com/binary-tree-maximum-path-sum -------------------------------------------------------------------------------- /0125-valid-palindrome/0125-valid-palindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | bool isPalindrome(string s) { 8 | // Step 1: Initialize two pointers 9 | int left = 0, right = s.length() - 1; 10 | 11 | // Step 2: Traverse the string from both ends 12 | while (left < right) { 13 | // Skip non-alphanumeric characters on the left 14 | while (left < right && !isalnum(s[left])) { 15 | left++; 16 | } 17 | // Skip non-alphanumeric characters on the right 18 | while (left < right && !isalnum(s[right])) { 19 | right--; 20 | } 21 | 22 | // Compare characters 23 | if (tolower(s[left]) != tolower(s[right])) { 24 | return false; 25 | } 26 | 27 | // Move both pointers inward 28 | left++; 29 | right--; 30 | } 31 | 32 | return true; 33 | } 34 | 35 | int main() { 36 | string s = "A man, a plan, a canal: Panama"; 37 | cout << (isPalindrome(s) ? "true" : "false") << endl; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /0125-valid-palindrome/0125-valid-palindrome.java: -------------------------------------------------------------------------------- 1 | public class ValidPalindrome { 2 | public static boolean isPalindrome(String s) { 3 | // Step 1: Initialize two pointers 4 | int left = 0, right = s.length() - 1; 5 | 6 | // Step 2: Traverse the string from both ends 7 | while (left < right) { 8 | // Skip non-alphanumeric characters on the left 9 | while (left < right && !Character.isLetterOrDigit(s.charAt(left))) { 10 | left++; 11 | } 12 | // Skip non-alphanumeric characters on the right 13 | while (left < right && !Character.isLetterOrDigit(s.charAt(right))) { 14 | right--; 15 | } 16 | 17 | // Compare characters 18 | if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { 19 | return false; 20 | } 21 | 22 | // Move both pointers inward 23 | left++; 24 | right--; 25 | } 26 | 27 | return true; 28 | } 29 | 30 | public static void main(String[] args) { 31 | String s = "A man, a plan, a canal: Panama"; 32 | System.out.println(isPalindrome(s)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /0125-valid-palindrome/0125-valid-palindrome.js: -------------------------------------------------------------------------------- 1 | function isPalindrome(s) { 2 | // Step 1: Initialize two pointers 3 | let left = 0, right = s.length - 1; 4 | 5 | // Step 2: Traverse the string from both ends 6 | while (left < right) { 7 | // Skip non-alphanumeric characters on the left 8 | while (left < right && !isAlphanumeric(s[left])) { 9 | left++; 10 | } 11 | // Skip non-alphanumeric characters on the right 12 | while (left < right && !isAlphanumeric(s[right])) { 13 | right--; 14 | } 15 | 16 | // Compare characters 17 | if (s[left].toLowerCase() !== s[right].toLowerCase()) { 18 | return false; 19 | } 20 | 21 | // Move both pointers inward 22 | left++; 23 | right--; 24 | } 25 | 26 | return true; 27 | } 28 | 29 | function isAlphanumeric(char) { 30 | return /^[a-zA-Z0-9]$/.test(char); 31 | } 32 | 33 | // Example usage 34 | const s = "A man, a plan, a canal: Panama"; 35 | console.log(isPalindrome(s)); 36 | -------------------------------------------------------------------------------- /0125-valid-palindrome/0125-valid-palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def is_alphanumeric(self, element): 3 | """Check if a character is alphanumeric.""" 4 | return ('A' <= element <= 'Z') or ('a' <= element <= 'z') or ('0' <= element <= '9') 5 | 6 | def isPalindrome(self, s: str) -> bool: 7 | left, right = 0, len(s) - 1 8 | 9 | while left < right: 10 | 11 | # Increment left pointer if not alphanumeric 12 | while left < right and not self.is_alphanumeric(s[left]): 13 | left += 1 14 | 15 | # Decrement right pointer if not alphanumeric 16 | while left < right and not self.is_alphanumeric(s[right]): 17 | right -= 1 18 | 19 | # Compare characters (case-insensitive) 20 | if s[left].lower() != s[right].lower(): 21 | return False 22 | 23 | left += 1 24 | right -= 1 25 | 26 | return True 27 | 28 | 29 | #Question: https://leetcode.com/problems/valid-palindrome 30 | #Blog: https://blog.unwiredlearning.com/valid-palindrome -------------------------------------------------------------------------------- /0128-longest-consecutive-sequence/0128-longest-consecutive-sequence.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int longestConsecutive(vector& nums) { 9 | if (nums.empty()) { 10 | return 0; 11 | } 12 | 13 | unordered_set numSet(nums.begin(), nums.end()); 14 | int longestStreak = 0; 15 | 16 | for (int num : numSet) { 17 | if (numSet.find(num - 1) == numSet.end()) { 18 | int currentNum = num; 19 | int currentStreak = 1; 20 | 21 | while (numSet.find(currentNum + 1) != numSet.end()) { 22 | currentNum += 1; 23 | currentStreak += 1; 24 | } 25 | 26 | longestStreak = max(longestStreak, currentStreak); 27 | } 28 | } 29 | 30 | return longestStreak; 31 | } 32 | 33 | int main() { 34 | vector nums = {100, 4, 200, 1, 3, 2}; 35 | cout << "Longest consecutive sequence length: " << longestConsecutive(nums) << endl; 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /0128-longest-consecutive-sequence/0128-longest-consecutive-sequence.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashSet; 3 | import java.util.Set; 4 | 5 | public class LongestConsecutiveSequence { 6 | public static int longestConsecutive(int[] nums) { 7 | if (nums == null || nums.length == 0) { 8 | return 0; 9 | } 10 | 11 | Set numSet = new HashSet<>(); 12 | for (int num : nums) { 13 | numSet.add(num); 14 | } 15 | 16 | int longestStreak = 0; 17 | 18 | for (int num : numSet) { 19 | if (!numSet.contains(num - 1)) { 20 | int currentNum = num; 21 | int currentStreak = 1; 22 | 23 | while (numSet.contains(currentNum + 1)) { 24 | currentNum += 1; 25 | currentStreak += 1; 26 | } 27 | 28 | longestStreak = Math.max(longestStreak, currentStreak); 29 | } 30 | } 31 | 32 | return longestStreak; 33 | } 34 | 35 | public static void main(String[] args) { 36 | int[] nums = {100, 4, 200, 1, 3, 2}; 37 | System.out.println("Longest consecutive sequence length: " + longestConsecutive(nums)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /0128-longest-consecutive-sequence/0128-longest-consecutive-sequence.js: -------------------------------------------------------------------------------- 1 | 2 | function longestConsecutive(nums) { 3 | if (!nums || nums.length === 0) { 4 | return 0; 5 | } 6 | 7 | const numSet = new Set(nums); 8 | let longestStreak = 0; 9 | 10 | for (let num of numSet) { 11 | if (!numSet.has(num - 1)) { 12 | let currentNum = num; 13 | let currentStreak = 1; 14 | 15 | while (numSet.has(currentNum + 1)) { 16 | currentNum += 1; 17 | currentStreak += 1; 18 | } 19 | 20 | longestStreak = Math.max(longestStreak, currentStreak); 21 | } 22 | } 23 | 24 | return longestStreak; 25 | } 26 | 27 | // Example usage 28 | const nums = [100, 4, 200, 1, 3, 2]; 29 | console.log("Longest consecutive sequence length:", longestConsecutive(nums)); 30 | -------------------------------------------------------------------------------- /0133-clone-graph/0133-clone-graph.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShubhamSarda/leetcode/e3907ef5667ab6db69541e3d85a0a68db8cf02b9/0133-clone-graph/0133-clone-graph.cpp -------------------------------------------------------------------------------- /0133-clone-graph/0133-clone-graph.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShubhamSarda/leetcode/e3907ef5667ab6db69541e3d85a0a68db8cf02b9/0133-clone-graph/0133-clone-graph.java -------------------------------------------------------------------------------- /0133-clone-graph/0133-clone-graph.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ShubhamSarda/leetcode/e3907ef5667ab6db69541e3d85a0a68db8cf02b9/0133-clone-graph/0133-clone-graph.js -------------------------------------------------------------------------------- /0139-word-break/0139-word-break.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class Solution { 6 | public: 7 | bool wordBreak(std::string s, std::vector& wordDict) { 8 | std::unordered_set wordSet(wordDict.begin(), wordDict.end()); 9 | std::vector res(s.length() + 1, false); 10 | res[0] = true; 11 | 12 | for (int i = 0; i <= s.length(); i++) { 13 | for (const std::string& word : wordSet) { 14 | if (res[i] && i + word.length() <= s.length() && s.substr(i, word.length()) == word) { 15 | res[i + word.length()] = true; 16 | } 17 | } 18 | } 19 | 20 | return res[s.length()]; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /0139-word-break/0139-word-break.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public boolean wordBreak(String s, List wordDict) { 5 | Set wordSet = new HashSet<>(wordDict); 6 | boolean[] res = new boolean[s.length() + 1]; 7 | res[0] = true; 8 | 9 | for (int i = 0; i <= s.length(); i++) { 10 | for (String word : wordSet) { 11 | if (res[i] && i + word.length() <= s.length() && s.substring(i, i + word.length()).equals(word)) { 12 | res[i + word.length()] = true; 13 | } 14 | } 15 | } 16 | 17 | return res[s.length()]; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /0139-word-break/0139-word-break.js: -------------------------------------------------------------------------------- 1 | var wordBreak = function(s, wordDict) { 2 | const wordSet = new Set(wordDict); 3 | const res = Array(s.length + 1).fill(false); 4 | res[0] = true; 5 | 6 | for (let i = 0; i <= s.length; i++) { 7 | for (const word of wordSet) { 8 | if (res[i] && i + word.length <= s.length && s.substring(i, i + word.length) === word) { 9 | res[i + word.length] = true; 10 | } 11 | } 12 | } 13 | 14 | return res[s.length]; 15 | }; 16 | -------------------------------------------------------------------------------- /0139-word-break/0139-word-break.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordBreak(self, s: str, wordDict: List[str]) -> bool: 3 | wordSet = set(wordDict) 4 | 5 | res = [False] * (len(s) + 1) 6 | res[0] = True 7 | 8 | # Iterate through all positions in the string 9 | for i in range(len(s) + 1): 10 | # Check all words in the wordSet 11 | for word in wordSet: 12 | if (res[i] and (i + len(word)) <= len(s) and s[i : i + len(word)] in wordSet): 13 | res[i + len(word)] = True 14 | 15 | return res[-1] 16 | 17 | 18 | #Question: https://leetcode.com/problems/word-break 19 | #Blog: https://blog.unwiredlearning.com/word-break -------------------------------------------------------------------------------- /0141-linked-list-cycle/0141-linked-list-cycle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode(int x) : val(x), next(NULL) {} 7 | }; 8 | 9 | class Solution { 10 | public: 11 | bool hasCycle(ListNode *head) { 12 | ListNode *slow = head; 13 | ListNode *fast = head; 14 | 15 | while (fast != nullptr && fast->next != nullptr) { 16 | slow = slow->next; 17 | fast = fast->next->next; 18 | 19 | if (slow == fast) { 20 | return true; 21 | } 22 | } 23 | 24 | return false; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /0141-linked-list-cycle/0141-linked-list-cycle.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | ListNode(int x) { 5 | val = x; 6 | next = null; 7 | } 8 | } 9 | 10 | public class Solution { 11 | public boolean hasCycle(ListNode head) { 12 | ListNode slow = head; 13 | ListNode fast = head; 14 | 15 | while (fast != null && fast.next != null) { 16 | slow = slow.next; 17 | fast = fast.next.next; 18 | 19 | if (slow == fast) { 20 | return true; 21 | } 22 | } 23 | 24 | return false; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /0141-linked-list-cycle/0141-linked-list-cycle.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.next = null; 5 | } 6 | } 7 | 8 | var hasCycle = function(head) { 9 | let slow = head; 10 | let fast = head; 11 | 12 | while (fast !== null && fast.next !== null) { 13 | slow = slow.next; 14 | fast = fast.next.next; 15 | 16 | if (slow === fast) { 17 | return true; 18 | } 19 | } 20 | 21 | return false; 22 | }; 23 | -------------------------------------------------------------------------------- /0141-linked-list-cycle/0141-linked-list-cycle.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def hasCycle(self, head: ListNode) -> bool: 9 | # Initialize the two pointers 10 | slow, fast = head, head 11 | 12 | # Traverse the list with the two pointers 13 | while fast is not None and fast.next is not None: 14 | slow = slow.next # Move the slow pointer one step 15 | fast = fast.next.next # Move the fast pointer two steps 16 | 17 | # If there's a cycle, the two pointers will meet 18 | if slow == fast: 19 | return True 20 | 21 | # If the fast pointer reaches the end, there's no cycle 22 | return False 23 | 24 | 25 | #Question: https://leetcode.com/problems/linked-list-cycle 26 | #Blog: https://blog.unwiredlearning.com/linked-list-cycle -------------------------------------------------------------------------------- /0142-linked-list-cycle-ii/0142-linked-list-cycle-ii.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct ListNode { 4 | int val; 5 | ListNode *next; 6 | ListNode(int x) : val(x), next(nullptr) {} 7 | }; 8 | 9 | class Solution { 10 | public: 11 | ListNode *detectCycle(ListNode *head) { 12 | ListNode *slow = head; 13 | ListNode *fast = head; 14 | 15 | // Advance both pointers at different speeds until they meet 16 | while (fast != nullptr && fast->next != nullptr) { 17 | fast = fast->next->next; 18 | slow = slow->next; 19 | 20 | // If they meet, start from the head again and move at the same speed 21 | if (slow == fast) { 22 | while (head != slow) { 23 | head = head->next; 24 | slow = slow->next; 25 | } 26 | return slow; 27 | } 28 | } 29 | 30 | // If no cycle is detected, return nullptr 31 | return nullptr; 32 | } 33 | }; -------------------------------------------------------------------------------- /0142-linked-list-cycle-ii/0142-linked-list-cycle-ii.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public ListNode detectCycle(ListNode head) { 3 | ListNode slow = head; 4 | ListNode fast = head; 5 | 6 | // Advance both pointers at different speeds until they meet 7 | while (fast != null && fast.next != null) { 8 | fast = fast.next.next; 9 | slow = slow.next; 10 | 11 | // If they meet, start from the head again and move at the same speed 12 | if (slow == fast) { 13 | while (head != slow) { 14 | head = head.next; 15 | slow = slow.next; 16 | } 17 | return slow; 18 | } 19 | } 20 | 21 | // If no cycle is detected, return null 22 | return null; 23 | } 24 | } 25 | 26 | class ListNode { 27 | int val; 28 | ListNode next; 29 | ListNode(int x) { 30 | val = x; 31 | next = null; 32 | } 33 | } -------------------------------------------------------------------------------- /0142-linked-list-cycle-ii/0142-linked-list-cycle-ii.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.next = null; 5 | } 6 | } 7 | 8 | var detectCycle = function(head) { 9 | let slow = head; 10 | let fast = head; 11 | 12 | // Advance both pointers at different speeds until they meet 13 | while (fast !== null && fast.next !== null) { 14 | fast = fast.next.next; 15 | slow = slow.next; 16 | 17 | // If they meet, start from the head again and move at the same speed 18 | if (slow === fast) { 19 | while (head !== slow) { 20 | head = head.next; 21 | slow = slow.next; 22 | } 23 | return slow; 24 | } 25 | } 26 | 27 | // If no cycle is detected, return null 28 | return null; 29 | }; -------------------------------------------------------------------------------- /0142-linked-list-cycle-ii/0142-linked-list-cycle-ii.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution: 8 | def detectCycle(self, head: ListNode) -> ListNode: 9 | slow = head 10 | fast = head 11 | 12 | # Advance both pointers at different speeds until they meet 13 | while fast and fast.next: 14 | fast = fast.next.next 15 | slow = slow.next 16 | 17 | # If they meet, start from the head again and move at the same speed 18 | if slow == fast: 19 | while head != slow: 20 | head = head.next 21 | slow = slow.next 22 | return slow 23 | 24 | # If no cycle is detected, return None 25 | return None 26 | 27 | 28 | #Question: https://leetcode.com/problems/linked-list-cycle-ii 29 | #Blog: https://blog.unwiredlearning.com/linked-list-cycle-ii -------------------------------------------------------------------------------- /0143-reorder-list/0143-reorder-list.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor(val = 0, next = null) { 3 | this.val = val; 4 | this.next = next; 5 | } 6 | } 7 | 8 | function reorderList(head) { 9 | if (head === null) return; 10 | 11 | // Step 1: Find the middle of the linked list 12 | let slow = head, fast = head; 13 | while (fast !== null && fast.next !== null) { 14 | slow = slow.next; 15 | fast = fast.next.next; 16 | } 17 | 18 | // Step 2: Reverse the second half of the list 19 | let previous = null, current = slow; 20 | while (current !== null) { 21 | let nextTemp = current.next; 22 | current.next = previous; 23 | previous = current; 24 | current = nextTemp; 25 | } 26 | 27 | // Step 3: Merge the two halves 28 | let first = head, second = previous; 29 | while (second.next !== null) { 30 | let temp1 = first.next; 31 | let temp2 = second.next; 32 | first.next = second; 33 | second.next = temp1; 34 | first = temp1; 35 | second = temp2; 36 | } 37 | } -------------------------------------------------------------------------------- /0143-reorder-list/0143-reorder-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | 7 | class Solution: 8 | def reorderList(self, head: ListNode) -> None: 9 | 10 | # Step 1: Find the middle of the linked list 11 | slow, fast = head, head 12 | while fast and fast.next: 13 | slow = slow.next 14 | fast = fast.next.next 15 | 16 | # Step 2: Reverse the second half of the list 17 | previous, current = None, slow 18 | while current: 19 | next_temp = current.next 20 | current.next = previous 21 | previous = current 22 | current = next_temp 23 | 24 | # Step 3: Merge the two halves 25 | first, second = head, previous 26 | while second.next: 27 | temp1, temp2 = first.next, second.next 28 | first.next = second 29 | second.next = temp1 30 | first, second = temp1, temp2 31 | 32 | 33 | #Question: https://leetcode.com/problems/reorder-list 34 | #Blog: https://blog.unwiredlearning.com/reorder-list -------------------------------------------------------------------------------- /0152-maximum-product-subarray/0152-maximum-product-subarray.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int maxProduct(vector& nums) { 9 | int n = nums.size(); 10 | int leftProduct = 1, rightProduct = 1; 11 | int result = nums[0]; 12 | 13 | for (int i = 0; i < n; i++) { 14 | // If any of left or right product becomes 0, update it to 1 15 | if (leftProduct == 0) { 16 | leftProduct = 1; 17 | } 18 | if (rightProduct == 0) { 19 | rightProduct = 1; 20 | } 21 | 22 | // Prefix product 23 | leftProduct *= nums[i]; 24 | 25 | // Suffix product 26 | rightProduct *= nums[n - 1 - i]; 27 | 28 | // Update the result with the maximum value found 29 | result = max(result, max(leftProduct, rightProduct)); 30 | } 31 | 32 | return result; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /0152-maximum-product-subarray/0152-maximum-product-subarray.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public int maxProduct(int[] nums) { 4 | int n = nums.length; 5 | int leftProduct = 1, rightProduct = 1; 6 | int result = nums[0]; 7 | 8 | for (int i = 0; i < n; i++) { 9 | // If any of left or right product becomes 0, update it to 1 10 | if (leftProduct == 0) { 11 | leftProduct = 1; 12 | } 13 | if (rightProduct == 0) { 14 | rightProduct = 1; 15 | } 16 | 17 | // Prefix product 18 | leftProduct *= nums[i]; 19 | 20 | // Suffix product 21 | rightProduct *= nums[n - 1 - i]; 22 | 23 | // Update the result with the maximum value found 24 | result = Math.max(result, Math.max(leftProduct, rightProduct)); 25 | } 26 | 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /0152-maximum-product-subarray/0152-maximum-product-subarray.js: -------------------------------------------------------------------------------- 1 | 2 | function maxProduct(nums) { 3 | const n = nums.length; 4 | let leftProduct = 1, rightProduct = 1; 5 | let result = nums[0]; 6 | 7 | for (let i = 0; i < n; i++) { 8 | // If any of left or right product becomes 0, update it to 1 9 | if (leftProduct === 0) { 10 | leftProduct = 1; 11 | } 12 | if (rightProduct === 0) { 13 | rightProduct = 1; 14 | } 15 | 16 | // Prefix product 17 | leftProduct *= nums[i]; 18 | 19 | // Suffix product 20 | rightProduct *= nums[n - 1 - i]; 21 | 22 | // Update the result with the maximum value found 23 | result = Math.max(result, leftProduct, rightProduct); 24 | } 25 | 26 | return result; 27 | } 28 | -------------------------------------------------------------------------------- /0152-maximum-product-subarray/0152-maximum-product-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | left_product, right_product = 1, 1 5 | result = nums[0] 6 | 7 | for i in range(n): 8 | # if any of left or right product become 0, update it to 1 9 | if left_product == 0: 10 | left_product = 1 11 | if right_product == 0: 12 | right_product = 1 13 | 14 | # prefix product 15 | left_product *= nums[i] 16 | 17 | # suffix product 18 | right_product *= nums[n - 1 - i] 19 | 20 | result = max(ans, max(left_product, right_product)) 21 | 22 | return result 23 | 24 | 25 | #Question: https://leetcode.com/problems/maximum-product-subarray 26 | #Blog: https://blog.unwiredlearning.com/maximum-product-subarray -------------------------------------------------------------------------------- /0153-find-minimum-in-rotated-sorted-array/0153-find-minimum-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Solution { 4 | public: 5 | int findMin(std::vector& nums) { 6 | int left = 0; 7 | int right = nums.size() - 1; 8 | 9 | while (left < right) { 10 | int mid = left + (right - left) / 2; 11 | 12 | // If the middle element is greater than the rightmost element, 13 | // it indicates that the smallest element is in the right half. 14 | if (nums[mid] > nums[right]) { 15 | left = mid + 1; 16 | } else { 17 | right = mid; 18 | } 19 | } 20 | 21 | // At the end of the loop, left will be pointing at the smallest element. 22 | return nums[left]; 23 | } 24 | }; -------------------------------------------------------------------------------- /0153-find-minimum-in-rotated-sorted-array/0153-find-minimum-in-rotated-sorted-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findMin(int[] nums) { 3 | int left = 0; 4 | int right = nums.length - 1; 5 | 6 | while (left < right) { 7 | int mid = left + (right - left) / 2; 8 | 9 | // If the middle element is greater than the rightmost element, 10 | // it indicates that the smallest element is in the right half. 11 | if (nums[mid] > nums[right]) { 12 | left = mid + 1; 13 | } else { 14 | right = mid; 15 | } 16 | } 17 | 18 | // At the end of the loop, left will be pointing at the smallest element. 19 | return nums[left]; 20 | } 21 | } -------------------------------------------------------------------------------- /0153-find-minimum-in-rotated-sorted-array/0153-find-minimum-in-rotated-sorted-array.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | findMin(nums) { 3 | let left = 0; 4 | let right = nums.length - 1; 5 | 6 | while (left < right) { 7 | let mid = Math.floor(left + (right - left) / 2); 8 | 9 | // If the middle element is greater than the rightmost element, 10 | // it indicates that the smallest element is in the right half. 11 | if (nums[mid] > nums[right]) { 12 | left = mid + 1; 13 | } else { 14 | right = mid; 15 | } 16 | } 17 | 18 | // At the end of the loop, left will be pointing at the smallest element. 19 | return nums[left]; 20 | } 21 | } -------------------------------------------------------------------------------- /0153-find-minimum-in-rotated-sorted-array/0153-find-minimum-in-rotated-sorted-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMin(self, nums: List[int]) -> int: 3 | left, right = 0, len(nums) - 1 4 | 5 | while left < right: 6 | mid = left + (right - left) // 2 7 | 8 | # If the middle element is greater than the rightmost element, 9 | # it indicates that the smallest element is in the right half. 10 | # Thus, adjust the left pointer to mid + 1. 11 | if nums[mid] > nums[right]: 12 | left = mid + 1 13 | 14 | # If the middle element is greater than the rightmost element, 15 | # it indicates that the smallest element is in the right half. 16 | # Thus, adjust the left pointer to mid + 1. 17 | else: 18 | right = mid 19 | 20 | # At the end of the loop, left will be pointing at the smallest element. 21 | return nums[left] 22 | 23 | 24 | #Question: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array 25 | #Blog: https://blog.unwiredlearning.com/find-minimum-in-rotated-sorted-array -------------------------------------------------------------------------------- /0167-two-sum-ii-input-array-is-sorted/0167-two-sum-ii-input-array-is-sorted.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | vector twoSum(vector& numbers, int target) { 7 | int left = 0, right = numbers.size() - 1; 8 | 9 | while (left < right) { 10 | int currentSum = numbers[left] + numbers[right]; 11 | 12 | if (currentSum == target) { 13 | return {left + 1, right + 1}; 14 | } else if (currentSum < target) { 15 | left++; 16 | } else { 17 | right--; 18 | } 19 | } 20 | 21 | return {}; // Return empty vector if no solution found. 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /0167-two-sum-ii-input-array-is-sorted/0167-two-sum-ii-input-array-is-sorted.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] numbers, int target) { 3 | int left = 0, right = numbers.length - 1; 4 | 5 | while (left < right) { 6 | int currentSum = numbers[left] + numbers[right]; 7 | 8 | if (currentSum == target) { 9 | return new int[] {left + 1, right + 1}; 10 | } else if (currentSum < target) { 11 | left++; 12 | } else { 13 | right--; 14 | } 15 | } 16 | 17 | return new int[] {}; // Return empty array if no solution found. 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /0167-two-sum-ii-input-array-is-sorted/0167-two-sum-ii-input-array-is-sorted.js: -------------------------------------------------------------------------------- 1 | function twoSum(numbers, target) { 2 | let left = 0; 3 | let right = numbers.length - 1; 4 | 5 | while (left < right) { 6 | const currentSum = numbers[left] + numbers[right]; 7 | 8 | if (currentSum === target) { 9 | return [left + 1, right + 1]; 10 | } else if (currentSum < target) { 11 | left++; 12 | } else { 13 | right--; 14 | } 15 | } 16 | 17 | return []; // Return empty array if no solution found. 18 | } 19 | -------------------------------------------------------------------------------- /0167-two-sum-ii-input-array-is-sorted/0167-two-sum-ii-input-array-is-sorted.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, numbers: List[int], target: int) -> List[int]: 3 | # Initialize two pointers: left at the start, right at the end. 4 | left, right = 0, len(numbers) - 1 5 | 6 | while left < right: 7 | current_sum = numbers[left] + numbers[right] 8 | 9 | # Return the 1-indexed positions if the target sum is found. 10 | if current_sum == target: 11 | return [left + 1, right + 1] 12 | 13 | # Move the left pointer to the right if the sum is less than the target. 14 | elif current_sum < target: 15 | left += 1 16 | 17 | # Move the right pointer to the left if the sum is greater than the target. 18 | elif current_sum > target: 19 | right -= 1 20 | 21 | return [] 22 | 23 | 24 | #Question: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted 25 | #Blog: https://blog.unwiredlearning.com/two-sum-ii-input-array-is-sorted -------------------------------------------------------------------------------- /0190-reverse-bits/0190-reverse-bits.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | uint32_t reverseBits(uint32_t n) { 8 | uint32_t result = 0; 9 | 10 | for (int i = 0; i < 32; i++) { 11 | uint32_t bit = n & 1; // Extract the last bit of n 12 | result = (result << 1) | bit; // Shift result to the left and add bit 13 | n = n >> 1; // Shift n to the right to process the next bit 14 | } 15 | 16 | return result; 17 | } 18 | 19 | int main() { 20 | uint32_t n = 43261596; // Example input (binary: 00000010100101000001111010011100) 21 | cout << reverseBits(n) << endl; // Output: 964176192 (binary: 00111001011110000010100101000000) 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /0190-reverse-bits/0190-reverse-bits.java: -------------------------------------------------------------------------------- 1 | 2 | public class ReverseBits { 3 | public static int reverseBits(int n) { 4 | int result = 0; 5 | 6 | for (int i = 0; i < 32; i++) { 7 | int bit = n & 1; // Extract the last bit of n 8 | result = (result << 1) | bit; // Shift result to the left and add bit 9 | n = n >> 1; // Shift n to the right to process the next bit 10 | } 11 | 12 | return result; 13 | } 14 | 15 | public static void main(String[] args) { 16 | int n = 43261596; // Example input (binary: 00000010100101000001111010011100) 17 | System.out.println(reverseBits(n)); // Output: 964176192 (binary: 00111001011110000010100101000000) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /0190-reverse-bits/0190-reverse-bits.js: -------------------------------------------------------------------------------- 1 | 2 | function reverseBits(n) { 3 | let result = 0; 4 | 5 | for (let i = 0; i < 32; i++) { 6 | let bit = n & 1; // Extract the last bit of n 7 | result = (result << 1) | bit; // Shift result to the left and add bit 8 | n = n >>> 1; // Logical right shift n to process the next bit 9 | } 10 | 11 | return result >>> 0; // Convert to unsigned 32-bit integer 12 | } 13 | 14 | // Example usage: 15 | let n = 43261596; // Example input (binary: 00000010100101000001111010011100) 16 | console.log(reverseBits(n)); // Output: 964176192 (binary: 00111001011110000010100101000000) 17 | -------------------------------------------------------------------------------- /0190-reverse-bits/0190-reverse-bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseBits(self, n: int) -> int: 3 | result = 0 4 | 5 | for _ in range(32): 6 | # Extract the last bit of n 7 | bit = n & 1 8 | 9 | # Shift result to the left to make space for the extracted bit 10 | result = (result << 1) | bit 11 | 12 | # Shift n to the right to process the next bit 13 | n = n >> 1 14 | 15 | return result 16 | 17 | 18 | #Question: https://leetcode.com/problems/reverse-bits 19 | #Blog: https://blog.unwiredlearning.com/reverse-bits -------------------------------------------------------------------------------- /0191-number-of-1-bits/0191-number-of-1-bits.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | using namespace std; 5 | 6 | int hammingWeight(uint32_t n) { 7 | int count = 0; 8 | 9 | // Assuming a 32-bit integer 10 | for (int i = 0; i < 32; i++) { 11 | count += (n & 1); 12 | n = n >> 1; 13 | } 14 | 15 | return count; 16 | } 17 | 18 | int main() { 19 | uint32_t n = 11; // Example input (binary: 1011) 20 | cout << hammingWeight(n) << endl; // Output: 3 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /0191-number-of-1-bits/0191-number-of-1-bits.java: -------------------------------------------------------------------------------- 1 | 2 | public class NumberOf1Bits { 3 | public static int hammingWeight(int n) { 4 | int count = 0; 5 | 6 | // Assuming a 32-bit integer 7 | for (int i = 0; i < 32; i++) { 8 | count += (n & 1); 9 | n = n >> 1; 10 | } 11 | 12 | return count; 13 | } 14 | 15 | public static void main(String[] args) { 16 | int n = 11; // Example input (binary: 1011) 17 | System.out.println(hammingWeight(n)); // Output: 3 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /0191-number-of-1-bits/0191-number-of-1-bits.js: -------------------------------------------------------------------------------- 1 | 2 | function hammingWeight(n) { 3 | let count = 0; 4 | 5 | // Assuming a 32-bit integer 6 | for (let i = 0; i < 32; i++) { 7 | count += (n & 1); 8 | n = n >> 1; 9 | } 10 | 11 | return count; 12 | } 13 | 14 | // Example usage: 15 | let n = 11; // Example input (binary: 1011) 16 | console.log(hammingWeight(n)); // Output: 3 17 | -------------------------------------------------------------------------------- /0191-number-of-1-bits/0191-number-of-1-bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n: int) -> int: 3 | count = 0 4 | 5 | # Assuming a 32-bit integer 6 | for _ in range(32): 7 | # Check the LSB 8 | count = count + (n & 1) 9 | 10 | # Right shift the bits of n 11 | n = n >> 1 12 | 13 | return count 14 | 15 | 16 | #Question: https://leetcode.com/problems/number-of-1-bits 17 | #Blog: https://blog.unwiredlearning.com/number-of-1-bits -------------------------------------------------------------------------------- /0198-house-robber/0198-house-robber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Solution { 5 | public: 6 | int rob(std::vector& nums) { 7 | if (nums.empty()) { 8 | return 0; 9 | } 10 | 11 | if (nums.size() == 1) { 12 | return nums[0]; 13 | } 14 | 15 | std::vector dp(nums.size()); 16 | dp[0] = nums[0]; 17 | dp[1] = std::max(nums[0], nums[1]); 18 | 19 | for (int i = 2; i < nums.size(); ++i) { 20 | dp[i] = std::max(dp[i - 2] + nums[i], dp[i - 1]); 21 | } 22 | 23 | return dp.back(); 24 | } 25 | }; -------------------------------------------------------------------------------- /0198-house-robber/0198-house-robber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rob(int[] nums) { 3 | if (nums == null || nums.length == 0) { 4 | return 0; 5 | } 6 | 7 | if (nums.length == 1) { 8 | return nums[0]; 9 | } 10 | 11 | int[] dp = new int[nums.length]; 12 | dp[0] = nums[0]; 13 | dp[1] = Math.max(nums[0], nums[1]); 14 | 15 | for (int i = 2; i < nums.length; i++) { 16 | dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]); 17 | } 18 | 19 | return dp[nums.length - 1]; 20 | } 21 | } -------------------------------------------------------------------------------- /0198-house-robber/0198-house-robber.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | rob(nums) { 3 | if (nums === null || nums.length === 0) { 4 | return 0; 5 | } 6 | 7 | if (nums.length === 1) { 8 | return nums[0]; 9 | } 10 | 11 | let dp = new Array(nums.length); 12 | dp[0] = nums[0]; 13 | dp[1] = Math.max(nums[0], nums[1]); 14 | 15 | for (let i = 2; i < nums.length; i++) { 16 | dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]); 17 | } 18 | 19 | return dp[nums.length - 1]; 20 | } 21 | } -------------------------------------------------------------------------------- /0198-house-robber/0198-house-robber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | if not nums: 4 | return 0 5 | 6 | if len(nums) == 1: 7 | return nums[0] 8 | 9 | dp = [0] * len(nums) 10 | dp[0] = nums[0] 11 | dp[1] = max(nums[0], nums[1]) 12 | 13 | for i in range(2, len(nums)): 14 | dp[i] = max(dp[i-2] + nums[i], dp[i-1]) 15 | 16 | return dp[-1] 17 | 18 | 19 | #Question: https://leetcode.com/problems/house-robber 20 | #Blog: https://blog.unwiredlearning.com/house-robber -------------------------------------------------------------------------------- /0200-number-of-islands/0200-number-of-islands.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int numIslands(vector>& grid) { 8 | if (grid.empty()) { 9 | return 0; 10 | } 11 | 12 | int count = 0; 13 | int rows = grid.size(); 14 | int cols = grid[0].size(); 15 | 16 | for (int i = 0; i < rows; ++i) { 17 | for (int j = 0; j < cols; ++j) { 18 | if (grid[i][j] == '1') { 19 | dfs(grid, i, j); 20 | count++; 21 | } 22 | } 23 | } 24 | 25 | return count; 26 | } 27 | 28 | private: 29 | void dfs(vector>& grid, int i, int j) { 30 | if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] == '0') { 31 | return; 32 | } 33 | 34 | grid[i][j] = '0'; 35 | dfs(grid, i + 1, j); 36 | dfs(grid, i - 1, j); 37 | dfs(grid, i, j + 1); 38 | dfs(grid, i, j - 1); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /0200-number-of-islands/0200-number-of-islands.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | public class Solution { 5 | public int numIslands(char[][] grid) { 6 | if (grid == null || grid.length == 0) { 7 | return 0; 8 | } 9 | 10 | int count = 0; 11 | int rows = grid.length; 12 | int cols = grid[0].length; 13 | 14 | for (int i = 0; i < rows; i++) { 15 | for (int j = 0; j < cols; j++) { 16 | if (grid[i][j] == '1') { 17 | dfs(grid, i, j); 18 | count++; 19 | } 20 | } 21 | } 22 | 23 | return count; 24 | } 25 | 26 | private void dfs(char[][] grid, int i, int j) { 27 | if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') { 28 | return; 29 | } 30 | 31 | grid[i][j] = '0'; 32 | dfs(grid, i + 1, j); 33 | dfs(grid, i - 1, j); 34 | dfs(grid, i, j + 1); 35 | dfs(grid, i, j - 1); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /0200-number-of-islands/0200-number-of-islands.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @param {character[][]} grid 4 | * @return {number} 5 | */ 6 | var numIslands = function(grid) { 7 | if (!grid || grid.length === 0) { 8 | return 0; 9 | } 10 | 11 | let count = 0; 12 | 13 | for (let i = 0; i < grid.length; i++) { 14 | for (let j = 0; j < grid[0].length; j++) { 15 | if (grid[i][j] === '1') { 16 | dfs(grid, i, j); 17 | count++; 18 | } 19 | } 20 | } 21 | 22 | return count; 23 | }; 24 | 25 | function dfs(grid, i, j) { 26 | if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] === '0') { 27 | return; 28 | } 29 | 30 | grid[i][j] = '0'; 31 | dfs(grid, i + 1, j); 32 | dfs(grid, i - 1, j); 33 | dfs(grid, i, j + 1); 34 | dfs(grid, i, j - 1); 35 | } 36 | -------------------------------------------------------------------------------- /0200-number-of-islands/0200-number-of-islands.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numIslands(self, grid: List[List[str]]) -> int: 3 | if not grid: 4 | return 0 5 | 6 | # Depth First Search (DFS) function to mark visited land 7 | def dfs(i, j): 8 | # Base case: if the index is out of bounds or the cell is water ('0'), return 9 | if (i < 0 or i >= len(grid) or 10 | j < 0 or j >= len(grid[0]) or grid[i][j] == '0'): 11 | return 12 | 13 | grid[i][j] = '0' # Mark as visited 14 | dfs(i+1, j) 15 | dfs(i-1, j) 16 | dfs(i, j+1) 17 | dfs(i, j-1) 18 | 19 | count = 0 20 | 21 | # Iterate through each cell in the grid 22 | for i in range(len(grid)): 23 | for j in range(len(grid[0])): 24 | if grid[i][j] == '1': 25 | dfs(i, j) 26 | count += 1 27 | 28 | return count 29 | 30 | 31 | #Question: https://leetcode.com/problems/number-of-islands 32 | #Blog: https://blog.unwiredlearning.com/number-of-islands -------------------------------------------------------------------------------- /0206-reverse-linked-list/0206-reverse-linked-list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct ListNode { 4 | int val; 5 | ListNode* next; 6 | ListNode(int x) : val(x), next(nullptr) {} 7 | }; 8 | 9 | class Solution { 10 | public: 11 | ListNode* reverseList(ListNode* head) { 12 | ListNode* previous = nullptr; 13 | ListNode* current = head; 14 | 15 | while (current != nullptr) { 16 | ListNode* temp = current->next; 17 | current->next = previous; 18 | previous = current; 19 | current = temp; 20 | } 21 | 22 | return previous; 23 | } 24 | }; -------------------------------------------------------------------------------- /0206-reverse-linked-list/0206-reverse-linked-list.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | ListNode(int val) { 5 | this.val = val; 6 | this.next = null; 7 | } 8 | } 9 | 10 | class Solution { 11 | public ListNode reverseList(ListNode head) { 12 | ListNode previous = null; 13 | ListNode current = head; 14 | 15 | while (current != null) { 16 | ListNode temp = current.next; 17 | current.next = previous; 18 | previous = current; 19 | current = temp; 20 | } 21 | 22 | return previous; 23 | } 24 | } -------------------------------------------------------------------------------- /0206-reverse-linked-list/0206-reverse-linked-list.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.next = null; 5 | } 6 | } 7 | 8 | function reverseList(head) { 9 | let previous = null; 10 | let current = head; 11 | 12 | while (current !== null) { 13 | let temp = current.next; 14 | current.next = previous; 15 | previous = current; 16 | current = temp; 17 | } 18 | 19 | return previous; 20 | } -------------------------------------------------------------------------------- /0208-implement-trie-prefix-tree/0208-implement-trie-prefix-tree.js: -------------------------------------------------------------------------------- 1 | class TrieNode { 2 | constructor() { 3 | this.children = {}; 4 | this.isEnd = false; 5 | } 6 | } 7 | 8 | class Trie { 9 | constructor() { 10 | this.root = new TrieNode(); 11 | } 12 | 13 | insert(word) { 14 | let node = this.root; 15 | for (let char of word) { 16 | if (!node.children[char]) { 17 | node.children[char] = new TrieNode(); 18 | } 19 | node = node.children[char]; 20 | } 21 | node.isEnd = true; 22 | } 23 | 24 | search(word) { 25 | let node = this.root; 26 | for (let char of word) { 27 | if (!node.children[char]) { 28 | return false; 29 | } 30 | node = node.children[char]; 31 | } 32 | return node.isEnd; 33 | } 34 | 35 | startsWith(prefix) { 36 | let node = this.root; 37 | for (let char of prefix) { 38 | if (!node.children[char]) { 39 | return false; 40 | } 41 | node = node.children[char]; 42 | } 43 | return true; 44 | } 45 | } -------------------------------------------------------------------------------- /0213-house-robber-ii/0213-house-robber-ii.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | if not nums: 4 | return 0 5 | if len(nums) == 1: 6 | return nums[0] 7 | 8 | # Create 2 new lists 9 | skip_last_house = nums[:-1] 10 | skip_first_house = nums[1:] 11 | 12 | # Get the loot from both possibilities 13 | loot_skipping_last = self.rob_helper(skip_last_house) 14 | loot_skipping_first = self.rob_helper(skip_first_house) 15 | 16 | # Return the maximum of 2 loots 17 | return max(loot_skipping_last, loot_skipping_first) 18 | 19 | def rob_helper(self, nums): 20 | if len(nums) == 1: 21 | return nums[0] 22 | 23 | dp = [0] * len(nums) 24 | dp[0] = nums[0] 25 | dp[1] = max(nums[0], nums[1]) 26 | 27 | for i in range(2, len(nums)): 28 | dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]) 29 | 30 | return dp[-1] 31 | 32 | 33 | #Question: https://leetcode.com/problems/house-robber-ii 34 | #Blog: https://blog.unwiredlearning.com/house-robber-ii -------------------------------------------------------------------------------- /0217-contains-duplicate/0217-contains-duplicate.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | class ContainsDuplicate { 6 | public: 7 | bool containsDuplicate(std::vector& nums) { 8 | std::unordered_set seen; 9 | for (int num : nums) { 10 | if (seen.find(num) != seen.end()) { 11 | return true; 12 | } 13 | seen.insert(num); 14 | } 15 | return false; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /0217-contains-duplicate/0217-contains-duplicate.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashSet; 3 | 4 | public class ContainsDuplicate { 5 | public boolean containsDuplicate(int[] nums) { 6 | HashSet seen = new HashSet<>(); 7 | for (int num : nums) { 8 | if (seen.contains(num)) { 9 | return true; 10 | } 11 | seen.add(num); 12 | } 13 | return false; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /0217-contains-duplicate/0217-contains-duplicate.js: -------------------------------------------------------------------------------- 1 | 2 | function containsDuplicate(nums) { 3 | const seen = new Set(); 4 | for (let num of nums) { 5 | if (seen.has(num)) { 6 | return true; 7 | } 8 | seen.add(num); 9 | } 10 | return false; 11 | } 12 | -------------------------------------------------------------------------------- /0217-contains-duplicate/0217-contains-duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | # Create an empty set to store unique numbers 4 | num_set = set() 5 | 6 | for num in nums: 7 | if num in num_set: 8 | return True 9 | num_set.add(num) 10 | 11 | return False 12 | 13 | 14 | #Question: https://leetcode.com/problems/contains-duplicate 15 | #Blog: https://blog.unwiredlearning.com/contains-duplicate -------------------------------------------------------------------------------- /0226-invert-binary-tree/0226-invert-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct TreeNode { 4 | int val; 5 | TreeNode* left; 6 | TreeNode* right; 7 | 8 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | TreeNode* invertTree(TreeNode* root) { 14 | if (root == nullptr) { 15 | return nullptr; 16 | } 17 | 18 | // Swap the left and right children 19 | TreeNode* temp = root->left; 20 | root->left = root->right; 21 | root->right = temp; 22 | 23 | // Recursively invert the left and right subtree 24 | invertTree(root->left); 25 | invertTree(root->right); 26 | 27 | return root; 28 | } 29 | }; -------------------------------------------------------------------------------- /0226-invert-binary-tree/0226-invert-binary-tree.java: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | 6 | TreeNode(int val) { 7 | this.val = val; 8 | this.left = null; 9 | this.right = null; 10 | } 11 | } 12 | 13 | public class Solution { 14 | public TreeNode invertTree(TreeNode root) { 15 | if (root == null) { 16 | return null; 17 | } 18 | 19 | // Swap the left and right children 20 | TreeNode temp = root.left; 21 | root.left = root.right; 22 | root.right = temp; 23 | 24 | // Recursively invert the left and right subtree 25 | invertTree(root.left); 26 | invertTree(root.right); 27 | 28 | return root; 29 | } 30 | } -------------------------------------------------------------------------------- /0226-invert-binary-tree/0226-invert-binary-tree.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | function invertTree(root) { 10 | if (root === null) { 11 | return null; 12 | } 13 | 14 | // Swap the left and right children 15 | [root.left, root.right] = [root.right, root.left]; 16 | 17 | // Recursively invert the left and right subtree 18 | invertTree(root.left); 19 | invertTree(root.right); 20 | 21 | return root; 22 | } -------------------------------------------------------------------------------- /0226-invert-binary-tree/0226-invert-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | 8 | class Solution: 9 | def invertTree(self, root: TreeNode) -> TreeNode: 10 | 11 | if root is None: 12 | return None 13 | 14 | # Swap the left and right children 15 | root.left, root.right = root.right, root.left 16 | 17 | # Recursively invert the left and right subtree 18 | self.invertTree(root.left) 19 | self.invertTree(root.right) 20 | 21 | return root 22 | 23 | 24 | #Question: https://leetcode.com/problems/invert-binary-tree 25 | #Blog: https://blog.unwiredlearning.com/invert-binary-tree -------------------------------------------------------------------------------- /0230-kth-smallest-element-in-a-bst/0230-kth-smallest-element-in-a-bst.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct TreeNode { 4 | int val; 5 | TreeNode *left; 6 | TreeNode *right; 7 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 8 | }; 9 | 10 | class Solution { 11 | public: 12 | int kthSmallest(TreeNode* root, int k) { 13 | std::vector ioList; 14 | inOrderTraversal(root, ioList); 15 | return ioList[k - 1]; 16 | } 17 | 18 | private: 19 | void inOrderTraversal(TreeNode* node, std::vector& ioList) { 20 | if (node == nullptr) { 21 | return; 22 | } 23 | 24 | inOrderTraversal(node->left, ioList); 25 | ioList.push_back(node->val); 26 | inOrderTraversal(node->right, ioList); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /0230-kth-smallest-element-in-a-bst/0230-kth-smallest-element-in-a-bst.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | 8 | TreeNode(int val) { 9 | this.val = val; 10 | this.left = null; 11 | this.right = null; 12 | } 13 | } 14 | 15 | class Solution { 16 | public int kthSmallest(TreeNode root, int k) { 17 | List ioList = new ArrayList<>(); 18 | inOrderTraversal(root, ioList); 19 | return ioList.get(k - 1); 20 | } 21 | 22 | private void inOrderTraversal(TreeNode node, List ioList) { 23 | if (node == null) { 24 | return; 25 | } 26 | 27 | inOrderTraversal(node.left, ioList); 28 | ioList.add(node.val); 29 | inOrderTraversal(node.right, ioList); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /0230-kth-smallest-element-in-a-bst/0230-kth-smallest-element-in-a-bst.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val, left = null, right = null) { 3 | this.val = val; 4 | this.left = left; 5 | this.right = right; 6 | } 7 | } 8 | 9 | class Solution { 10 | kthSmallest(root, k) { 11 | const ioList = []; 12 | this.inOrderTraversal(root, ioList); 13 | return ioList[k - 1]; 14 | } 15 | 16 | inOrderTraversal(node, ioList) { 17 | if (node === null) { 18 | return; 19 | } 20 | 21 | this.inOrderTraversal(node.left, ioList); 22 | ioList.push(node.val); 23 | this.inOrderTraversal(node.right, ioList); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /0230-kth-smallest-element-in-a-bst/0230-kth-smallest-element-in-a-bst.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | 8 | class Solution: 9 | def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: 10 | # List to store the values of nodes in in-order traversal 11 | io_list = [] 12 | 13 | # Populate the io_list with the in-order traversal of the tree 14 | self.helper(root, io_list) 15 | 16 | return io_list[k-1] 17 | 18 | def helper(self, tree_node, io_list): 19 | # Base case: if the node is None, return 20 | if tree_node is None: 21 | return 22 | 23 | self.helper(tree_node.left, io_list) 24 | io_list.append(tree_node.val) 25 | self.helper(tree_node.right, io_list) 26 | 27 | 28 | #Question: https://leetcode.com/problems/kth-smallest-element-in-a-bst 29 | #Blog: https://blog.unwiredlearning.com/kth-smallest-element-in-a-bst -------------------------------------------------------------------------------- /0235-lowest-common-ancestor-of-a-binary-search-tree/0235-lowest-common-ancestor-of-a-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 14 | while (root != nullptr) { 15 | // If both p and q are greater than root, go to right subtree 16 | if (p->val > root->val && q->val > root->val) { 17 | root = root->right; 18 | } 19 | // If both p and q are lesser than root, go to left subtree 20 | else if (p->val < root->val && q->val < root->val) { 21 | root = root->left; 22 | } else { 23 | // We have found the split point, i.e. the LCA node. 24 | return root; 25 | } 26 | } 27 | return nullptr; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /0235-lowest-common-ancestor-of-a-binary-search-tree/0235-lowest-common-ancestor-of-a-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | TreeNode(int x) { val = x; } 6 | } 7 | 8 | public class Solution { 9 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 10 | while (root != null) { 11 | // If both p and q are greater than root, go to right subtree 12 | if (p.val > root.val && q.val > root.val) { 13 | root = root.right; 14 | } 15 | // If both p and q are lesser than root, go to left subtree 16 | else if (p.val < root.val && q.val < root.val) { 17 | root = root.left; 18 | } else { 19 | // We have found the split point, i.e. the LCA node. 20 | return root; 21 | } 22 | } 23 | return null; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /0235-lowest-common-ancestor-of-a-binary-search-tree/0235-lowest-common-ancestor-of-a-binary-search-tree.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | class Solution { 10 | lowestCommonAncestor(root, p, q) { 11 | while (root !== null) { 12 | // If both p and q are greater than root, go to right subtree 13 | if (p.val > root.val && q.val > root.val) { 14 | root = root.right; 15 | } 16 | // If both p and q are lesser than root, go to left subtree 17 | else if (p.val < root.val && q.val < root.val) { 18 | root = root.left; 19 | } else { 20 | // We have found the split point, i.e. the LCA node. 21 | return root; 22 | } 23 | } 24 | return null; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /0235-lowest-common-ancestor-of-a-binary-search-tree/0235-lowest-common-ancestor-of-a-binary-search-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution: 9 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 10 | while root: 11 | 12 | # If both p and q are greater than root, go to right subtree 13 | if p.val > root.val and q.val > root.val: 14 | root = root.right 15 | 16 | # If both p and q are lesser than root, go to left subtree 17 | elif p.val < root.val and q.val < root.val: 18 | root = root.left 19 | 20 | else: 21 | # We have found the split point, i.e. the LCA node. 22 | return root 23 | 24 | 25 | #Question: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree 26 | #Blog: https://blog.unwiredlearning.com/lowest-common-ancestor-of-a-binary-search-tree -------------------------------------------------------------------------------- /0238-product-of-array-except-self/0238-product-of-array-except-self.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | class Solution { 5 | public: 6 | std::vector productExceptSelf(std::vector& nums) { 7 | int n = nums.size(); 8 | 9 | // Array to store all left multiplication 10 | std::vector left(n, 1); 11 | for (int i = 1; i < n; i++) { 12 | left[i] = left[i - 1] * nums[i - 1]; 13 | } 14 | 15 | // Array to store all right multiplication 16 | std::vector right(n, 1); 17 | for (int i = n - 2; i >= 0; i--) { 18 | right[i] = right[i + 1] * nums[i + 1]; 19 | } 20 | 21 | // Calculate the result array by multiplying left and right products 22 | std::vector result(n); 23 | for (int i = 0; i < n; i++) { 24 | result[i] = left[i] * right[i]; 25 | } 26 | 27 | return result; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /0238-product-of-array-except-self/0238-product-of-array-except-self.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | class Solution { 5 | public int[] productExceptSelf(int[] nums) { 6 | int n = nums.length; 7 | 8 | // Array to store all left multiplication 9 | int[] left = new int[n]; 10 | Arrays.fill(left, 1); 11 | for (int i = 1; i < n; i++) { 12 | left[i] = left[i - 1] * nums[i - 1]; 13 | } 14 | 15 | // Array to store all right multiplication 16 | int[] right = new int[n]; 17 | Arrays.fill(right, 1); 18 | for (int i = n - 2; i >= 0; i--) { 19 | right[i] = right[i + 1] * nums[i + 1]; 20 | } 21 | 22 | // Calculate the result array by multiplying left and right products 23 | int[] result = new int[n]; 24 | for (int i = 0; i < n; i++) { 25 | result[i] = left[i] * right[i]; 26 | } 27 | 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /0238-product-of-array-except-self/0238-product-of-array-except-self.js: -------------------------------------------------------------------------------- 1 | 2 | function productExceptSelf(nums) { 3 | const n = nums.length; 4 | 5 | // Array to store all left multiplication 6 | const left = Array(n).fill(1); 7 | for (let i = 1; i < n; i++) { 8 | left[i] = left[i - 1] * nums[i - 1]; 9 | } 10 | 11 | // Array to store all right multiplication 12 | const right = Array(n).fill(1); 13 | for (let i = n - 2; i >= 0; i--) { 14 | right[i] = right[i + 1] * nums[i + 1]; 15 | } 16 | 17 | // Calculate the result array by multiplying left and right products 18 | const result = Array(n); 19 | for (let i = 0; i < n; i++) { 20 | result[i] = left[i] * right[i]; 21 | } 22 | 23 | return result; 24 | } 25 | -------------------------------------------------------------------------------- /0238-product-of-array-except-self/0238-product-of-array-except-self.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | n = len(nums) 4 | 5 | # Array to store all left multiplication 6 | left = [1] * n 7 | for i in range(1, n): 8 | left[i] = left[i - 1] * nums[i - 1] 9 | 10 | # Array to store all right multiplication 11 | right = [1] * n 12 | for i in range(n - 2, -1, -1): 13 | right[i] = right[i + 1] * nums[i + 1] 14 | 15 | result = [1] * n 16 | for i in range(n): 17 | result[i] = left[i] * right[i] 18 | 19 | return result 20 | 21 | 22 | #Question: https://leetcode.com/problems/product-of-array-except-self 23 | #Blog: https://blog.unwiredlearning.com/product-of-array-except-self -------------------------------------------------------------------------------- /0242-valid-anagram/0242-valid-anagram.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | bool isAnagram(std::string s, std::string t) { 7 | if (s.length() != t.length()) { 8 | return false; 9 | } 10 | 11 | std::unordered_map count; 12 | 13 | for (char c : s) { 14 | count[c]++; 15 | } 16 | 17 | for (char c : t) { 18 | if (count.find(c) == count.end()) { 19 | return false; 20 | } 21 | count[c]--; 22 | if (count[c] < 0) { 23 | return false; 24 | } 25 | } 26 | 27 | return true; 28 | } 29 | 30 | int main() { 31 | std::cout << std::boolalpha << isAnagram("anagram", "nagaram") << std::endl; // true 32 | std::cout << std::boolalpha << isAnagram("rat", "car") << std::endl; // false 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /0242-valid-anagram/0242-valid-anagram.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.HashMap; 3 | 4 | public class ValidAnagram { 5 | public static boolean isAnagram(String s, String t) { 6 | if (s.length() != t.length()) { 7 | return false; 8 | } 9 | 10 | HashMap count = new HashMap<>(); 11 | 12 | for (char c : s.toCharArray()) { 13 | count.put(c, count.getOrDefault(c, 0) + 1); 14 | } 15 | 16 | for (char c : t.toCharArray()) { 17 | if (!count.containsKey(c)) { 18 | return false; 19 | } 20 | count.put(c, count.get(c) - 1); 21 | if (count.get(c) < 0) { 22 | return false; 23 | } 24 | } 25 | 26 | return true; 27 | } 28 | 29 | public static void main(String[] args) { 30 | System.out.println(isAnagram("anagram", "nagaram")); // true 31 | System.out.println(isAnagram("rat", "car")); // false 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /0242-valid-anagram/0242-valid-anagram.js: -------------------------------------------------------------------------------- 1 | 2 | function isAnagram(s, t) { 3 | if (s.length !== t.length) { 4 | return false; 5 | } 6 | 7 | let count = {}; 8 | 9 | for (let char of s) { 10 | count[char] = (count[char] || 0) + 1; 11 | } 12 | 13 | for (let char of t) { 14 | if (!count[char]) { 15 | return false; 16 | } 17 | count[char]--; 18 | if (count[char] < 0) { 19 | return false; 20 | } 21 | } 22 | 23 | return true; 24 | } 25 | 26 | console.log(isAnagram("anagram", "nagaram")); // true 27 | console.log(isAnagram("rat", "car")); // false 28 | -------------------------------------------------------------------------------- /0242-valid-anagram/0242-valid-anagram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAnagram(self, str1: str, str2: str) -> bool: 3 | # Convert both to lowercase to ignore case match 4 | str1 = str1.lower() 5 | str2 = str2.lower() 6 | 7 | # Strip off all the white spaces 8 | str1 = str1.replace(" ", "") 9 | str2 = str2.replace(" ", "") 10 | 11 | # Initialize the bucket array 12 | counts = [0] * 26 13 | 14 | # Fill the buckets 15 | for char in str1: 16 | counts[ord(char) - ord('a')] += 1 17 | 18 | # Empty the buckets 19 | for char in str2: 20 | counts[ord(char) - ord('a')] -= 1 21 | 22 | # Check if all buckets are empty 23 | for count in counts: 24 | if count != 0: 25 | return False 26 | 27 | return True 28 | 29 | 30 | #Question: https://leetcode.com/problems/valid-anagram 31 | #Blog: https://blog.unwiredlearning.com/valid-anagram -------------------------------------------------------------------------------- /0252-meeting-rooms/0252-meeting-rooms.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | bool canAttendMeetings(std::vector> intervals) { 7 | std::sort(intervals.begin(), intervals.end()); 8 | 9 | for (int i = 1; i < intervals.size(); i++) { 10 | if (intervals[i].first < intervals[i - 1].second) { 11 | return false; 12 | } 13 | } 14 | 15 | return true; 16 | } 17 | 18 | int main() { 19 | std::vector> intervals = {{0, 30}, {5, 10}, {15, 20}}; 20 | std::cout << (canAttendMeetings(intervals) ? "true" : "false") << std::endl; 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /0252-meeting-rooms/0252-meeting-rooms.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | public class MeetingRooms { 5 | public static boolean canAttendMeetings(int[][] intervals) { 6 | Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); 7 | 8 | for (int i = 1; i < intervals.length; i++) { 9 | if (intervals[i][0] < intervals[i - 1][1]) { 10 | return false; 11 | } 12 | } 13 | 14 | return true; 15 | } 16 | 17 | public static void main(String[] args) { 18 | int[][] intervals = {{0, 30}, {5, 10}, {15, 20}}; 19 | System.out.println(canAttendMeetings(intervals)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /0252-meeting-rooms/0252-meeting-rooms.js: -------------------------------------------------------------------------------- 1 | 2 | function canAttendMeetings(intervals) { 3 | intervals.sort((a, b) => a[0] - b[0]); 4 | 5 | for (let i = 1; i < intervals.length; i++) { 6 | if (intervals[i][0] < intervals[i - 1][1]) { 7 | return false; 8 | } 9 | } 10 | 11 | return true; 12 | } 13 | 14 | // Example usage: 15 | let intervals = [[0, 30], [5, 10], [15, 20]]; 16 | console.log(canAttendMeetings(intervals)); 17 | -------------------------------------------------------------------------------- /0252-meeting-rooms/0252-meeting-rooms.py: -------------------------------------------------------------------------------- 1 | def can_attend_meetings(intervals): 2 | intervals.sort() 3 | 4 | for i in range(1, len(intervals)): 5 | if intervals[i][0] < intervals[i - 1][1]: 6 | return False 7 | 8 | return True 9 | 10 | 11 | #Question: https://www.lintcode.com/problem/920/ 12 | #Blog: https://blog.unwiredlearning.com/meeting-rooms -------------------------------------------------------------------------------- /0253-meeting-rooms-ii/0253-meeting-rooms-ii.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | int minMeetingRooms(std::vector> intervals) { 7 | std::vector start_times, end_times; 8 | 9 | for (const auto& interval : intervals) { 10 | start_times.push_back(interval.first); 11 | end_times.push_back(interval.second); 12 | } 13 | 14 | std::sort(start_times.begin(), start_times.end()); 15 | std::sort(end_times.begin(), end_times.end()); 16 | 17 | int start_pointer = 0, end_pointer = 0, used_rooms = 0, max_rooms = 0; 18 | 19 | while (start_pointer < intervals.size()) { 20 | if (start_times[start_pointer] < end_times[end_pointer]) { 21 | used_rooms++; 22 | start_pointer++; 23 | } else { 24 | used_rooms--; 25 | end_pointer++; 26 | } 27 | max_rooms = std::max(max_rooms, used_rooms); 28 | } 29 | 30 | return max_rooms; 31 | } 32 | 33 | int main() { 34 | std::vector> intervals = {{0, 30}, {5, 10}, {15, 20}}; 35 | std::cout << minMeetingRooms(intervals) << std::endl; 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /0253-meeting-rooms-ii/0253-meeting-rooms-ii.js: -------------------------------------------------------------------------------- 1 | 2 | function minMeetingRooms(intervals) { 3 | let start_times = intervals.map(interval => interval[0]); 4 | let end_times = intervals.map(interval => interval[1]); 5 | 6 | start_times.sort((a, b) => a - b); 7 | end_times.sort((a, b) => a - b); 8 | 9 | let start_pointer = 0, end_pointer = 0, used_rooms = 0, max_rooms = 0; 10 | 11 | while (start_pointer < intervals.length) { 12 | if (start_times[start_pointer] < end_times[end_pointer]) { 13 | used_rooms++; 14 | start_pointer++; 15 | } else { 16 | used_rooms--; 17 | end_pointer++; 18 | } 19 | max_rooms = Math.max(max_rooms, used_rooms); 20 | } 21 | 22 | return max_rooms; 23 | } 24 | 25 | // Example usage: 26 | let intervals = [[0, 30], [5, 10], [15, 20]]; 27 | console.log(minMeetingRooms(intervals)); 28 | -------------------------------------------------------------------------------- /0253-meeting-rooms-ii/0253-meeting-rooms-ii.py: -------------------------------------------------------------------------------- 1 | def minMeetingRooms(intervals): 2 | # Separate and sort start and end times 3 | start_times = sorted(interval.start for interval in intervals) 4 | end_times = sorted(interval.end for interval in intervals) 5 | 6 | start_pointer, end_pointer = 0, 0 7 | used_rooms = 0 8 | max_rooms = 0 9 | 10 | # Iterate over start times 11 | while start_pointer < len(intervals): 12 | if start_times[start_pointer] < end_times[end_pointer]: 13 | # A new room is needed 14 | used_rooms += 1 15 | start_pointer += 1 16 | else: 17 | # A room is freed up 18 | used_rooms -= 1 19 | end_pointer += 1 20 | 21 | # Update the maximum number of rooms needed 22 | max_rooms = max(max_rooms, used_rooms) 23 | 24 | return max_rooms 25 | 26 | 27 | #Question: https://www.lintcode.com/problem/919/ 28 | #Blog: https://blog.unwiredlearning.com/meeting-rooms-ii -------------------------------------------------------------------------------- /0268-missing-number/0268-missing-number.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int missingNumber(vector& nums) { 8 | int xor_result = 0; 9 | int n = nums.size(); 10 | 11 | // XOR all indices and all elements in nums 12 | for (int i = 0; i < n; i++) { 13 | xor_result = xor_result ^ i ^ nums[i]; 14 | } 15 | 16 | // Finally XOR with n (since the range is from 0 to n) 17 | xor_result = xor_result ^ n; 18 | 19 | return xor_result; 20 | } 21 | 22 | int main() { 23 | vector nums = {3, 0, 1}; 24 | cout << missingNumber(nums) << endl; // Output: 2 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /0268-missing-number/0268-missing-number.java: -------------------------------------------------------------------------------- 1 | 2 | public class MissingNumber { 3 | public static int missingNumber(int[] nums) { 4 | int xor = 0; 5 | int n = nums.length; 6 | 7 | // XOR all indices and all elements in nums 8 | for (int i = 0; i < n; i++) { 9 | xor = xor ^ i ^ nums[i]; 10 | } 11 | 12 | // Finally XOR with n (since the range is from 0 to n) 13 | xor = xor ^ n; 14 | 15 | return xor; 16 | } 17 | 18 | public static void main(String[] args) { 19 | int[] nums = {3, 0, 1}; 20 | System.out.println(missingNumber(nums)); // Output: 2 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /0268-missing-number/0268-missing-number.js: -------------------------------------------------------------------------------- 1 | 2 | function missingNumber(nums) { 3 | let xor = 0; 4 | let n = nums.length; 5 | 6 | // XOR all indices and all elements in nums 7 | for (let i = 0; i < n; i++) { 8 | xor = xor ^ i ^ nums[i]; 9 | } 10 | 11 | // Finally XOR with n (since the range is from 0 to n) 12 | xor = xor ^ n; 13 | 14 | return xor; 15 | } 16 | 17 | // Example usage: 18 | let nums = [3, 0, 1]; 19 | console.log(missingNumber(nums)); // Output: 2 20 | -------------------------------------------------------------------------------- /0268-missing-number/0268-missing-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingNumber(self, nums: List[int]) -> int: 3 | xor = 0 4 | n = len(nums) 5 | 6 | # XOR all indices and all elements in nums 7 | for i in range(n): 8 | xor = xor ^ i ^ nums[i] 9 | 10 | # Finally XOR with n (since the range is from 0 to n) 11 | xor = xor ^ n 12 | 13 | return xor 14 | 15 | 16 | #Question: https://leetcode.com/problems/missing-number 17 | #Blog: https://blog.unwiredlearning.com/missing-number -------------------------------------------------------------------------------- /0300-longest-increasing-subsequence/0300-longest-increasing-subsequence.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int lengthOfLIS(vector& nums) { 10 | if (nums.empty()) { 11 | return 0; 12 | } 13 | 14 | vector dp(nums.size(), 1); 15 | int max_length = 1; 16 | 17 | for (int i = 0; i < nums.size(); ++i) { 18 | for (int j = 0; j < i; ++j) { 19 | if (nums[i] > nums[j]) { 20 | dp[i] = max(dp[i], dp[j] + 1); 21 | } 22 | } 23 | max_length = max(max_length, dp[i]); 24 | } 25 | 26 | return max_length; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /0300-longest-increasing-subsequence/0300-longest-increasing-subsequence.java: -------------------------------------------------------------------------------- 1 | 2 | public class Solution { 3 | public int lengthOfLIS(int[] nums) { 4 | if (nums.length == 0) { 5 | return 0; 6 | } 7 | 8 | int[] dp = new int[nums.length]; 9 | int max_length = 1; 10 | 11 | for (int i = 0; i < nums.length; i++) { 12 | dp[i] = 1; 13 | for (int j = 0; j < i; j++) { 14 | if (nums[i] > nums[j]) { 15 | dp[i] = Math.max(dp[i], dp[j] + 1); 16 | } 17 | } 18 | max_length = Math.max(max_length, dp[i]); 19 | } 20 | 21 | return max_length; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /0300-longest-increasing-subsequence/0300-longest-increasing-subsequence.js: -------------------------------------------------------------------------------- 1 | 2 | function lengthOfLIS(nums) { 3 | if (nums.length === 0) { 4 | return 0; 5 | } 6 | 7 | let dp = new Array(nums.length).fill(1); 8 | let max_length = 1; 9 | 10 | for (let i = 0; i < nums.length; i++) { 11 | for (let j = 0; j < i; j++) { 12 | if (nums[i] > nums[j]) { 13 | dp[i] = Math.max(dp[i], dp[j] + 1); 14 | } 15 | } 16 | max_length = Math.max(max_length, dp[i]); 17 | } 18 | 19 | return max_length; 20 | } 21 | -------------------------------------------------------------------------------- /0300-longest-increasing-subsequence/0300-longest-increasing-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLIS(self, nums: List[int]) -> int: 3 | if len(nums) == 0: 4 | return 0 5 | 6 | dp = [1 for _ in range(len(nums))] 7 | max_length = 1 8 | 9 | for i in range(len(nums)): 10 | for j in range(i): 11 | if nums[i] > nums[j]: 12 | dp[i] = max(dp[i], dp[j] + 1) 13 | max_length = max(max_length, dp[i]) 14 | 15 | return max_length 16 | 17 | 18 | #Question: https://leetcode.com/problems/longest-increasing-subsequence 19 | #Blog: https://blog.unwiredlearning.com/longest-increasing-subsequence -------------------------------------------------------------------------------- /0322-coin-change/0322-coin-change.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Solution { 5 | public: 6 | int coinChange(std::vector& coins, int amount) { 7 | std::vector dp(amount + 1, amount + 1); 8 | dp[0] = 0; 9 | 10 | for (int i = 1; i <= amount; ++i) { 11 | for (int coin : coins) { 12 | if (coin <= i) { 13 | dp[i] = std::min(dp[i], dp[i - coin] + 1); 14 | } 15 | } 16 | } 17 | 18 | return dp[amount] > amount ? -1 : dp[amount]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /0322-coin-change/0322-coin-change.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int coinChange(int[] coins, int amount) { 5 | int[] dp = new int[amount + 1]; 6 | Arrays.fill(dp, amount + 1); 7 | dp[0] = 0; 8 | 9 | for (int i = 1; i <= amount; i++) { 10 | for (int coin : coins) { 11 | if (coin <= i) { 12 | dp[i] = Math.min(dp[i], dp[i - coin] + 1); 13 | } 14 | } 15 | } 16 | 17 | return dp[amount] > amount ? -1 : dp[amount]; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /0322-coin-change/0322-coin-change.js: -------------------------------------------------------------------------------- 1 | function coinChange(coins, amount) { 2 | const dp = new Array(amount + 1).fill(amount + 1); 3 | dp[0] = 0; 4 | 5 | for (let i = 1; i <= amount; i++) { 6 | for (let coin of coins) { 7 | if (coin <= i) { 8 | dp[i] = Math.min(dp[i], dp[i - coin] + 1); 9 | } 10 | } 11 | } 12 | 13 | return dp[amount] > amount ? -1 : dp[amount]; 14 | } 15 | -------------------------------------------------------------------------------- /0322-coin-change/0322-coin-change.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def coinChange(self, coins: List[int], amount: int) -> int: 3 | dp = [amount + 1] * (amount + 1) 4 | dp[0] = 0 5 | 6 | for i in range(1, amount + 1): 7 | for coin in coins: 8 | if coin <= i: 9 | dp[i] = min(dp[i], dp[i - coin] + 1) 10 | 11 | # No solution exists, return -1. 12 | if dp[amount] == amount + 1: 13 | return -1 14 | 15 | return dp[amount] 16 | 17 | 18 | #Question: https://leetcode.com/problems/coin-change 19 | #Blog: https://blog.unwiredlearning.com/coin-change -------------------------------------------------------------------------------- /0323-number-of-connected-components-in-an-undirected-graph/0323-number-of-connected-components-in-an-undirected-graph.py: -------------------------------------------------------------------------------- 1 | def countComponents(n, edges): 2 | def dfs(node): 3 | # If the node is already visited, return to avoid cycles 4 | if visited[node]: 5 | return 6 | 7 | visited[node] = True 8 | for neighbor in graph[node]: 9 | dfs(neighbor) 10 | 11 | # Initialize a graph represented as an adjacency list 12 | graph = {i: [] for i in range(n)} # n nodes with ids 0 to n-1 13 | 14 | # Populate the graph with the given edges 15 | for u, v in edges: 16 | graph[u].append(v) 17 | graph[v].append(u) 18 | 19 | visited = [False] * n 20 | components = 0 21 | 22 | # Iterate through each node in the graph 23 | for i in range(n): 24 | # If a node is unvisited, it's part of a new component 25 | if not visited[i]: 26 | dfs(i) 27 | components += 1 28 | 29 | return components 30 | 31 | 32 | #Question: https://www.lintcode.com/problem/3651/ 33 | #Blog: https://blog.unwiredlearning.com/number-of-connected-components-in-an-undirected-graph -------------------------------------------------------------------------------- /0338-counting-bits/0338-counting-bits.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | vector countBits(int n) { 8 | vector result(n + 1, 0); 9 | 10 | if (n == 0) { 11 | return result; 12 | } 13 | 14 | result[1] = 1; 15 | 16 | for (int i = 2; i <= n; i++) { 17 | if (i % 2 == 0) { 18 | result[i] = result[i / 2]; 19 | } else { 20 | result[i] = result[i / 2] + 1; 21 | } 22 | } 23 | 24 | return result; 25 | } 26 | 27 | int main() { 28 | int n = 5; 29 | vector result = countBits(n); 30 | 31 | for (int val : result) { 32 | cout << val << " "; 33 | } 34 | cout << endl; 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /0338-counting-bits/0338-counting-bits.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | 4 | public class CountingBits { 5 | public static int[] countBits(int n) { 6 | int[] result = new int[n + 1]; 7 | if (n == 0) { 8 | return result; 9 | } 10 | 11 | result[1] = 1; 12 | 13 | for (int i = 2; i <= n; i++) { 14 | if (i % 2 == 0) { 15 | result[i] = result[i / 2]; 16 | } else { 17 | result[i] = result[i / 2] + 1; 18 | } 19 | } 20 | 21 | return result; 22 | } 23 | 24 | public static void main(String[] args) { 25 | int n = 5; 26 | System.out.println(Arrays.toString(countBits(n))); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /0338-counting-bits/0338-counting-bits.js: -------------------------------------------------------------------------------- 1 | 2 | function countBits(n) { 3 | let result = new Array(n + 1).fill(0); 4 | 5 | if (n === 0) { 6 | return result; 7 | } 8 | 9 | result[1] = 1; 10 | 11 | for (let i = 2; i <= n; i++) { 12 | if (i % 2 === 0) { 13 | result[i] = result[Math.floor(i / 2)]; 14 | } else { 15 | result[i] = result[Math.floor(i / 2)] + 1; 16 | } 17 | } 18 | 19 | return result; 20 | } 21 | 22 | // Example usage: 23 | let n = 5; 24 | console.log(countBits(n)); 25 | -------------------------------------------------------------------------------- /0338-counting-bits/0338-counting-bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countBits(self, n: int) -> List[int]: 3 | # Initialize a list to store the result 4 | result = [0] * (n + 1) 5 | 6 | # If n is 0, simply return the result list (which is [0]) 7 | if n == 0: 8 | return result 9 | 10 | # The number of 1's in the binary representation of 1 is 1 11 | result[1] = 1 12 | 13 | # Loop through numbers from 2 to n 14 | for i in range(2, n + 1): 15 | if i % 2 == 0: 16 | result[i] = result[i // 2] 17 | else: 18 | result[i] = result[i // 2] + 1 19 | 20 | return result 21 | 22 | 23 | #Question: https://leetcode.com/problems/counting-bits 24 | #Blog: https://blog.unwiredlearning.com/counting-bits -------------------------------------------------------------------------------- /0347-top-k-frequent-elements/0347-top-k-frequent-elements.js: -------------------------------------------------------------------------------- 1 | function topKFrequent(nums, k) { 2 | // Step 1: Count the frequency of each element 3 | const count = new Map(); 4 | for (const num of nums) { 5 | count.set(num, (count.get(num) || 0) + 1); 6 | } 7 | 8 | // Step 2: Use a priority queue (heap) to find the k most frequent elements 9 | const heap = new MinPriorityQueue({ priority: (a) => count.get(a) }); 10 | for (const [key] of count) { 11 | heap.enqueue(key); 12 | if (heap.size() > k) { 13 | heap.dequeue(); 14 | } 15 | } 16 | 17 | // Step 3: Build output list from the heap 18 | const result = []; 19 | while (heap.size() > 0) { 20 | result.push(heap.dequeue().element); 21 | } 22 | return result.reverse(); 23 | } 24 | 25 | // Example usage 26 | const nums = [1, 1, 1, 2, 2, 3]; 27 | const k = 2; 28 | console.log(topKFrequent(nums, k)); 29 | -------------------------------------------------------------------------------- /0347-top-k-frequent-elements/0347-top-k-frequent-elements.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 3 | # Initialize bucket as a list of empty lists 4 | bucket = [[] for _ in range(len(nums) + 1)] 5 | frequencyMap = {} 6 | 7 | # Fill frequencyMap 8 | for n in nums: 9 | if n not in frequencyMap: 10 | frequencyMap[n] = 1 11 | else: 12 | frequencyMap[n] += 1 13 | 14 | # Fill bucket 15 | for key, frequency in frequencyMap.items(): 16 | bucket[frequency].append(key) 17 | 18 | result = [] 19 | # Iterate through bucket in reverse to get top k frequent elements 20 | for i in reversed(range(len(bucket))): 21 | if bucket[i]: 22 | for value in bucket[i]: 23 | if len(result) < k: 24 | result.append(value) 25 | else: 26 | return result 27 | return result 28 | 29 | 30 | #Question: https://leetcode.com/problems/top-k-frequent-elements 31 | #Blog: https://blog.unwiredlearning.com/top-k-frequent-elements -------------------------------------------------------------------------------- /0371-sum-of-two-integers/0371-sum-of-two-integers.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | using namespace std; 5 | 6 | int getSum(int a, int b) { 7 | // 32-bit integer max value 8 | int MAX = 0x7FFFFFFF; 9 | 10 | // Mask to get 32 bits 11 | unsigned int mask = 0xFFFFFFFF; 12 | 13 | while (b != 0) { 14 | // Calculate the carry bits 15 | unsigned int carry = (a & b) & mask; 16 | 17 | // XOR the bits for sum without carry 18 | a = (a ^ b) & mask; 19 | 20 | // Shift the carry to add in the next higher bit position 21 | b = (carry << 1) & mask; 22 | } 23 | 24 | // If a is negative, return a's complement in 32-bit format 25 | return a <= MAX ? a : ~(a ^ mask); 26 | } 27 | 28 | int main() { 29 | int a = 1, b = 2; 30 | cout << getSum(a, b) << endl; // Output: 3 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /0371-sum-of-two-integers/0371-sum-of-two-integers.java: -------------------------------------------------------------------------------- 1 | 2 | public class SumOfTwoIntegers { 3 | public static int getSum(int a, int b) { 4 | // 32-bit integer max value 5 | int MAX = 0x7FFFFFFF; 6 | 7 | // Mask to get 32 bits 8 | int mask = 0xFFFFFFFF; 9 | 10 | while (b != 0) { 11 | // Calculate the carry bits 12 | int carry = (a & b) & mask; 13 | 14 | // XOR the bits for sum without carry 15 | a = (a ^ b) & mask; 16 | 17 | // Shift the carry to add in the next higher bit position 18 | b = (carry << 1) & mask; 19 | } 20 | 21 | // If a is negative, return a's complement in 32-bit format 22 | return a <= MAX ? a : ~(a ^ mask); 23 | } 24 | 25 | public static void main(String[] args) { 26 | int a = 1, b = 2; 27 | System.out.println(getSum(a, b)); // Output: 3 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /0371-sum-of-two-integers/0371-sum-of-two-integers.js: -------------------------------------------------------------------------------- 1 | 2 | function getSum(a, b) { 3 | // 32-bit integer max value 4 | const MAX = 0x7FFFFFFF; 5 | 6 | // Mask to get 32 bits 7 | const mask = 0xFFFFFFFF; 8 | 9 | while (b !== 0) { 10 | // Calculate the carry bits 11 | let carry = (a & b) & mask; 12 | 13 | // XOR the bits for sum without carry 14 | a = (a ^ b) & mask; 15 | 16 | // Shift the carry to add in the next higher bit position 17 | b = (carry << 1) & mask; 18 | } 19 | 20 | // If a is negative, return a's complement in 32-bit format 21 | return a <= MAX ? a : ~(a ^ mask); 22 | } 23 | 24 | // Example usage: 25 | let a = 1, b = 2; 26 | console.log(getSum(a, b)); // Output: 3 27 | -------------------------------------------------------------------------------- /0371-sum-of-two-integers/0371-sum-of-two-integers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getSum(self, a: int, b: int) -> int: 3 | # 32-bit integer max value 4 | MAX = 0x7FFFFFFF 5 | 6 | # Mask to get 32 bits 7 | mask = 0xFFFFFFFF 8 | 9 | while b != 0: 10 | # Calculate the carry bits 11 | carry = (a & b) & mask 12 | 13 | # XOR the bits for sum without carry 14 | a = (a ^ b) & mask 15 | 16 | # Shift the carry to add in the next higher bit position 17 | b = (carry << 1) & mask 18 | 19 | # If a is negative, return a's complement in Python's 32-bit format 20 | return a if a <= MAX else ~(a ^ mask) 21 | 22 | 23 | #Question: https://leetcode.com/problems/sum-of-two-integers 24 | #Blog: https://blog.unwiredlearning.com/sum-of-two-integers -------------------------------------------------------------------------------- /0392-is-subsequence/0392-is-subsequence.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | bool isSubsequence(string str1, string str2) { 5 | int itr1 = 0, itr2 = 0; 6 | 7 | while (itr1 < str1.length() && itr2 < str2.length()) { 8 | if (str1[itr1] == str2[itr2]) { 9 | itr1++; 10 | } 11 | itr2++; 12 | } 13 | 14 | return itr1 == str1.length(); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /0392-is-subsequence/0392-is-subsequence.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public boolean isSubsequence(String str1, String str2) { 4 | int itr1 = 0, itr2 = 0; 5 | 6 | while (itr1 < str1.length() && itr2 < str2.length()) { 7 | if (str1.charAt(itr1) == str2.charAt(itr2)) { 8 | itr1++; 9 | } 10 | itr2++; 11 | } 12 | 13 | return itr1 == str1.length(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /0392-is-subsequence/0392-is-subsequence.js: -------------------------------------------------------------------------------- 1 | 2 | function isSubsequence(str1, str2) { 3 | let itr1 = 0, itr2 = 0; 4 | 5 | while (itr1 < str1.length && itr2 < str2.length) { 6 | if (str1[itr1] === str2[itr2]) { 7 | itr1++; 8 | } 9 | itr2++; 10 | } 11 | 12 | return itr1 === str1.length; 13 | } 14 | -------------------------------------------------------------------------------- /0392-is-subsequence/0392-is-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSubsequence(self, str1: str, str2: str) -> bool: 3 | # Initialize pointers for both strings 4 | itr1, itr2 = 0, 0 5 | 6 | # We can iterate until either of them becomes zero... 7 | while itr1 < len(str1) and itr2 < len(str2): 8 | # Compare characters, increment both pointers if same 9 | if str1[itr1] == str2[itr2]: 10 | itr1 += 1 11 | itr2 += 1 12 | else: 13 | itr2 += 1 # Only increment second pointer 14 | 15 | # If it is a subsequence, 'i' will have travelled full 16 | # length of string 'str1', so just check and return 17 | return itr1 == len(str1) 18 | 19 | 20 | #Question: https://leetcode.com/problems/is-subsequence 21 | #Blog: https://blog.unwiredlearning.com/is-subsequence -------------------------------------------------------------------------------- /0424-longest-repeating-character-replacement/0424-longest-repeating-character-replacement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int characterReplacement(string s, int k) { 9 | unordered_map count; 10 | int maxLen = 0; 11 | int left = 0; 12 | int maxFreq = 0; 13 | 14 | for (int right = 0; right < s.length(); ++right) { 15 | count[s[right]]++; 16 | maxFreq = max(maxFreq, count[s[right]]); 17 | 18 | while (right - left + 1 - maxFreq > k) { 19 | count[s[left]]--; 20 | left++; 21 | } 22 | 23 | maxLen = max(maxLen, right - left + 1); 24 | } 25 | 26 | return maxLen; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /0424-longest-repeating-character-replacement/0424-longest-repeating-character-replacement.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int characterReplacement(String s, int k) { 3 | int[] count = new int[26]; 4 | int maxLen = 0; 5 | int left = 0; 6 | int maxFreq = 0; 7 | 8 | for (int right = 0; right < s.length(); right++) { 9 | count[s.charAt(right) - 'A']++; 10 | maxFreq = Math.max(maxFreq, count[s.charAt(right) - 'A']); 11 | 12 | while (right - left + 1 - maxFreq > k) { 13 | count[s.charAt(left) - 'A']--; 14 | left++; 15 | } 16 | 17 | maxLen = Math.max(maxLen, right - left + 1); 18 | } 19 | 20 | return maxLen; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /0424-longest-repeating-character-replacement/0424-longest-repeating-character-replacement.js: -------------------------------------------------------------------------------- 1 | function characterReplacement(s, k) { 2 | const count = {}; 3 | let maxLen = 0; 4 | let left = 0; 5 | let maxFreq = 0; 6 | 7 | for (let right = 0; right < s.length; right++) { 8 | const char = s[right]; 9 | count[char] = (count[char] || 0) + 1; 10 | maxFreq = Math.max(maxFreq, count[char]); 11 | 12 | while (right - left + 1 - maxFreq > k) { 13 | count[s[left]]--; 14 | left++; 15 | } 16 | 17 | maxLen = Math.max(maxLen, right - left + 1); 18 | } 19 | 20 | return maxLen; 21 | } 22 | -------------------------------------------------------------------------------- /0424-longest-repeating-character-replacement/0424-longest-repeating-character-replacement.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def characterReplacement(self, s: str, k: int) -> int: 3 | count = {} 4 | 5 | start, max_length, max_repeat = 0, 0, 0 6 | 7 | for end in range(len(s)): 8 | # Increment character count, and handle the case when key doesn't exist 9 | count[s[end]] = count.get(s[end], 0) + 1 10 | 11 | # max_repeat is the character with highest frequency 12 | max_repeat = max(max_repeat, count[s[end]]) 13 | 14 | # If characters that need to be replaced exceed k, shrink the window 15 | window = end - start + 1 16 | if (window - max_repeat) > k: 17 | count[s[start]] -= 1 18 | start += 1 19 | 20 | window = end - start + 1 21 | max_length = max(max_length, window) 22 | 23 | return max_length 24 | 25 | 26 | #Question: https://leetcode.com/problems/longest-repeating-character-replacement 27 | #Blog: https://blog.unwiredlearning.com/longest-repeating-character-replacement -------------------------------------------------------------------------------- /0435-non-overlapping-intervals/0435-non-overlapping-intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: 3 | # Sort intervals by start time 4 | intervals.sort() 5 | 6 | # Initialize the previous interval end time and count 7 | prev_end = intervals[0][1] 8 | count = 0 9 | 10 | for i in range(1, len(intervals)): 11 | if intervals[i][0] < prev_end: 12 | # Overlap detected, increment the count 13 | count += 1 14 | # Keep the interval with the smaller end to minimize future overlaps 15 | prev_end = min(prev_end, intervals[i][1]) 16 | else: 17 | # No overlap, update the prev_end to current interval's end 18 | prev_end = intervals[i][1] 19 | 20 | return count 21 | 22 | 23 | #Question: https://leetcode.com/problems/non-overlapping-intervals 24 | #Blog: https://blog.unwiredlearning.com/non-overlapping-intervals -------------------------------------------------------------------------------- /0435-non-overlapping-intervals/NonOverlappingIntervals.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Arrays; 3 | import java.util.Comparator; 4 | 5 | public class NonOverlappingIntervals { 6 | public static int eraseOverlapIntervals(int[][] intervals) { 7 | Arrays.sort(intervals, Comparator.comparingInt(a -> a[0])); 8 | 9 | int prev_end = intervals[0][1]; 10 | int count = 0; 11 | 12 | for (int i = 1; i < intervals.length; i++) { 13 | if (intervals[i][0] < prev_end) { 14 | count++; 15 | prev_end = Math.min(prev_end, intervals[i][1]); 16 | } else { 17 | prev_end = intervals[i][1]; 18 | } 19 | } 20 | 21 | return count; 22 | } 23 | 24 | public static void main(String[] args) { 25 | int[][] intervals = {{1, 2}, {2, 3}, {3, 4}, {1, 3}}; 26 | System.out.println(eraseOverlapIntervals(intervals)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /0435-non-overlapping-intervals/nonOverlappingIntervals.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | int eraseOverlapIntervals(std::vector> intervals) { 7 | std::sort(intervals.begin(), intervals.end()); 8 | 9 | int prev_end = intervals[0].second; 10 | int count = 0; 11 | 12 | for (int i = 1; i < intervals.size(); i++) { 13 | if (intervals[i].first < prev_end) { 14 | count++; 15 | prev_end = std::min(prev_end, intervals[i].second); 16 | } else { 17 | prev_end = intervals[i].second; 18 | } 19 | } 20 | 21 | return count; 22 | } 23 | 24 | int main() { 25 | std::vector> intervals = {{1, 2}, {2, 3}, {3, 4}, {1, 3}}; 26 | std::cout << eraseOverlapIntervals(intervals) << std::endl; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /0435-non-overlapping-intervals/nonOverlappingIntervals.js: -------------------------------------------------------------------------------- 1 | 2 | function eraseOverlapIntervals(intervals) { 3 | intervals.sort((a, b) => a[0] - b[0]); 4 | 5 | let prev_end = intervals[0][1]; 6 | let count = 0; 7 | 8 | for (let i = 1; i < intervals.length; i++) { 9 | if (intervals[i][0] < prev_end) { 10 | count++; 11 | prev_end = Math.min(prev_end, intervals[i][1]); 12 | } else { 13 | prev_end = intervals[i][1]; 14 | } 15 | } 16 | 17 | return count; 18 | } 19 | 20 | // Example usage: 21 | let intervals = [[1, 2], [2, 3], [3, 4], [1, 3]]; 22 | console.log(eraseOverlapIntervals(intervals)); 23 | -------------------------------------------------------------------------------- /0509-fibonacci-number/0509-fibonacci-number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Solution { 4 | public: 5 | int fib(int n) { 6 | // Base case: if n is 0 or 1, return n directly 7 | if (n <= 1) { 8 | return n; 9 | } 10 | 11 | // Initialize a vector (dp) to store computed Fibonacci numbers 12 | std::vector dp(n + 1, 0); 13 | 14 | dp[0] = 0; 15 | dp[1] = 1; 16 | 17 | // Start calculating Fibonacci numbers from 2 to n 18 | for (int i = 2; i <= n; i++) { 19 | dp[i] = dp[i - 1] + dp[i - 2]; 20 | } 21 | 22 | // Return the nth Fibonacci number 23 | return dp[n]; 24 | } 25 | }; -------------------------------------------------------------------------------- /0509-fibonacci-number/0509-fibonacci-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int fib(int n) { 3 | // Base case: if n is 0 or 1, return n directly 4 | if (n <= 1) { 5 | return n; 6 | } 7 | 8 | // Initialize an array (dp) to store computed Fibonacci numbers 9 | int[] dp = new int[n + 1]; 10 | 11 | dp[0] = 0; 12 | dp[1] = 1; 13 | 14 | // Start calculating Fibonacci numbers from 2 to n 15 | for (int i = 2; i <= n; i++) { 16 | dp[i] = dp[i - 1] + dp[i - 2]; 17 | } 18 | 19 | // Return the nth Fibonacci number 20 | return dp[n]; 21 | } 22 | } -------------------------------------------------------------------------------- /0509-fibonacci-number/0509-fibonacci-number.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | fib(n) { 3 | // Base case: if n is 0 or 1, return n directly 4 | if (n <= 1) { 5 | return n; 6 | } 7 | 8 | // Initialize an array (dp) to store computed Fibonacci numbers 9 | let dp = new Array(n + 1).fill(0); 10 | 11 | dp[0] = 0; 12 | dp[1] = 1; 13 | 14 | // Start calculating Fibonacci numbers from 2 to n 15 | for (let i = 2; i <= n; i++) { 16 | dp[i] = dp[i - 1] + dp[i - 2]; 17 | } 18 | 19 | // Return the nth Fibonacci number 20 | return dp[n]; 21 | } 22 | } -------------------------------------------------------------------------------- /0509-fibonacci-number/0509-fibonacci-number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fib(self, n: int) -> int: 3 | # Base case: if n is 0 or 1, return n directly 4 | if n <= 1: 5 | return n 6 | 7 | # Initialize a list (dp) to store computed Fibonacci numbers 8 | dp = [0] * (n+1) 9 | 10 | dp[0] = 0 11 | dp[1] = 1 12 | 13 | # Start calculating Fibonacci numbers from 2 to n 14 | for i in range(2, n+1): 15 | dp[i] = dp[i-1] + dp[i-2] 16 | 17 | # Return the nth Fibonacci number 18 | return dp[n] 19 | 20 | 21 | #Question: https://leetcode.com/problems/fibonacci-number 22 | #Blog: https://blog.unwiredlearning.com/fibonacci-number -------------------------------------------------------------------------------- /0572-subtree-of-another-tree/0572-subtree-of-another-tree.java: -------------------------------------------------------------------------------- 1 | 2 | class TreeNode { 3 | int val; 4 | TreeNode left; 5 | TreeNode right; 6 | TreeNode(int x) { val = x; } 7 | } 8 | 9 | class Solution { 10 | public boolean isSubtree(TreeNode root, TreeNode subRoot) { 11 | if (subRoot == null) { 12 | return true; 13 | } 14 | if (root == null) { 15 | return false; 16 | } 17 | if (isSameTree(root, subRoot)) { 18 | return true; 19 | } 20 | return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); 21 | } 22 | 23 | private boolean isSameTree(TreeNode p, TreeNode q) { 24 | if (p == null && q == null) { 25 | return true; 26 | } 27 | if (p == null || q == null || p.val != q.val) { 28 | return false; 29 | } 30 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /0572-subtree-of-another-tree/0572-subtree-of-another-tree.js: -------------------------------------------------------------------------------- 1 | 2 | class TreeNode { 3 | constructor(val) { 4 | this.val = val; 5 | this.left = null; 6 | this.right = null; 7 | } 8 | } 9 | 10 | class Solution { 11 | isSubtree(root, subRoot) { 12 | if (subRoot === null) { 13 | return true; 14 | } 15 | if (root === null) { 16 | return false; 17 | } 18 | if (this.isSameTree(root, subRoot)) { 19 | return true; 20 | } 21 | return this.isSubtree(root.left, subRoot) || this.isSubtree(root.right, subRoot); 22 | } 23 | 24 | isSameTree(p, q) { 25 | if (p === null && q === null) { 26 | return true; 27 | } 28 | if (p === null || q === null || p.val !== q.val) { 29 | return false; 30 | } 31 | return this.isSameTree(p.left, q.left) && this.isSameTree(p.right, q.right); 32 | } 33 | } 34 | 35 | // Example usage: 36 | // const root = new TreeNode(1); 37 | // const subRoot = new TreeNode(1); 38 | // const solution = new Solution(); 39 | // console.log(solution.isSubtree(root, subRoot)); 40 | -------------------------------------------------------------------------------- /0643-maximum-average-subarray-i/0643-maximum-average-subarray-i.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | double findMaxAverage(vector& nums, int k) { 8 | // Sum for starting window 9 | int currentSum = 0; 10 | for (int i = 0; i < k; i++) { 11 | currentSum += nums[i]; 12 | } 13 | 14 | int maxSum = currentSum; 15 | 16 | // Start sliding window 17 | int startIndex = 0; 18 | int endIndex = k; 19 | 20 | while (endIndex < nums.size()) { 21 | // Remove previous element 22 | currentSum -= nums[startIndex]; 23 | startIndex++; 24 | 25 | // Add next element 26 | currentSum += nums[endIndex]; 27 | endIndex++; 28 | 29 | // Update max sum 30 | maxSum = max(maxSum, currentSum); 31 | } 32 | 33 | // Return the average 34 | return static_cast(maxSum) / k; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /0643-maximum-average-subarray-i/0643-maximum-average-subarray-i.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public double findMaxAverage(int[] nums, int k) { 5 | // Sum for starting window 6 | int currentSum = 0; 7 | for (int i = 0; i < k; i++) { 8 | currentSum += nums[i]; 9 | } 10 | 11 | int maxSum = currentSum; 12 | 13 | // Start sliding window 14 | int startIndex = 0; 15 | int endIndex = k; 16 | 17 | while (endIndex < nums.length) { 18 | // Remove previous element 19 | currentSum -= nums[startIndex]; 20 | startIndex++; 21 | 22 | // Add next element 23 | currentSum += nums[endIndex]; 24 | endIndex++; 25 | 26 | // Update max sum 27 | maxSum = Math.max(maxSum, currentSum); 28 | } 29 | 30 | // Return the average 31 | return (double) maxSum / k; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /0643-maximum-average-subarray-i/0643-maximum-average-subarray-i.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {number[]} nums 3 | * @param {number} k 4 | * @return {number} 5 | */ 6 | var findMaxAverage = function(nums, k) { 7 | // Sum for starting window 8 | let currentSum = 0; 9 | for (let i = 0; i < k; i++) { 10 | currentSum += nums[i]; 11 | } 12 | 13 | let maxSum = currentSum; 14 | 15 | // Start sliding window 16 | let startIndex = 0; 17 | let endIndex = k; 18 | 19 | while (endIndex < nums.length) { 20 | // Remove previous element 21 | currentSum -= nums[startIndex]; 22 | startIndex++; 23 | 24 | // Add next element 25 | currentSum += nums[endIndex]; 26 | endIndex++; 27 | 28 | // Update max sum 29 | maxSum = Math.max(maxSum, currentSum); 30 | } 31 | 32 | // Return the average 33 | return maxSum / k; 34 | }; 35 | -------------------------------------------------------------------------------- /0643-maximum-average-subarray-i/0643-maximum-average-subarray-i.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMaxAverage(self, nums: List[int], k: int) -> float: 3 | # Sum for starting window 4 | current_sum = 0 5 | for i in range(k): 6 | current_sum += nums[i] 7 | 8 | max_sum = current_sum 9 | 10 | # Start sliding window 11 | start_index = 0 12 | end_index = k 13 | 14 | while end_index < len(nums): 15 | 16 | # Remove previous element 17 | current_sum -= nums[start_index] 18 | start_index += 1 19 | 20 | # Add next element 21 | current_sum += nums[end_index] 22 | end_index += 1 23 | 24 | # Update max sum 25 | max_sum = max(max_sum, current_sum) 26 | 27 | # Return the average 28 | return max_sum / k 29 | 30 | 31 | #Question: https://leetcode.com/problems/maximum-average-subarray-i 32 | #Blog: https://blog.unwiredlearning.com/maximum-average-subarray-i -------------------------------------------------------------------------------- /0704-binary-search/0704-binary-search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Solution { 4 | public: 5 | int search(std::vector& nums, int target) { 6 | int left = 0, right = nums.size() - 1; 7 | 8 | while (left <= right) { 9 | int mid = left + (right - left) / 2; 10 | 11 | if (nums[mid] == target) { 12 | return mid; 13 | } else if (nums[mid] > target) { 14 | right = mid - 1; 15 | } else { 16 | left = mid + 1; 17 | } 18 | } 19 | 20 | return -1; 21 | } 22 | }; -------------------------------------------------------------------------------- /0704-binary-search/0704-binary-search.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int search(int[] nums, int target) { 3 | int left = 0, right = nums.length - 1; 4 | 5 | while (left <= right) { 6 | int mid = left + (right - left) / 2; 7 | 8 | if (nums[mid] == target) { 9 | return mid; 10 | } else if (nums[mid] > target) { 11 | right = mid - 1; 12 | } else { 13 | left = mid + 1; 14 | } 15 | } 16 | 17 | return -1; 18 | } 19 | } -------------------------------------------------------------------------------- /0704-binary-search/0704-binary-search.js: -------------------------------------------------------------------------------- 1 | function search(nums, target) { 2 | let left = 0; 3 | let right = nums.length - 1; 4 | 5 | while (left <= right) { 6 | const mid = left + Math.floor((right - left) / 2); 7 | 8 | if (nums[mid] === target) { 9 | return mid; 10 | } else if (nums[mid] > target) { 11 | right = mid - 1; 12 | } else { 13 | left = mid + 1; 14 | } 15 | } 16 | 17 | return -1; 18 | } -------------------------------------------------------------------------------- /0739-daily-temperatures/0739-daily-temperatures.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Solution { 5 | public: 6 | std::vector dailyTemperatures(std::vector& temperatures) { 7 | int n = temperatures.size(); 8 | std::vector result(n, 0); 9 | std::stack stack; 10 | 11 | for (int i = n - 1; i >= 0; i--) { 12 | while (!stack.empty() && temperatures[i] >= temperatures[stack.top()]) { 13 | stack.pop(); 14 | } 15 | 16 | if (!stack.empty()) { 17 | result[i] = stack.top() - i; 18 | } 19 | 20 | stack.push(i); 21 | } 22 | 23 | return result; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /0739-daily-temperatures/0739-daily-temperatures.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | class Solution { 4 | public int[] dailyTemperatures(int[] temperatures) { 5 | int n = temperatures.length; 6 | int[] result = new int[n]; 7 | Stack stack = new Stack<>(); 8 | 9 | for (int i = n - 1; i >= 0; i--) { 10 | while (!stack.isEmpty() && temperatures[i] >= temperatures[stack.peek()]) { 11 | stack.pop(); 12 | } 13 | 14 | if (!stack.isEmpty()) { 15 | result[i] = stack.peek() - i; 16 | } 17 | 18 | stack.push(i); 19 | } 20 | 21 | return result; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /0739-daily-temperatures/0739-daily-temperatures.js: -------------------------------------------------------------------------------- 1 | function dailyTemperatures(temperatures) { 2 | const n = temperatures.length; 3 | const result = new Array(n).fill(0); 4 | const stack = []; 5 | 6 | for (let i = n - 1; i >= 0; i--) { 7 | while (stack.length > 0 && temperatures[i] >= temperatures[stack[stack.length - 1]]) { 8 | stack.pop(); 9 | } 10 | 11 | if (stack.length > 0) { 12 | result[i] = stack[stack.length - 1] - i; 13 | } 14 | 15 | stack.push(i); 16 | } 17 | 18 | return result; 19 | } 20 | -------------------------------------------------------------------------------- /0739-daily-temperatures/0739-daily-temperatures.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dailyTemperatures(self, temperatures: List[int]) -> List[int]: 3 | n = len(temperatures) 4 | result = [0] * n 5 | stack = [] 6 | 7 | for i in range(n - 1, -1, -1): 8 | # Popping all indices with a lower or equal temperature than the current index 9 | while stack and temperatures[i] >= temperatures[stack[-1]]: 10 | stack.pop() 11 | 12 | # If the stack still has elements, then the next warmer temperature exists! 13 | if stack: 14 | result[i] = stack[-1] - i 15 | 16 | # Inserting current index in the stack 17 | stack.append(i) 18 | 19 | return result 20 | 21 | 22 | #Question: https://leetcode.com/problems/daily-temperatures 23 | #Blog: https://blog.unwiredlearning.com/daily-temperatures -------------------------------------------------------------------------------- /0876-middle-of-the-linked-list/0876-middle-of-the-linked-list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct ListNode { 4 | int val; 5 | ListNode* next; 6 | ListNode(int x) : val(x), next(nullptr) {} 7 | }; 8 | 9 | class Solution { 10 | public: 11 | ListNode* middleNode(ListNode* head) { 12 | ListNode* slow = head; 13 | ListNode* fast = head; 14 | 15 | while (fast != nullptr && fast->next != nullptr) { 16 | slow = slow->next; 17 | fast = fast->next->next; 18 | } 19 | 20 | return slow; 21 | } 22 | }; -------------------------------------------------------------------------------- /0876-middle-of-the-linked-list/0876-middle-of-the-linked-list.java: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | int val; 3 | ListNode next; 4 | ListNode(int val) { 5 | this.val = val; 6 | this.next = null; 7 | } 8 | } 9 | 10 | public class Solution { 11 | public ListNode middleNode(ListNode head) { 12 | ListNode slow = head; 13 | ListNode fast = head; 14 | 15 | while (fast != null && fast.next != null) { 16 | slow = slow.next; 17 | fast = fast.next.next; 18 | } 19 | 20 | return slow; 21 | } 22 | } -------------------------------------------------------------------------------- /0876-middle-of-the-linked-list/0876-middle-of-the-linked-list.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor(val = 0, next = null) { 3 | this.val = val; 4 | this.next = next; 5 | } 6 | } 7 | 8 | function middleNode(head) { 9 | let slow = head; 10 | let fast = head; 11 | 12 | while (fast !== null && fast.next !== null) { 13 | slow = slow.next; 14 | fast = fast.next.next; 15 | } 16 | 17 | return slow; 18 | } -------------------------------------------------------------------------------- /0876-middle-of-the-linked-list/0876-middle-of-the-linked-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | 7 | class Solution: 8 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: 9 | # Initialize two pointers, slow and fast, both pointing to the head of the list. 10 | slow, fast = head, head 11 | 12 | # Traverse the list. The loop continues as long as fast and its next node are not None. 13 | while fast != None and fast.next != None: 14 | # Move the slow pointer one step. 15 | slow = slow.next 16 | 17 | # Move the fast pointer two steps. 18 | fast = fast.next.next 19 | 20 | # By the time the loop ends, the slow pointer will be at the middle of the list. 21 | return slow 22 | 23 | 24 | #Question: https://leetcode.com/problems/middle-of-the-linked-list 25 | #Blog: https://blog.unwiredlearning.com/middle-of-the-linked-list -------------------------------------------------------------------------------- /0881-boats-to-save-people/0881-boats-to-save-people.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Solution { 5 | public: 6 | int numRescueBoats(std::vector& people, int limit) { 7 | std::sort(people.begin(), people.end()); 8 | int i = 0, j = people.size() - 1; 9 | int boats = 0; 10 | 11 | while (i <= j) { 12 | boats++; 13 | if (people[i] + people[j] <= limit) { 14 | i++; 15 | } 16 | j--; 17 | } 18 | 19 | return boats; 20 | } 21 | }; -------------------------------------------------------------------------------- /0881-boats-to-save-people/0881-boats-to-save-people.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int numRescueBoats(int[] people, int limit) { 5 | Arrays.sort(people); 6 | int i = 0, j = people.length - 1; 7 | int boats = 0; 8 | 9 | while (i <= j) { 10 | boats++; 11 | if (people[i] + people[j] <= limit) { 12 | i++; 13 | } 14 | j--; 15 | } 16 | 17 | return boats; 18 | } 19 | } -------------------------------------------------------------------------------- /0881-boats-to-save-people/0881-boats-to-save-people.js: -------------------------------------------------------------------------------- 1 | function numRescueBoats(people, limit) { 2 | people.sort((a, b) => a - b); 3 | let i = 0; 4 | let j = people.length - 1; 5 | let boats = 0; 6 | 7 | while (i <= j) { 8 | boats++; 9 | if (people[i] + people[j] <= limit) { 10 | i++; 11 | } 12 | j--; 13 | } 14 | 15 | return boats; 16 | } -------------------------------------------------------------------------------- /0881-boats-to-save-people/0881-boats-to-save-people.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numRescueBoats(self, people: List[int], limit: int) -> int: 3 | people.sort() 4 | i, j = 0, len(people) - 1 5 | boats = 0 6 | 7 | # Loop until the two pointers meet or cross each other 8 | while i <= j: 9 | boats += 1 10 | 11 | # Check if the lightest and heaviest person can share a boat 12 | if people[i] + people[j] <= limit: 13 | i += 1 14 | 15 | j -= 1 16 | 17 | # Return the total number of boats used 18 | return boats 19 | 20 | 21 | #Question: https://leetcode.com/problems/boats-to-save-people 22 | #Blog: https://blog.unwiredlearning.com/boats-to-save-people -------------------------------------------------------------------------------- /1143-longest-common-subsequence/1143-longest-common-subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class Solution { 6 | public: 7 | int longestCommonSubsequence(std::string text1, std::string text2) { 8 | int m = text1.size(); 9 | int n = text2.size(); 10 | std::vector> dp(m + 1, std::vector(n + 1, 0)); 11 | 12 | for (int j = 1; j <= n; ++j) { 13 | for (int i = 1; i <= m; ++i) { 14 | if (text1[i - 1] == text2[j - 1]) { 15 | dp[i][j] = dp[i - 1][j - 1] + 1; 16 | } else { 17 | dp[i][j] = std::max(dp[i][j - 1], dp[i - 1][j]); 18 | } 19 | } 20 | } 21 | 22 | // The bottom-right corner is the length of the LCS 23 | return dp[m][n]; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /1143-longest-common-subsequence/1143-longest-common-subsequence.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int longestCommonSubsequence(String text1, String text2) { 3 | int m = text1.length(); 4 | int n = text2.length(); 5 | int[][] dp = new int[m + 1][n + 1]; 6 | 7 | for (int j = 1; j <= n; j++) { 8 | for (int i = 1; i <= m; i++) { 9 | if (text1.charAt(i - 1) == text2.charAt(j - 1)) { 10 | dp[i][j] = dp[i - 1][j - 1] + 1; 11 | } else { 12 | dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); 13 | } 14 | } 15 | } 16 | 17 | // The bottom-right corner is the length of the LCS 18 | return dp[m][n]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /1143-longest-common-subsequence/1143-longest-common-subsequence.js: -------------------------------------------------------------------------------- 1 | class Solution { 2 | longestCommonSubsequence(text1, text2) { 3 | const m = text1.length; 4 | const n = text2.length; 5 | const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); 6 | 7 | for (let j = 1; j <= n; j++) { 8 | for (let i = 1; i <= m; i++) { 9 | if (text1[i - 1] === text2[j - 1]) { 10 | dp[i][j] = dp[i - 1][j - 1] + 1; 11 | } else { 12 | dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); 13 | } 14 | } 15 | } 16 | 17 | // The bottom-right corner is the length of the LCS 18 | return dp[m][n]; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /1143-longest-common-subsequence/1143-longest-common-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 3 | m, n = len(text1), len(text2) 4 | dp = [[0] * (n + 1) for _ in range(m + 1)] 5 | 6 | for j in range(1, n + 1): 7 | for i in range(1, m + 1): 8 | 9 | if text1[i - 1] == text2[j - 1]: 10 | dp[i][j] = dp[i - 1][j - 1] + 1 11 | else: 12 | dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]) 13 | 14 | # The bottom-right corner is the length of the LCS 15 | return dp[m][n] 16 | 17 | 18 | #Question: https://leetcode.com/problems/longest-common-subsequence 19 | #Blog: https://blog.unwiredlearning.com/longest-common-subsequence --------------------------------------------------------------------------------