diff --git a/3Sum - Leetcode 15.py b/3Sum - Leetcode 15.py deleted file mode 100644 index cd6b49f..0000000 --- a/3Sum - Leetcode 15.py +++ /dev/null @@ -1,19 +0,0 @@ -class Solution: - def threeSum(self, nums: List[int]) -> List[List[int]]: - h = {} - n = len(nums) - s = set() - - for i, num in enumerate(nums): - h[num] = i - - for i in range(n): - for j in range(i + 1, n): - desired = -nums[i] - nums[j] - if desired in h and h[desired] != i and h[desired] != j: - s.add(tuple(sorted([nums[i], nums[j], desired]))) - - return s - -# Time Complexity: O(n^2) -# Space Complexity: O(n) diff --git a/3Sum - Leetcode 15/3Sum - Leetcode 15.cpp b/3Sum - Leetcode 15/3Sum - Leetcode 15.cpp new file mode 100644 index 0000000..5d35e29 --- /dev/null +++ b/3Sum - Leetcode 15/3Sum - Leetcode 15.cpp @@ -0,0 +1,80 @@ + +// Hashmap Solution: +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector> threeSum(vector& nums) { + unordered_map indexMap; + set> result; + int n = nums.size(); + + // Build the index map + for (int i = 0; i < n; ++i) { + indexMap[nums[i]] = i; + } + + // Iterate over each pair + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + int desired = -nums[i] - nums[j]; + if (indexMap.find(desired) != indexMap.end() && + indexMap[desired] != i && indexMap[desired] != j) { + vector triplet = {nums[i], nums[j], desired}; + sort(triplet.begin(), triplet.end()); + result.insert(triplet); + } + } + } + + return vector>(result.begin(), result.end()); + } +}; + + +// Two Pointer Solution: +#include +#include + +using namespace std; + +class Solution { +public: + vector> threeSum(vector& nums) { + sort(nums.begin(), nums.end()); + int n = nums.size(); + vector> answer; + + for (int i = 0; i < n; i++) { + if (nums[i] > 0) { + break; + } + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + int lo = i + 1, hi = n - 1; + while (lo < hi) { + int sum = nums[i] + nums[lo] + nums[hi]; + if (sum == 0) { + answer.push_back({nums[i], nums[lo], nums[hi]}); + lo++; + hi--; + while (lo < hi && nums[lo] == nums[lo - 1]) lo++; + while (lo < hi && nums[hi] == nums[hi + 1]) hi--; + } else if (sum < 0) { + lo++; + } else { + hi--; + } + } + } + + return answer; + } +}; + diff --git a/3Sum - Leetcode 15/3Sum - Leetcode 15.java b/3Sum - Leetcode 15/3Sum - Leetcode 15.java new file mode 100644 index 0000000..f59485b --- /dev/null +++ b/3Sum - Leetcode 15/3Sum - Leetcode 15.java @@ -0,0 +1,69 @@ +// Hashmap Solution: +import java.util.*; + +public class Solution { + public List> threeSum(int[] nums) { + Set> result = new HashSet<>(); + Map indexMap = new HashMap<>(); + int n = nums.length; + + // Build the index map + for (int i = 0; i < n; i++) { + indexMap.put(nums[i], i); + } + + // Iterate over each pair + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + int desired = -nums[i] - nums[j]; + if (indexMap.containsKey(desired) && indexMap.get(desired) != i && indexMap.get(desired) != j) { + List triplet = Arrays.asList(nums[i], nums[j], desired); + Collections.sort(triplet); + result.add(triplet); + } + } + } + + return new ArrayList<>(result); + } +} + + +// Two Pointer Solution: +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Solution { + public List> threeSum(int[] nums) { + Arrays.sort(nums); + int n = nums.length; + List> answer = new ArrayList<>(); + + for (int i = 0; i < n; i++) { + if (nums[i] > 0) { + break; + } + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + int lo = i + 1, hi = n - 1; + while (lo < hi) { + int sum = nums[i] + nums[lo] + nums[hi]; + if (sum == 0) { + answer.add(Arrays.asList(nums[i], nums[lo], nums[hi])); + lo++; + hi--; + while (lo < hi && nums[lo] == nums[lo - 1]) lo++; + while (lo < hi && nums[hi] == nums[hi + 1]) hi--; + } else if (sum < 0) { + lo++; + } else { + hi--; + } + } + } + + return answer; + } +} diff --git a/3Sum - Leetcode 15/3Sum - Leetcode 15.js b/3Sum - Leetcode 15/3Sum - Leetcode 15.js new file mode 100644 index 0000000..a74a8e7 --- /dev/null +++ b/3Sum - Leetcode 15/3Sum - Leetcode 15.js @@ -0,0 +1,63 @@ +// Hashmap Solution: + +/** + * @param {number[]} nums + * @return {number[][]} + */ +var threeSum = function(nums) { + const indexMap = new Map(); + const result = new Set(); + const n = nums.length; + + // Build the index map + for (let i = 0; i < n; i++) { + indexMap.set(nums[i], i); + } + + // Iterate over each pair + for (let i = 0; i < n; i++) { + for (let j = i + 1; j < n; j++) { + const desired = -nums[i] - nums[j]; + if (indexMap.has(desired) && indexMap.get(desired) !== i && indexMap.get(desired) !== j) { + const triplet = [nums[i], nums[j], desired].sort((a, b) => a - b); + result.add(triplet.toString()); + } + } + } + + return Array.from(result, str => str.split(',').map(Number)); +}; + + +// Two Pointer Solution: +var threeSum = function(nums) { + nums.sort((a, b) => a - b); + let n = nums.length; + let answer = []; + + for (let i = 0; i < n; i++) { + if (nums[i] > 0) { + break; + } + if (i > 0 && nums[i] === nums[i - 1]) { + continue; + } + let lo = i + 1, hi = n - 1; + while (lo < hi) { + let sum = nums[i] + nums[lo] + nums[hi]; + if (sum === 0) { + answer.push([nums[i], nums[lo], nums[hi]]); + lo++; + hi--; + while (lo < hi && nums[lo] === nums[lo - 1]) lo++; + while (lo < hi && nums[hi] === nums[hi + 1]) hi--; + } else if (sum < 0) { + lo++; + } else { + hi--; + } + } + } + + return answer; +}; diff --git a/3Sum - Leetcode 15/3Sum - Leetcode 15.py b/3Sum - Leetcode 15/3Sum - Leetcode 15.py new file mode 100644 index 0000000..f03821d --- /dev/null +++ b/3Sum - Leetcode 15/3Sum - Leetcode 15.py @@ -0,0 +1,51 @@ +# Hashmap Solution: +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + h = {} + n = len(nums) + s = set() + + for i, num in enumerate(nums): + h[num] = i + + for i in range(n): + for j in range(i + 1, n): + desired = -nums[i] - nums[j] + if desired in h and h[desired] != i and h[desired] != j: + s.add(tuple(sorted([nums[i], nums[j], desired]))) + + return s + +# Time Complexity: O(n^2) +# Space Complexity: O(n) + + +## Two Pointer Solution: +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + nums.sort() + n = len(nums) + answer = [] + for i in range(n): + if nums[i] > 0: + break + elif i > 0 and nums[i] == nums[i-1]: + continue + lo, hi = i+1, n-1 + while lo < hi: + summ = nums[i] + nums[lo] + nums[hi] + if summ == 0: + answer.append([nums[i], nums[lo], nums[hi]]) + lo, hi = lo+1, hi-1 + while lo < hi and nums[lo] == nums[lo-1]: + lo += 1 + while lo < hi and nums[hi] == nums[hi+1]: + hi -= 1 + elif summ < 0: + lo += 1 + else: + hi -= 1 + + return answer + # Time: O(n^2) + # Space: O(n) (Excluding the output) diff --git a/3Sum Closest - Leetcode 16/3Sum Closest - Leetcode 16.cpp b/3Sum Closest - Leetcode 16/3Sum Closest - Leetcode 16.cpp new file mode 100644 index 0000000..d779e1b --- /dev/null +++ b/3Sum Closest - Leetcode 16/3Sum Closest - Leetcode 16.cpp @@ -0,0 +1,34 @@ +#include +#include +#include + +class Solution { +public: + int threeSumClosest(std::vector& nums, int target) { + int n = nums.size(); + std::sort(nums.begin(), nums.end()); + int closestSum = INT_MAX; + + for (int i = 0; i < n; i++) { + if (i > 0 && nums[i] == nums[i - 1]) continue; + + int lo = i + 1, hi = n - 1; + while (lo < hi) { + int curSum = nums[i] + nums[lo] + nums[hi]; + + if (std::abs(curSum - target) < std::abs(closestSum - target)) { + closestSum = curSum; + } + + if (curSum == target) { + return curSum; + } else if (curSum < target) { + lo++; + } else { + hi--; + } + } + } + return closestSum; + } +}; diff --git a/3Sum Closest - Leetcode 16/3Sum Closest - Leetcode 16.java b/3Sum Closest - Leetcode 16/3Sum Closest - Leetcode 16.java new file mode 100644 index 0000000..962bf33 --- /dev/null +++ b/3Sum Closest - Leetcode 16/3Sum Closest - Leetcode 16.java @@ -0,0 +1,31 @@ +import java.util.Arrays; + +public class Solution { + public int threeSumClosest(int[] nums, int target) { + int n = nums.length; + Arrays.sort(nums); + int closestSum = Integer.MAX_VALUE; + + for (int i = 0; i < n; i++) { + if (i > 0 && nums[i] == nums[i - 1]) continue; + + int lo = i + 1, hi = n - 1; + while (lo < hi) { + int curSum = nums[i] + nums[lo] + nums[hi]; + + if (Math.abs(curSum - target) < Math.abs(closestSum - target)) { + closestSum = curSum; + } + + if (curSum == target) { + return curSum; + } else if (curSum < target) { + lo++; + } else { + hi--; + } + } + } + return closestSum; + } +} diff --git a/3Sum Closest - Leetcode 16/3Sum Closest - Leetcode 16.js b/3Sum Closest - Leetcode 16/3Sum Closest - Leetcode 16.js new file mode 100644 index 0000000..8308f8e --- /dev/null +++ b/3Sum Closest - Leetcode 16/3Sum Closest - Leetcode 16.js @@ -0,0 +1,27 @@ +var threeSumClosest = function(nums, target) { + nums.sort((a, b) => a - b); + let n = nums.length; + let closestSum = Infinity; + + for (let i = 0; i < n; i++) { + if (i > 0 && nums[i] === nums[i - 1]) continue; + + let lo = i + 1, hi = n - 1; + while (lo < hi) { + let curSum = nums[i] + nums[lo] + nums[hi]; + + if (Math.abs(curSum - target) < Math.abs(closestSum - target)) { + closestSum = curSum; + } + + if (curSum === target) { + return curSum; + } else if (curSum < target) { + lo++; + } else { + hi--; + } + } + } + return closestSum; +}; diff --git a/3Sum Closest - Leetcode 16/3Sum Closest - Leetcode 16.py b/3Sum Closest - Leetcode 16/3Sum Closest - Leetcode 16.py new file mode 100644 index 0000000..02bd6ee --- /dev/null +++ b/3Sum Closest - Leetcode 16/3Sum Closest - Leetcode 16.py @@ -0,0 +1,27 @@ +class Solution: + def threeSumClosest(self, nums: List[int], target: int) -> int: + n = len(nums) + nums.sort() + closest_sum = float('inf') + + for i in range(n): + if i > 0 and nums[i] == nums[i-1]: + continue + + lo, hi = i + 1, n - 1 + while lo < hi: + cur_sum = nums[i] + nums[lo] + nums[hi] + + if abs(cur_sum - target) < abs(closest_sum - target): + closest_sum = cur_sum + + if cur_sum == target: + return cur_sum + elif cur_sum < target: + lo += 1 + else: + hi -= 1 + + return closest_sum + # Time: O(n^2) + # Space: O(n) diff --git a/4Sum - Leetcode 18/4Sum - Leetcode 15.cpp b/4Sum - Leetcode 18/4Sum - Leetcode 15.cpp new file mode 100644 index 0000000..762bb0a --- /dev/null +++ b/4Sum - Leetcode 18/4Sum - Leetcode 15.cpp @@ -0,0 +1,38 @@ +#include +#include + +using namespace std; + +class Solution { +public: + vector> fourSum(vector& nums, int target) { + vector> answer; + sort(nums.begin(), nums.end()); + int n = nums.size(); + + for (int i = 0; i < n; i++) { + if (i > 0 && nums[i] == nums[i - 1]) continue; + + for (int j = i + 1; j < n; j++) { + if (j > i + 1 && nums[j] == nums[j - 1]) continue; + + int lo = j + 1, hi = n - 1; + while (lo < hi) { + long long sum = (long long)nums[i] + nums[j] + nums[lo] + nums[hi]; + if (sum == target) { + answer.push_back({nums[i], nums[j], nums[lo], nums[hi]}); + lo++; + hi--; + while (lo < hi && nums[lo] == nums[lo - 1]) lo++; + while (lo < hi && nums[hi] == nums[hi + 1]) hi--; + } else if (sum < target) { + lo++; + } else { + hi--; + } + } + } + } + return answer; + } +}; diff --git a/4Sum - Leetcode 18/4Sum - Leetcode 15.java b/4Sum - Leetcode 18/4Sum - Leetcode 15.java new file mode 100644 index 0000000..0dc2f21 --- /dev/null +++ b/4Sum - Leetcode 18/4Sum - Leetcode 15.java @@ -0,0 +1,36 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Solution { + public List> fourSum(int[] nums, int target) { + List> answer = new ArrayList<>(); + Arrays.sort(nums); + int n = nums.length; + + for (int i = 0; i < n; i++) { + if (i > 0 && nums[i] == nums[i - 1]) continue; + + for (int j = i + 1; j < n; j++) { + if (j > i + 1 && nums[j] == nums[j - 1]) continue; + + int lo = j + 1, hi = n - 1; + while (lo < hi) { + long sum = (long) nums[i] + nums[j] + nums[lo] + nums[hi]; + if (sum == target) { + answer.add(Arrays.asList(nums[i], nums[j], nums[lo], nums[hi])); + lo++; + hi--; + while (lo < hi && nums[lo] == nums[lo - 1]) lo++; + while (lo < hi && nums[hi] == nums[hi + 1]) hi--; + } else if (sum < target) { + lo++; + } else { + hi--; + } + } + } + } + return answer; + } +} diff --git a/4Sum - Leetcode 18/4Sum - Leetcode 15.js b/4Sum - Leetcode 18/4Sum - Leetcode 15.js new file mode 100644 index 0000000..c1417e4 --- /dev/null +++ b/4Sum - Leetcode 18/4Sum - Leetcode 15.js @@ -0,0 +1,30 @@ +var fourSum = function(nums, target) { + let answer = []; + nums.sort((a, b) => a - b); + let n = nums.length; + + for (let i = 0; i < n; i++) { + if (i > 0 && nums[i] === nums[i - 1]) continue; + + for (let j = i + 1; j < n; j++) { + if (j > i + 1 && nums[j] === nums[j - 1]) continue; + + let lo = j + 1, hi = n - 1; + while (lo < hi) { + let sum = nums[i] + nums[j] + nums[lo] + nums[hi]; + if (sum === target) { + answer.push([nums[i], nums[j], nums[lo], nums[hi]]); + lo++; + hi--; + while (lo < hi && nums[lo] === nums[lo - 1]) lo++; + while (lo < hi && nums[hi] === nums[hi + 1]) hi--; + } else if (sum < target) { + lo++; + } else { + hi--; + } + } + } + } + return answer; +}; diff --git a/4Sum - Leetcode 18/4Sum - Leetcode 15.py b/4Sum - Leetcode 18/4Sum - Leetcode 15.py new file mode 100644 index 0000000..d17aaaa --- /dev/null +++ b/4Sum - Leetcode 18/4Sum - Leetcode 15.py @@ -0,0 +1,33 @@ +class Solution: + def fourSum(self, nums: List[int], target: int) -> List[List[int]]: + n = len(nums) + answer = [] + nums.sort() + + for i in range(n): + if i > 0 and nums[i] == nums[i-1]: + continue + + for j in range(i+1, n): + if j > i + 1 and nums[j] == nums[j-1]: + continue + + lo, hi = j + 1, n - 1 + while lo < hi: + summ = nums[i] + nums[j] + nums[lo] + nums[hi] + if summ == target: + answer.append([nums[i], nums[j], nums[lo], nums[hi]]) + lo += 1 + hi -= 1 + while lo < hi and nums[lo] == nums[lo - 1]: + lo += 1 + while lo < hi and nums[hi] == nums[hi + 1]: + hi -= 1 + elif summ < target: + lo += 1 + else: + hi -= 1 + + return answer + # Time: O(n^3) + # Space: O(n) \ No newline at end of file diff --git a/Add Binary - Leetcode 67/Add Binary - Leetcode 67.cpp b/Add Binary - Leetcode 67/Add Binary - Leetcode 67.cpp new file mode 100644 index 0000000..cb8f793 --- /dev/null +++ b/Add Binary - Leetcode 67/Add Binary - Leetcode 67.cpp @@ -0,0 +1,92 @@ +class BigInt { +private: + string binary; + + // Helper function to ensure strings are the same length + static void equalizeLength(string& a, string& b) { + int lengthDifference = a.size() - b.size(); + if (lengthDifference > 0) + b.insert(0, lengthDifference, '0'); + else + a.insert(0, -lengthDifference, '0'); + } + + // Helper function to remove leading zeros + void removeLeadingZeros() { + // Erase leading zeros while keeping at least one zero if the number is + // zero + auto firstNonZero = binary.find_first_not_of('0'); + if (firstNonZero != string::npos) { + binary.erase(0, firstNonZero); + } else { + binary = + "0"; // Adjust to maintain a minimum representation of zero + } + } + +public: + BigInt() : binary("0") {} + + // Constructor from a binary string + BigInt(const string& bin) : binary(bin) { removeLeadingZeros(); } + + // Bitwise XOR + BigInt operator^(const BigInt& other) const { + string a = binary; + string b = other.binary; + equalizeLength(a, b); + string result; + for (size_t i = 0; i < a.size(); i++) { + char xorChar = (a[i] == b[i] ? '0' : '1'); + result.push_back(xorChar); + } + return BigInt(result); + } + + // Bitwise AND + BigInt operator&(const BigInt& other) const { + string a = binary; + string b = other.binary; + equalizeLength(a, b); + string result; + for (size_t i = 0; i < a.size(); i++) { + char andChar = (a[i] == '1' && b[i] == '1' ? '1' : '0'); + result.push_back(andChar); + } + return BigInt(result); + } + + // Left shift + BigInt operator<<(int shift) const { + string result = binary; + result.append(shift, '0'); + return BigInt(result); + } + + // Check if BigInt is zero + bool isZero() const { + for (char c : binary) + if (c != '0') return false; + return true; + } + + // Getter for binary string + string getBinary() const { return binary; } +}; + +class Solution { +public: + string addBinary(string a, string b) { + BigInt x(a); + BigInt y(b); + BigInt carry, answer; + + while (!y.isZero()) { + answer = x ^ y; + carry = (x & y) << 1; + x = answer; + y = carry; + } + return x.getBinary(); + } +}; \ No newline at end of file diff --git a/Add Binary - Leetcode 67/Add Binary - Leetcode 67.java b/Add Binary - Leetcode 67/Add Binary - Leetcode 67.java new file mode 100644 index 0000000..4f44835 --- /dev/null +++ b/Add Binary - Leetcode 67/Add Binary - Leetcode 67.java @@ -0,0 +1,20 @@ +import java.math.BigInteger; + +public class Solution { + public String addBinary(String a, String b) { + // Convert the binary strings to BigInteger + BigInteger x = new BigInteger(a, 2); + BigInteger y = new BigInteger(b, 2); + + // Perform the binary addition using bitwise operations + while (y.compareTo(BigInteger.ZERO) != 0) { + BigInteger withoutCarry = x.xor(y); + BigInteger carry = x.and(y).shiftLeft(1); + x = withoutCarry; + y = carry; + } + + // Convert the result back to binary and return it as a string + return x.toString(2); + } +} diff --git a/Add Binary - Leetcode 67/Add Binary - Leetcode 67.js b/Add Binary - Leetcode 67/Add Binary - Leetcode 67.js new file mode 100644 index 0000000..1061499 --- /dev/null +++ b/Add Binary - Leetcode 67/Add Binary - Leetcode 67.js @@ -0,0 +1,16 @@ +var addBinary = function(a, b) { + // Convert the binary strings to BigInt + let x = BigInt("0b" + a); + let y = BigInt("0b" + b); + + // Perform the binary addition using bitwise operations + while (y !== 0n) { + let withoutCarry = x ^ y; + let carry = (x & y) << 1n; + x = withoutCarry; + y = carry; + } + + // Convert the result back to binary and return it as a string + return x.toString(2); +}; diff --git a/Add Binary - Leetcode 67/Add Binary - Leetcode 67.py b/Add Binary - Leetcode 67/Add Binary - Leetcode 67.py new file mode 100644 index 0000000..ed81271 --- /dev/null +++ b/Add Binary - Leetcode 67/Add Binary - Leetcode 67.py @@ -0,0 +1,12 @@ +class Solution: + def addBinary(self, a, b) -> str: + a, b = int(a, 2), int(b, 2) + + while b: + without_carry = a ^ b + carry = (a & b) << 1 + a, b = without_carry, carry + + return bin(a)[2:] + # Time: O(A + B) + # Space: O(1) \ No newline at end of file diff --git a/Average of Levels in Binary Tree - Leetcode 637/Average of Levels in Binary Tree - Leetcode 637.cpp b/Average of Levels in Binary Tree - Leetcode 637/Average of Levels in Binary Tree - Leetcode 637.cpp new file mode 100644 index 0000000..f263914 --- /dev/null +++ b/Average of Levels in Binary Tree - Leetcode 637/Average of Levels in Binary Tree - Leetcode 637.cpp @@ -0,0 +1,33 @@ +#include +#include + +class Solution { +public: + vector averageOfLevels(TreeNode* root) { + vector avgs; + if (!root) return avgs; + + queue q; + q.push(root); + + while (!q.empty()) { + double sum = 0; + int size = q.size(); + for (int i = 0; i < size; ++i) { + TreeNode* node = q.front(); + q.pop(); + sum += node->val; + + if (node->left) { + q.push(node->left); + } + if (node->right) { + q.push(node->right); + } + } + avgs.push_back(sum / size); + } + + return avgs; + } +}; diff --git a/Average of Levels in Binary Tree - Leetcode 637/Average of Levels in Binary Tree - Leetcode 637.java b/Average of Levels in Binary Tree - Leetcode 637/Average of Levels in Binary Tree - Leetcode 637.java new file mode 100644 index 0000000..25f4eeb --- /dev/null +++ b/Average of Levels in Binary Tree - Leetcode 637/Average of Levels in Binary Tree - Leetcode 637.java @@ -0,0 +1,43 @@ +import java.util.*; + +public class Solution { + public List averageOfLevels(TreeNode root) { + List avgs = new ArrayList<>(); + if (root == null) return avgs; + + Queue q = new LinkedList<>(); + q.add(root); + + while (!q.isEmpty()) { + double sum = 0; + int size = q.size(); + for (int i = 0; i < size; i++) { + TreeNode node = q.poll(); + sum += node.val; + + if (node.left != null) { + q.add(node.left); + } + if (node.right != null) { + q.add(node.right); + } + } + avgs.add(sum / size); + } + + return avgs; + } +} + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode() {} + TreeNode(int val) { this.val = val; } + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } +} diff --git a/Average of Levels in Binary Tree - Leetcode 637/Average of Levels in Binary Tree - Leetcode 637.js b/Average of Levels in Binary Tree - Leetcode 637/Average of Levels in Binary Tree - Leetcode 637.js new file mode 100644 index 0000000..562f9b5 --- /dev/null +++ b/Average of Levels in Binary Tree - Leetcode 637/Average of Levels in Binary Tree - Leetcode 637.js @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = val; + * this.left = left === undefined ? null : left; + * this.right = right === undefined ? null : right; + * } + */ + +var averageOfLevels = function(root) { + let avgs = []; + if (root === null) return avgs; + + let q = [root]; + + while (q.length > 0) { + let sum = 0; + let size = q.length; + for (let i = 0; i < size; i++) { + let node = q.shift(); + sum += node.val; + + if (node.left !== null) { + q.push(node.left); + } + if (node.right !== null) { + q.push(node.right); + } + } + avgs.push(sum / size); + } + + return avgs; +}; diff --git a/Average of Levels in Binary Tree - Leetcode 637/Average of Levels in Binary Tree - Leetcode 637.py b/Average of Levels in Binary Tree - Leetcode 637/Average of Levels in Binary Tree - Leetcode 637.py new file mode 100644 index 0000000..a8cceec --- /dev/null +++ b/Average of Levels in Binary Tree - Leetcode 637/Average of Levels in Binary Tree - Leetcode 637.py @@ -0,0 +1,30 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +from collections import deque +class Solution: + def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: + avgs = [] + q = deque() + q.append(root) + + while q: + summ = 0 + n = len(q) + for _ in range(n): + node = q.popleft() + summ += node.val + + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + + avgs.append(summ / n) + + return avgs + # Time: O(n) + # Space: O(n) diff --git a/Balanced Binary Tree - Leetcode 110/Balanced Binary Tree - Leetcode 110.cpp b/Balanced Binary Tree - Leetcode 110/Balanced Binary Tree - Leetcode 110.cpp new file mode 100644 index 0000000..3563e6f --- /dev/null +++ b/Balanced Binary Tree - Leetcode 110/Balanced Binary Tree - Leetcode 110.cpp @@ -0,0 +1,24 @@ + +class Solution { +public: + bool isBalanced(TreeNode* root) { + return height(root) != -1; + } + +private: + int height(TreeNode* node) { + if (!node) return 0; + + int leftHeight = height(node->left); + if (leftHeight == -1) return -1; + + int rightHeight = height(node->right); + if (rightHeight == -1) return -1; + + if (abs(leftHeight - rightHeight) > 1) { + return -1; + } + + return 1 + max(leftHeight, rightHeight); + } +}; diff --git a/Balanced Binary Tree - Leetcode 110/Balanced Binary Tree - Leetcode 110.java b/Balanced Binary Tree - Leetcode 110/Balanced Binary Tree - Leetcode 110.java new file mode 100644 index 0000000..0efb55c --- /dev/null +++ b/Balanced Binary Tree - Leetcode 110/Balanced Binary Tree - Leetcode 110.java @@ -0,0 +1,34 @@ +public class Solution { + public boolean isBalanced(TreeNode root) { + return height(root) != -1; + } + + private int height(TreeNode node) { + if (node == null) return 0; + + int leftHeight = height(node.left); + if (leftHeight == -1) return -1; + + int rightHeight = height(node.right); + if (rightHeight == -1) return -1; + + if (Math.abs(leftHeight - rightHeight) > 1) { + return -1; + } + + return 1 + Math.max(leftHeight, rightHeight); + } +} + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode() {} + TreeNode(int val) { this.val = val; } + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } +} diff --git a/Balanced Binary Tree - Leetcode 110/Balanced Binary Tree - Leetcode 110.js b/Balanced Binary Tree - Leetcode 110/Balanced Binary Tree - Leetcode 110.js new file mode 100644 index 0000000..b8a6576 --- /dev/null +++ b/Balanced Binary Tree - Leetcode 110/Balanced Binary Tree - Leetcode 110.js @@ -0,0 +1,28 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = val; + * this.left = left === undefined ? null : left; + * this.right = right === undefined ? null : right; + * } + */ + +var isBalanced = function(root) { + return height(root) !== -1; +}; + +function height(node) { + if (node === null) return 0; + + const leftHeight = height(node.left); + if (leftHeight === -1) return -1; + + const rightHeight = height(node.right); + if (rightHeight === -1) return -1; + + if (Math.abs(leftHeight - rightHeight) > 1) { + return -1; + } + + return 1 + Math.max(leftHeight, rightHeight); +} diff --git a/Balanced Binary Tree - Leetcode 110.py b/Balanced Binary Tree - Leetcode 110/Balanced Binary Tree - Leetcode 110.py similarity index 100% rename from Balanced Binary Tree - Leetcode 110.py rename to Balanced Binary Tree - Leetcode 110/Balanced Binary Tree - Leetcode 110.py diff --git a/Base 7 - Leetcode 504/Base 7 - Leetcode 504.cpp b/Base 7 - Leetcode 504/Base 7 - Leetcode 504.cpp new file mode 100644 index 0000000..8c44f4b --- /dev/null +++ b/Base 7 - Leetcode 504/Base 7 - Leetcode 504.cpp @@ -0,0 +1,28 @@ +#include +#include + +class Solution { +public: + std::string convertToBase7(int num) { + if (num == 0) { + return "0"; + } + + int originalNum = num; + num = abs(num); + std::string remainders; + + while (num > 0) { + int remainder = num % 7; + remainders.push_back(remainder + '0'); + num /= 7; + } + + if (originalNum < 0) { + remainders.push_back('-'); + } + + std::reverse(remainders.begin(), remainders.end()); + return remainders; + } +}; diff --git a/Base 7 - Leetcode 504/Base 7 - Leetcode 504.java b/Base 7 - Leetcode 504/Base 7 - Leetcode 504.java new file mode 100644 index 0000000..03ae68f --- /dev/null +++ b/Base 7 - Leetcode 504/Base 7 - Leetcode 504.java @@ -0,0 +1,23 @@ +public class Solution { + public String convertToBase7(int num) { + if (num == 0) { + return "0"; + } + + int originalNum = num; + num = Math.abs(num); + StringBuilder remainders = new StringBuilder(); + + while (num > 0) { + int remainder = num % 7; + remainders.append(remainder); + num /= 7; + } + + if (originalNum < 0) { + remainders.append('-'); + } + + return remainders.reverse().toString(); + } +} diff --git a/Base 7 - Leetcode 504/Base 7 - Leetcode 504.js b/Base 7 - Leetcode 504/Base 7 - Leetcode 504.js new file mode 100644 index 0000000..90a4a9d --- /dev/null +++ b/Base 7 - Leetcode 504/Base 7 - Leetcode 504.js @@ -0,0 +1,22 @@ +var convertToBase7 = function(num) { + if (num === 0) { + return '0'; + } + + var originalNum = num; + num = Math.abs(num); + var remainders = []; + + while (num > 0) { + var remainder = num % 7; + remainders.push(String(remainder)); + num = Math.floor(num / 7); + } + + if (originalNum < 0) { + remainders.push('-'); + } + + remainders.reverse(); + return remainders.join(''); +}; diff --git a/Base 7 - Leetcode 504/Base 7 - Leetcode 504.py b/Base 7 - Leetcode 504/Base 7 - Leetcode 504.py new file mode 100644 index 0000000..601ff98 --- /dev/null +++ b/Base 7 - Leetcode 504/Base 7 - Leetcode 504.py @@ -0,0 +1,20 @@ +class Solution: + def convertToBase7(self, num: int) -> str: + if num == 0: + return '0' + + original_num = num + num = abs(num) + remainders = [] + + while num > 0: + remainder = num % 7 + remainders.append(str(remainder)) + num //= 7 + + if original_num < 0: + remainders.append('-') + remainders.reverse() + return ''.join(remainders) + + # Time and Space: O(log_7(N)) \ No newline at end of file diff --git a/Baseball Game - Leetcode 682/Baseball Game - Leetcode 682.cpp b/Baseball Game - Leetcode 682/Baseball Game - Leetcode 682.cpp new file mode 100644 index 0000000..ac00d5c --- /dev/null +++ b/Baseball Game - Leetcode 682/Baseball Game - Leetcode 682.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + int calPoints(vector& operations) { + stack stk; + + for (const string& op : operations) { + if (op == "+") { + int top = stk.top(); stk.pop(); + int newTop = top + stk.top(); + stk.push(top); + stk.push(newTop); + } else if (op == "D") { + stk.push(2 * stk.top()); + } else if (op == "C") { + stk.pop(); + } else { + stk.push(stoi(op)); + } + } + + int sum = 0; + while (!stk.empty()) { + sum += stk.top(); stk.pop(); + } + + return sum; + } +}; diff --git a/Baseball Game - Leetcode 682/Baseball Game - Leetcode 682.java b/Baseball Game - Leetcode 682/Baseball Game - Leetcode 682.java new file mode 100644 index 0000000..7177a1b --- /dev/null +++ b/Baseball Game - Leetcode 682/Baseball Game - Leetcode 682.java @@ -0,0 +1,29 @@ +import java.util.*; + +public class Solution { + public int calPoints(String[] operations) { + Stack stack = new Stack<>(); + + for (String op : operations) { + if (op.equals("+")) { + int top = stack.pop(); + int newTop = top + stack.peek(); + stack.push(top); + stack.push(newTop); + } else if (op.equals("D")) { + stack.push(stack.peek() * 2); + } else if (op.equals("C")) { + stack.pop(); + } else { + stack.push(Integer.parseInt(op)); + } + } + + int sum = 0; + while (!stack.isEmpty()) { + sum += stack.pop(); + } + + return sum; + } +} diff --git a/Baseball Game - Leetcode 682/Baseball Game - Leetcode 682.js b/Baseball Game - Leetcode 682/Baseball Game - Leetcode 682.js new file mode 100644 index 0000000..89c3d53 --- /dev/null +++ b/Baseball Game - Leetcode 682/Baseball Game - Leetcode 682.js @@ -0,0 +1,24 @@ +/** + * @param {string[]} operations + * @return {number} + */ +var calPoints = function(operations) { + const stack = []; + + for (const op of operations) { + if (op === "+") { + const top = stack.pop(); + const newTop = top + stack[stack.length - 1]; + stack.push(top); + stack.push(newTop); + } else if (op === "D") { + stack.push(stack[stack.length - 1] * 2); + } else if (op === "C") { + stack.pop(); + } else { + stack.push(parseInt(op)); + } + } + + return stack.reduce((acc, val) => acc + val, 0); +}; diff --git a/Baseball Game - Leetcode 682.py b/Baseball Game - Leetcode 682/Baseball Game - Leetcode 682.py similarity index 100% rename from Baseball Game - Leetcode 682.py rename to Baseball Game - Leetcode 682/Baseball Game - Leetcode 682.py diff --git a/Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.cpp b/Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.cpp new file mode 100644 index 0000000..cdad257 --- /dev/null +++ b/Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.cpp @@ -0,0 +1,23 @@ +#include +#include +using namespace std; + +class Solution { +public: + int maxProfit(vector& prices) { + int minPrice = INT_MAX; + int maxProfit = 0; + + for (int price : prices) { + if (price < minPrice) { + minPrice = price; + } + int profit = price - minPrice; + if (profit > maxProfit) { + maxProfit = profit; + } + } + + return maxProfit; + } +}; diff --git a/Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.java b/Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.java new file mode 100644 index 0000000..3e8ec5d --- /dev/null +++ b/Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.java @@ -0,0 +1,18 @@ +public class Solution { + public int maxProfit(int[] prices) { + int minPrice = Integer.MAX_VALUE; + int maxProfit = 0; + + for (int price : prices) { + if (price < minPrice) { + minPrice = price; + } + int profit = price - minPrice; + if (profit > maxProfit) { + maxProfit = profit; + } + } + + return maxProfit; + } +} diff --git a/Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.js b/Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.js new file mode 100644 index 0000000..044e54d --- /dev/null +++ b/Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.js @@ -0,0 +1,20 @@ +/** + * @param {number[]} prices + * @return {number} + */ +var maxProfit = function(prices) { + let minPrice = Infinity; + let maxProfit = 0; + + for (const price of prices) { + if (price < minPrice) { + minPrice = price; + } + const profit = price - minPrice; + if (profit > maxProfit) { + maxProfit = profit; + } + } + + return maxProfit; +}; diff --git a/Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.py b/Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.py new file mode 100644 index 0000000..faf4100 --- /dev/null +++ b/Best Time to Buy and Sell Stock - Leetcode 121/Best Time to Buy and Sell Stock - Leetcode 121.py @@ -0,0 +1,50 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + max_profit = 0 + for i in range(len(prices)): + for j in range(i+1, len(prices)): + profit = prices[j] - prices[i] + + if profit > 0: + max_profit = max(max_profit, profit) + + return max_profit + # Time: O(N^2) (Brute Force) + # Space: O(1) + # This was modified from the video explanation to let max_profit = 0, this is better + + +class Solution: + def maxProfit(self, prices: List[int]) -> int: + # Time: O(n) + # Space: O(1) + min_price = float('inf') + max_profit = 0 + + for price in prices: + if price < min_price: + min_price = price + + profit = price - min_price + + if profit > max_profit: + max_profit = profit + + return max_profit + + +# Optimal Solution for Bootcamp +class Solution: + def maxProfit(self, prices: List[int]) -> int: + # Time: O(n) + # Space: O(1) + min_price = float('inf') + max_profit = 0 + + for price in prices: + profit = price - min_price + + min_price = min(price, min_price) + max_profit = max(profit, max_profit) + + return max_profit diff --git a/Best Time to Buy and Sell Stock II - Leetcode 122/Best Time to Buy and Sell Stock II - Leetcode 122.cpp b/Best Time to Buy and Sell Stock II - Leetcode 122/Best Time to Buy and Sell Stock II - Leetcode 122.cpp new file mode 100644 index 0000000..4b23e49 --- /dev/null +++ b/Best Time to Buy and Sell Stock II - Leetcode 122/Best Time to Buy and Sell Stock II - Leetcode 122.cpp @@ -0,0 +1,30 @@ +#include + +class Solution { +public: + int maxProfit(std::vector& prices) { + int i = 0; + int lo = prices[0]; + int hi = prices[0]; + int profit = 0; + int n = prices.size(); + + while (i < n - 1) { + // Look where to buy + while (i < n - 1 && prices[i] >= prices[i + 1]) { + i++; + } + lo = prices[i]; + + // Look where to sell + while (i < n - 1 && prices[i] <= prices[i + 1]) { + i++; + } + hi = prices[i]; + + profit += hi - lo; + } + + return profit; + } +}; diff --git a/Best Time to Buy and Sell Stock II - Leetcode 122/Best Time to Buy and Sell Stock II - Leetcode 122.java b/Best Time to Buy and Sell Stock II - Leetcode 122/Best Time to Buy and Sell Stock II - Leetcode 122.java new file mode 100644 index 0000000..014e89c --- /dev/null +++ b/Best Time to Buy and Sell Stock II - Leetcode 122/Best Time to Buy and Sell Stock II - Leetcode 122.java @@ -0,0 +1,27 @@ +class Solution { + public int maxProfit(int[] prices) { + int i = 0; + int lo = prices[0]; + int hi = prices[0]; + int profit = 0; + int n = prices.length; + + while (i < n - 1) { + // Look where to buy + while (i < n - 1 && prices[i] >= prices[i + 1]) { + i++; + } + lo = prices[i]; + + // Look where to sell + while (i < n - 1 && prices[i] <= prices[i + 1]) { + i++; + } + hi = prices[i]; + + profit += hi - lo; + } + + return profit; + } +} diff --git a/Best Time to Buy and Sell Stock II - Leetcode 122/Best Time to Buy and Sell Stock II - Leetcode 122.js b/Best Time to Buy and Sell Stock II - Leetcode 122/Best Time to Buy and Sell Stock II - Leetcode 122.js new file mode 100644 index 0000000..ba53568 --- /dev/null +++ b/Best Time to Buy and Sell Stock II - Leetcode 122/Best Time to Buy and Sell Stock II - Leetcode 122.js @@ -0,0 +1,25 @@ +var maxProfit = function(prices) { + var i = 0; + var lo = prices[0]; + var hi = prices[0]; + var profit = 0; + var n = prices.length; + + while (i < n - 1) { + // Look where to buy + while (i < n - 1 && prices[i] >= prices[i + 1]) { + i++; + } + lo = prices[i]; + + // Look where to sell + while (i < n - 1 && prices[i] <= prices[i + 1]) { + i++; + } + hi = prices[i]; + + profit += hi - lo; + } + + return profit; +}; diff --git a/Best Time to Buy and Sell Stock II - Leetcode 122/Best Time to Buy and Sell Stock II - Leetcode 122.py b/Best Time to Buy and Sell Stock II - Leetcode 122/Best Time to Buy and Sell Stock II - Leetcode 122.py new file mode 100644 index 0000000..c3cb31b --- /dev/null +++ b/Best Time to Buy and Sell Stock II - Leetcode 122/Best Time to Buy and Sell Stock II - Leetcode 122.py @@ -0,0 +1,22 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + i = 0 + lo = prices[0] + hi = prices[0] + profit = 0 + n = len(prices) + + while i < n-1: + # look where to buy + while i < n-1 and prices[i] >= prices[i+1]: + i += 1 + lo = prices[i] + + # look where to sell + while i < n-1 and prices[i] <= prices[i+1]: + i += 1 + hi = prices[i] + + profit += hi - lo + + return profit # Time: O(n), Space: O(1) \ No newline at end of file diff --git a/Binary Search - Leetcode 704/Binary Search - Leetcode 704.cpp b/Binary Search - Leetcode 704/Binary Search - Leetcode 704.cpp new file mode 100644 index 0000000..3acf809 --- /dev/null +++ b/Binary Search - Leetcode 704/Binary Search - Leetcode 704.cpp @@ -0,0 +1,24 @@ +#include +using namespace std; + +class Solution { +public: + int search(vector& nums, int target) { + int left = 0; + int right = nums.size() - 1; + + while (left <= right) { + int middle = left + (right - left) / 2; + + if (nums[middle] == target) { + return middle; + } else if (nums[middle] > target) { + right = middle - 1; + } else { + left = middle + 1; + } + } + + return -1; + } +}; diff --git a/Binary Search - Leetcode 704/Binary Search - Leetcode 704.java b/Binary Search - Leetcode 704/Binary Search - Leetcode 704.java new file mode 100644 index 0000000..cc89454 --- /dev/null +++ b/Binary Search - Leetcode 704/Binary Search - Leetcode 704.java @@ -0,0 +1,20 @@ +public class Solution { + public int search(int[] nums, int target) { + int left = 0; + int right = nums.length - 1; + + while (left <= right) { + int middle = left + (right - left) / 2; + + if (nums[middle] == target) { + return middle; + } else if (nums[middle] > target) { + right = middle - 1; + } else { + left = middle + 1; + } + } + + return -1; + } +} diff --git a/Binary Search - Leetcode 704/Binary Search - Leetcode 704.js b/Binary Search - Leetcode 704/Binary Search - Leetcode 704.js new file mode 100644 index 0000000..bbf1d8c --- /dev/null +++ b/Binary Search - Leetcode 704/Binary Search - Leetcode 704.js @@ -0,0 +1,23 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number} + */ +var search = function(nums, target) { + let left = 0; + let right = nums.length - 1; + + while (left <= right) { + const middle = Math.floor(left + (right - left) / 2); + + if (nums[middle] === target) { + return middle; + } else if (nums[middle] > target) { + right = middle - 1; + } else { + left = middle + 1; + } + } + + return -1; +}; diff --git a/Binary Search - Leetcode 704.py b/Binary Search - Leetcode 704/Binary Search - Leetcode 704.py similarity index 63% rename from Binary Search - Leetcode 704.py rename to Binary Search - Leetcode 704/Binary Search - Leetcode 704.py index 12a81b5..ad5c032 100644 --- a/Binary Search - Leetcode 704.py +++ b/Binary Search - Leetcode 704/Binary Search - Leetcode 704.py @@ -1,3 +1,14 @@ +# Brute Force Solution +class Solution: + def search(self, nums: List[int], target: int) -> int: + n = len(nums) + for i in range(n): + if nums[i] == target: + return i + return -1 + # Time: O(n) + # Space: O(1) + class Solution: def search(self, nums: List[int], target: int) -> int: left = 0 diff --git a/Binary Tree Level Order Traversal (BFS) - Leetcode 102/Binary Tree Level Order Traversal (BFS) - Leetcode 102.cpp b/Binary Tree Level Order Traversal (BFS) - Leetcode 102/Binary Tree Level Order Traversal (BFS) - Leetcode 102.cpp new file mode 100644 index 0000000..d2f1eeb --- /dev/null +++ b/Binary Tree Level Order Traversal (BFS) - Leetcode 102/Binary Tree Level Order Traversal (BFS) - Leetcode 102.cpp @@ -0,0 +1,33 @@ +#include +#include +using namespace std; + + + +class Solution { +public: + vector> levelOrder(TreeNode* root) { + vector> ans; + if (!root) return ans; + + queue q; + q.push(root); + + while (!q.empty()) { + vector level; + int n = q.size(); + + for (int i = 0; i < n; ++i) { + TreeNode* node = q.front(); q.pop(); + level.push_back(node->val); + + if (node->left) q.push(node->left); + if (node->right) q.push(node->right); + } + + ans.push_back(level); + } + + return ans; + } +}; diff --git a/Binary Tree Level Order Traversal (BFS) - Leetcode 102/Binary Tree Level Order Traversal (BFS) - Leetcode 102.java b/Binary Tree Level Order Traversal (BFS) - Leetcode 102/Binary Tree Level Order Traversal (BFS) - Leetcode 102.java new file mode 100644 index 0000000..5640371 --- /dev/null +++ b/Binary Tree Level Order Traversal (BFS) - Leetcode 102/Binary Tree Level Order Traversal (BFS) - Leetcode 102.java @@ -0,0 +1,41 @@ +import java.util.*; + +public class Solution { + public List> levelOrder(TreeNode root) { + List> ans = new ArrayList<>(); + if (root == null) return ans; + + Queue queue = new LinkedList<>(); + queue.add(root); + + while (!queue.isEmpty()) { + List level = new ArrayList<>(); + int n = queue.size(); + + for (int i = 0; i < n; i++) { + TreeNode node = queue.poll(); + level.add(node.val); + + if (node.left != null) queue.add(node.left); + if (node.right != null) queue.add(node.right); + } + + ans.add(level); + } + + return ans; + } +} + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode() {} + TreeNode(int val) { this.val = val; } + TreeNode(int val, TreeNode left, TreeNode right) { + this.val = val; + this.left = left; + this.right = right; + } +} diff --git a/Binary Tree Level Order Traversal (BFS) - Leetcode 102/Binary Tree Level Order Traversal (BFS) - Leetcode 102.js b/Binary Tree Level Order Traversal (BFS) - Leetcode 102/Binary Tree Level Order Traversal (BFS) - Leetcode 102.js new file mode 100644 index 0000000..4422bbc --- /dev/null +++ b/Binary Tree Level Order Traversal (BFS) - Leetcode 102/Binary Tree Level Order Traversal (BFS) - Leetcode 102.js @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = val; + * this.left = left === undefined ? null : left; + * this.right = right === undefined ? null : right; + * } + */ + +/** + * @param {TreeNode} root + * @return {number[][]} + */ +var levelOrder = function(root) { + if (!root) return []; + + const ans = []; + const queue = [root]; + + while (queue.length > 0) { + const level = []; + const n = queue.length; + + for (let i = 0; i < n; i++) { + const node = queue.shift(); + level.push(node.val); + + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + + ans.push(level); + } + + return ans; +}; diff --git a/Binary Tree Level Order Traversal (BFS) - Leetcode 102.py b/Binary Tree Level Order Traversal (BFS) - Leetcode 102/Binary Tree Level Order Traversal (BFS) - Leetcode 102.py similarity index 100% rename from Binary Tree Level Order Traversal (BFS) - Leetcode 102.py rename to Binary Tree Level Order Traversal (BFS) - Leetcode 102/Binary Tree Level Order Traversal (BFS) - Leetcode 102.py diff --git a/Bitwise AND of Numbers Range - Leetcode 201/Bitwise AND of Numbers Range - Leetcode 201.cpp b/Bitwise AND of Numbers Range - Leetcode 201/Bitwise AND of Numbers Range - Leetcode 201.cpp new file mode 100644 index 0000000..f20d365 --- /dev/null +++ b/Bitwise AND of Numbers Range - Leetcode 201/Bitwise AND of Numbers Range - Leetcode 201.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int rangeBitwiseAnd(int m, int n) { + int shift = 0; + + // Shift both numbers to the right until they are equal + while (m < n) { + m >>= 1; + n >>= 1; + shift++; + } + + // Shift the common prefix back to its original position + return m << shift; + } +}; diff --git a/Bitwise AND of Numbers Range - Leetcode 201/Bitwise AND of Numbers Range - Leetcode 201.java b/Bitwise AND of Numbers Range - Leetcode 201/Bitwise AND of Numbers Range - Leetcode 201.java new file mode 100644 index 0000000..542153f --- /dev/null +++ b/Bitwise AND of Numbers Range - Leetcode 201/Bitwise AND of Numbers Range - Leetcode 201.java @@ -0,0 +1,15 @@ +public class Solution { + public int rangeBitwiseAnd(int m, int n) { + int shift = 0; + + // Shift both numbers to the right until they are equal + while (m < n) { + m >>= 1; + n >>= 1; + shift++; + } + + // Shift the common prefix back to its original position + return m << shift; + } +} diff --git a/Bitwise AND of Numbers Range - Leetcode 201/Bitwise AND of Numbers Range - Leetcode 201.js b/Bitwise AND of Numbers Range - Leetcode 201/Bitwise AND of Numbers Range - Leetcode 201.js new file mode 100644 index 0000000..af2bccc --- /dev/null +++ b/Bitwise AND of Numbers Range - Leetcode 201/Bitwise AND of Numbers Range - Leetcode 201.js @@ -0,0 +1,13 @@ +var rangeBitwiseAnd = function(m, n) { + let shift = 0; + + // Shift both numbers to the right until they are equal + while (m < n) { + m >>= 1; + n >>= 1; + shift++; + } + + // Shift the common prefix back to its original position + return m << shift; +}; diff --git a/Bitwise AND of Numbers Range - Leetcode 201/Bitwise AND of Numbers Range - Leetcode 201.py b/Bitwise AND of Numbers Range - Leetcode 201/Bitwise AND of Numbers Range - Leetcode 201.py new file mode 100644 index 0000000..66d6758 --- /dev/null +++ b/Bitwise AND of Numbers Range - Leetcode 201/Bitwise AND of Numbers Range - Leetcode 201.py @@ -0,0 +1,12 @@ +class Solution: + def rangeBitwiseAnd(self, m: int, n: int) -> int: + shift = 0 + + while m < n: + m = m >> 1 + n = n >> 1 + shift += 1 + + return m << shift + # Time: O(Bits) + # Space: O(1) \ No newline at end of file diff --git a/Climbing Stairs - Leetcode 70/Climbing Stairs - Leetcode 70.cpp b/Climbing Stairs - Leetcode 70/Climbing Stairs - Leetcode 70.cpp new file mode 100644 index 0000000..84011f2 --- /dev/null +++ b/Climbing Stairs - Leetcode 70/Climbing Stairs - Leetcode 70.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int climbStairs(int n) { + if (n == 1) return 1; + if (n == 2) return 2; + + int twoBack = 1; + int oneBack = 2; + + for (int i = 2; i < n; ++i) { + int nextNum = twoBack + oneBack; + twoBack = oneBack; + oneBack = nextNum; + } + + return oneBack; + } +}; diff --git a/Climbing Stairs - Leetcode 70/Climbing Stairs - Leetcode 70.java b/Climbing Stairs - Leetcode 70/Climbing Stairs - Leetcode 70.java new file mode 100644 index 0000000..157282a --- /dev/null +++ b/Climbing Stairs - Leetcode 70/Climbing Stairs - Leetcode 70.java @@ -0,0 +1,17 @@ +public class Solution { + public int climbStairs(int n) { + if (n == 1) return 1; + if (n == 2) return 2; + + int twoBack = 1; + int oneBack = 2; + + for (int i = 2; i < n; i++) { + int nextNum = twoBack + oneBack; + twoBack = oneBack; + oneBack = nextNum; + } + + return oneBack; + } +} diff --git a/Climbing Stairs - Leetcode 70/Climbing Stairs - Leetcode 70.js b/Climbing Stairs - Leetcode 70/Climbing Stairs - Leetcode 70.js new file mode 100644 index 0000000..c892a03 --- /dev/null +++ b/Climbing Stairs - Leetcode 70/Climbing Stairs - Leetcode 70.js @@ -0,0 +1,19 @@ +/** + * @param {number} n + * @return {number} + */ +var climbStairs = function(n) { + if (n === 1) return 1; + if (n === 2) return 2; + + let twoBack = 1; + let oneBack = 2; + + for (let i = 2; i < n; i++) { + const nextNum = twoBack + oneBack; + twoBack = oneBack; + oneBack = nextNum; + } + + return oneBack; +}; diff --git a/Climbing Stairs - Leetcode 70.py b/Climbing Stairs - Leetcode 70/Climbing Stairs - Leetcode 70.py similarity index 100% rename from Climbing Stairs - Leetcode 70.py rename to Climbing Stairs - Leetcode 70/Climbing Stairs - Leetcode 70.py diff --git a/Clone Graph - Leetcode 133/Clone Graph - Leetcode 133.cpp b/Clone Graph - Leetcode 133/Clone Graph - Leetcode 133.cpp new file mode 100644 index 0000000..638b5a5 --- /dev/null +++ b/Clone Graph - Leetcode 133/Clone Graph - Leetcode 133.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +#include +using namespace std; + + +class Solution { +public: + Node* cloneGraph(Node* node) { + if (!node) return nullptr; + + unordered_map oToN; + stack stk; + unordered_set visited; + + stk.push(node); + visited.insert(node); + + // DFS to create the nodes + while (!stk.empty()) { + Node* curr = stk.top(); + stk.pop(); + oToN[curr] = new Node(curr->val); + + for (Node* nei : curr->neighbors) { + if (visited.find(nei) == visited.end()) { + visited.insert(nei); + stk.push(nei); + } + } + } + + // DFS to set up neighbors + for (auto& entry : oToN) { + Node* oldNode = entry.first; + Node* newNode = entry.second; + for (Node* nei : oldNode->neighbors) { + newNode->neighbors.push_back(oToN[nei]); + } + } + + return oToN[node]; + } +}; diff --git a/Clone Graph - Leetcode 133/Clone Graph - Leetcode 133.java b/Clone Graph - Leetcode 133/Clone Graph - Leetcode 133.java new file mode 100644 index 0000000..d46eb4b --- /dev/null +++ b/Clone Graph - Leetcode 133/Clone Graph - Leetcode 133.java @@ -0,0 +1,40 @@ +import java.util.*; + +public class Solution { + public Node cloneGraph(Node node) { + if (node == null) return null; + + Map oToN = new HashMap<>(); + Stack stk = new Stack<>(); + Set visited = new HashSet<>(); + + stk.push(node); + visited.add(node); + + // DFS to create the nodes + while (!stk.isEmpty()) { + Node curr = stk.pop(); + oToN.put(curr, new Node(curr.val)); + + for (Node nei : curr.neighbors) { + if (!visited.contains(nei)) { + visited.add(nei); + stk.push(nei); + } + } + } + + // DFS to set up neighbors + for (Map.Entry entry : oToN.entrySet()) { + Node oldNode = entry.getKey(); + Node newNode = entry.getValue(); + for (Node nei : oldNode.neighbors) { + newNode.neighbors.add(oToN.get(nei)); + } + } + + return oToN.get(node); + } +} + + diff --git a/Clone Graph - Leetcode 133/Clone Graph - Leetcode 133.js b/Clone Graph - Leetcode 133/Clone Graph - Leetcode 133.js new file mode 100644 index 0000000..40b6b48 --- /dev/null +++ b/Clone Graph - Leetcode 133/Clone Graph - Leetcode 133.js @@ -0,0 +1,43 @@ +/** + * Definition for a Node. + * function Node(val, neighbors) { + * this.val = val; + * this.neighbors = neighbors === undefined ? [] : neighbors; + * } + */ + +/** + * @param {Node} node + * @return {Node} + */ +var cloneGraph = function(node) { + if (!node) return null; + + const oToN = new Map(); + const stk = [node]; + const visited = new Set(); + + visited.add(node); + + // DFS to create the nodes + while (stk.length > 0) { + const curr = stk.pop(); + oToN.set(curr, new Node(curr.val)); + + for (const nei of curr.neighbors) { + if (!visited.has(nei)) { + visited.add(nei); + stk.push(nei); + } + } + } + + // DFS to set up neighbors + for (const [oldNode, newNode] of oToN.entries()) { + for (const nei of oldNode.neighbors) { + newNode.neighbors.push(oToN.get(nei)); + } + } + + return oToN.get(node); +}; diff --git a/Clone Graph - Leetcode 133.py b/Clone Graph - Leetcode 133/Clone Graph - Leetcode 133.py similarity index 100% rename from Clone Graph - Leetcode 133.py rename to Clone Graph - Leetcode 133/Clone Graph - Leetcode 133.py diff --git a/Coin Change - Leetcode 322.py b/Coin Change - Leetcode 322.py deleted file mode 100644 index 9080678..0000000 --- a/Coin Change - Leetcode 322.py +++ /dev/null @@ -1,19 +0,0 @@ -class Solution: - def coinChange(self, coins: List[int], amount: int) -> int: - n = len(coins) - coins.sort() - dp = [float('inf')] * (amount + 1) - dp[0] = 0 - - for i in range(1, amount+1): - for coin in coins: - difference = i - coin - if difference < 0: - break - dp[i] = min(dp[i], 1+dp[difference]) - - - return dp[amount] if dp[amount] < float('inf') else -1 - # Let C be the number of coins and A be the amount. - # Time Complexity: O(C * Amount) - # Space Complexity: O(Amount) diff --git a/Coin Change - Leetcode 322/Coin Change - Leetcode 322.cpp b/Coin Change - Leetcode 322/Coin Change - Leetcode 322.cpp new file mode 100644 index 0000000..0482c5d --- /dev/null +++ b/Coin Change - Leetcode 322/Coin Change - Leetcode 322.cpp @@ -0,0 +1,47 @@ +#include +#include +using namespace std; + + +/** + * Brute force approach with simple recursion + */ +class Solution { +public: + int coinChange(vector& coins, int amount) { + if (amount == 0) + return 0; + else if (amount < 0) + return -1; + + int min_cnt = -1; + for (int coin : coins) { + int cnt = coinChange(coins, amount - coin); + if (cnt >= 0) + min_cnt = min_cnt < 0 ? cnt + 1 : min(min_cnt, cnt + 1); + } + return min_cnt; + } +}; + + + +class Solution { +public: + int coinChange(vector& coins, int amount) { + vector dp(amount + 1, INT_MAX); + dp[0] = 0; + sort(coins.begin(), coins.end()); + + for (int i = 1; i <= amount; ++i) { + for (int coin : coins) { + if (i - coin < 0) break; + if (dp[i - coin] != INT_MAX) { + dp[i] = min(dp[i], dp[i - coin] + 1); + } + } + } + + return dp[amount] < INT_MAX ? dp[amount] : -1; + } +}; diff --git a/Coin Change - Leetcode 322/Coin Change - Leetcode 322.java b/Coin Change - Leetcode 322/Coin Change - Leetcode 322.java new file mode 100644 index 0000000..59c5ade --- /dev/null +++ b/Coin Change - Leetcode 322/Coin Change - Leetcode 322.java @@ -0,0 +1,44 @@ +import java.util.Arrays; + + +/** + * Brute force approach with simple recursion + */ +class Solution { + public int coinChange(int[] coins, int amount) { + if (amount == 0) + return 0; + else if (amount < 0) + return -1; + + int min_cnt = -1; + for (int coin : coins) { + int cnt = coinChange(coins, amount - coin); + if (cnt >= 0) + min_cnt = min_cnt < 0 ? cnt + 1 : Math.min(min_cnt, cnt + 1); + } + return min_cnt; + } +} + + + +public class Solution { + public int coinChange(int[] coins, int amount) { + int[] dp = new int[amount + 1]; + Arrays.fill(dp, Integer.MAX_VALUE); + dp[0] = 0; // base case: 0 amount requires 0 coins + Arrays.sort(coins); + + for (int i = 1; i <= amount; i++) { + for (int coin : coins) { + if (i - coin < 0) break; + if (dp[i - coin] != Integer.MAX_VALUE) { + dp[i] = Math.min(dp[i], dp[i - coin] + 1); + } + } + } + + return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount]; + } +} diff --git a/Coin Change - Leetcode 322/Coin Change - Leetcode 322.js b/Coin Change - Leetcode 322/Coin Change - Leetcode 322.js new file mode 100644 index 0000000..e6aee29 --- /dev/null +++ b/Coin Change - Leetcode 322/Coin Change - Leetcode 322.js @@ -0,0 +1,42 @@ +/** + * Brute force approach with simple recursion + * + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ +var coinChange = function(coins, amount) { + if (amount == 0) + return 0; + else if (amount < 0) + return -1; + + let min_cnt = -1; + for (let coin of coins) { + let cnt = coinChange(coins, amount - coin); + if (cnt >= 0) + min_cnt = min_cnt < 0 ? cnt + 1 : Math.min(min_cnt, cnt + 1); + } + return min_cnt; +}; + + +/** + * @param {number[]} coins + * @param {number} amount + * @return {number} + */ +var coinChange = function(coins, amount) { + const dp = new Array(amount + 1).fill(Infinity); + dp[0] = 0; + coins.sort((a, b) => a - b); + + for (let i = 1; i <= amount; i++) { + for (const coin of coins) { + if (i - coin < 0) break; + dp[i] = Math.min(dp[i], dp[i - coin] + 1); + } + } + + return dp[amount] < Infinity ? dp[amount] : -1; +}; diff --git a/Coin Change - Leetcode 322/Coin Change - Leetcode 322.py b/Coin Change - Leetcode 322/Coin Change - Leetcode 322.py new file mode 100644 index 0000000..6d88a3e --- /dev/null +++ b/Coin Change - Leetcode 322/Coin Change - Leetcode 322.py @@ -0,0 +1,73 @@ +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + # Brute force with simple recursion + # Time: O(Coins ^ Amount) + # Space: O(Amount) + if amount == 0: + return 0 + elif amount < 0: + return -1 + + min_cnt = -1 + for coin in coins: + cnt = self.coinChange(coins, amount - coin) + if cnt >= 0: + min_cnt = cnt + 1 if min_cnt < 0 else min(min_cnt, cnt + 1) + return min_cnt + + + +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + # Top Down DP (Memoization) + # Time: O(Coins * Amount) + # Space: O(Amount) + coins.sort() + memo = {0:0} + + def min_coins(amt): + if amt in memo: + return memo[amt] + + minn = float('inf') + for coin in coins: + diff = amt - coin + if diff < 0: + break + minn = min(minn, 1 + min_coins(diff)) + + memo[amt] = minn + return minn + + result = min_coins(amount) + if result < float('inf'): + return result + else: + return -1 + + + +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + # Bottom Up DP (Tabulation) + # Time: O(Coins * Amount) + # Space: O(Amount) + dp = [0] * (amount + 1) + coins.sort() + + for i in range(1, amount+1): + minn = float('inf') + + for coin in coins: + diff = i - coin + if diff < 0: + break + minn = min(minn, dp[diff] + 1) + + dp[i] = minn + + if dp[amount] < float('inf'): + return dp[amount] + else: + return -1 + diff --git a/Combination Sum - Leetcode 39.py b/Combination Sum - Leetcode 39.py deleted file mode 100644 index 30a6bfa..0000000 --- a/Combination Sum - Leetcode 39.py +++ /dev/null @@ -1,25 +0,0 @@ -class Solution: - def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: - res, sol = [], [] - nums = candidates - n = len(nums) - - def backtrack(i, cur_sum): - if cur_sum == target: - res.append(sol[:]) - return - - if cur_sum > target or i == n: - return - - backtrack(i + 1, cur_sum) - - sol.append(nums[i]) - backtrack(i, cur_sum + nums[i]) - sol.pop() - - backtrack(0, 0) - return res - -# Time Complexity: O(n^t) -# Space Complexity: O(n) diff --git a/Combination Sum - Leetcode 39/Combination Sum - Leetcode 39.cpp b/Combination Sum - Leetcode 39/Combination Sum - Leetcode 39.cpp new file mode 100644 index 0000000..6d87fb8 --- /dev/null +++ b/Combination Sum - Leetcode 39/Combination Sum - Leetcode 39.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; + +class Solution { +public: + vector> combinationSum(vector& candidates, int target) { + vector> res; + vector sol; + backtrack(candidates, target, 0, 0, sol, res); + return res; + } + +private: + void backtrack(vector& candidates, int target, int start, int curSum, vector& sol, vector>& res) { + if (curSum == target) { + res.push_back(sol); + return; + } + if (curSum > target || start == candidates.size()) { + return; + } + + // Skip the current candidate + backtrack(candidates, target, start + 1, curSum, sol, res); + + // Include the current candidate + sol.push_back(candidates[start]); + backtrack(candidates, target, start, curSum + candidates[start], sol, res); + sol.pop_back(); + } +}; diff --git a/Combination Sum - Leetcode 39/Combination Sum - Leetcode 39.java b/Combination Sum - Leetcode 39/Combination Sum - Leetcode 39.java new file mode 100644 index 0000000..6e230b5 --- /dev/null +++ b/Combination Sum - Leetcode 39/Combination Sum - Leetcode 39.java @@ -0,0 +1,28 @@ +import java.util.*; + +public class Solution { + public List> combinationSum(int[] candidates, int target) { + List> res = new ArrayList<>(); + List sol = new ArrayList<>(); + backtrack(candidates, target, 0, 0, sol, res); + return res; + } + + private void backtrack(int[] candidates, int target, int start, int curSum, List sol, List> res) { + if (curSum == target) { + res.add(new ArrayList<>(sol)); + return; + } + if (curSum > target || start == candidates.length) { + return; + } + + // Skip the current candidate + backtrack(candidates, target, start + 1, curSum, sol, res); + + // Include the current candidate + sol.add(candidates[start]); + backtrack(candidates, target, start, curSum + candidates[start], sol, res); + sol.remove(sol.size() - 1); + } +} diff --git a/Combination Sum - Leetcode 39/Combination Sum - Leetcode 39.js b/Combination Sum - Leetcode 39/Combination Sum - Leetcode 39.js new file mode 100644 index 0000000..bfee7ff --- /dev/null +++ b/Combination Sum - Leetcode 39/Combination Sum - Leetcode 39.js @@ -0,0 +1,29 @@ +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum = function(candidates, target) { + const res = []; + const sol = []; + backtrack(candidates, target, 0, 0, sol, res); + return res; +}; + +function backtrack(candidates, target, start, curSum, sol, res) { + if (curSum === target) { + res.push([...sol]); + return; + } + if (curSum > target || start === candidates.length) { + return; + } + + // Skip the current candidate + backtrack(candidates, target, start + 1, curSum, sol, res); + + // Include the current candidate + sol.push(candidates[start]); + backtrack(candidates, target, start, curSum + candidates[start], sol, res); + sol.pop(); +} diff --git a/Combination Sum - Leetcode 39/Combination Sum - Leetcode 39.py b/Combination Sum - Leetcode 39/Combination Sum - Leetcode 39.py new file mode 100644 index 0000000..e69de29 diff --git a/Combinations - Leetcode 77/Combinations - Leetcode 77.cpp b/Combinations - Leetcode 77/Combinations - Leetcode 77.cpp new file mode 100644 index 0000000..9dfe5d8 --- /dev/null +++ b/Combinations - Leetcode 77/Combinations - Leetcode 77.cpp @@ -0,0 +1,28 @@ +#include +using namespace std; + +class Solution { +public: + vector> combine(int n, int k) { + vector> ans; + vector sol; + backtrack(n, k, sol, ans); + return ans; + } + +private: + void backtrack(int x, int k, vector& sol, vector>& ans) { + if (sol.size() == k) { + ans.push_back(sol); + return; + } + + if (x > k - sol.size()) { + backtrack(x - 1, k, sol, ans); + } + + sol.push_back(x); + backtrack(x - 1, k, sol, ans); + sol.pop_back(); + } +}; diff --git a/Combinations - Leetcode 77/Combinations - Leetcode 77.java b/Combinations - Leetcode 77/Combinations - Leetcode 77.java new file mode 100644 index 0000000..b6f48b7 --- /dev/null +++ b/Combinations - Leetcode 77/Combinations - Leetcode 77.java @@ -0,0 +1,25 @@ +import java.util.*; + +public class Solution { + public List> combine(int n, int k) { + List> ans = new ArrayList<>(); + List sol = new ArrayList<>(); + backtrack(n, k, sol, ans); + return ans; + } + + private void backtrack(int x, int k, List sol, List> ans) { + if (sol.size() == k) { + ans.add(new ArrayList<>(sol)); + return; + } + + if (x > k - sol.size()) { + backtrack(x - 1, k, sol, ans); + } + + sol.add(x); + backtrack(x - 1, k, sol, ans); + sol.remove(sol.size() - 1); + } +} diff --git a/Combinations - Leetcode 77/Combinations - Leetcode 77.js b/Combinations - Leetcode 77/Combinations - Leetcode 77.js new file mode 100644 index 0000000..ec3eb5c --- /dev/null +++ b/Combinations - Leetcode 77/Combinations - Leetcode 77.js @@ -0,0 +1,26 @@ +/** + * @param {number} n + * @param {number} k + * @return {number[][]} + */ +var combine = function(n, k) { + const ans = []; + const sol = []; + backtrack(n, k, sol, ans); + return ans; +}; + +function backtrack(x, k, sol, ans) { + if (sol.length === k) { + ans.push([...sol]); + return; + } + + if (x > k - sol.length) { + backtrack(x - 1, k, sol, ans); + } + + sol.push(x); + backtrack(x - 1, k, sol, ans); + sol.pop(); +} diff --git a/Combinations - Leetcode 77.py b/Combinations - Leetcode 77/Combinations - Leetcode 77.py similarity index 100% rename from Combinations - Leetcode 77.py rename to Combinations - Leetcode 77/Combinations - Leetcode 77.py diff --git a/Container With Most Water - Leetcode 11/Container With Most Water - Leetcode 11.cpp b/Container With Most Water - Leetcode 11/Container With Most Water - Leetcode 11.cpp new file mode 100644 index 0000000..103857a --- /dev/null +++ b/Container With Most Water - Leetcode 11/Container With Most Water - Leetcode 11.cpp @@ -0,0 +1,28 @@ +#include +#include +using namespace std; + +class Solution { +public: + int maxArea(vector& height) { + int n = height.size(); + int l = 0; + int r = n - 1; + int maxArea = 0; + + while (l < r) { + int w = r - l; + int h = min(height[l], height[r]); + int a = w * h; + maxArea = max(maxArea, a); + + if (height[l] < height[r]) { + l++; + } else { + r--; + } + } + + return maxArea; + } +}; diff --git a/Container With Most Water - Leetcode 11/Container With Most Water - Leetcode 11.java b/Container With Most Water - Leetcode 11/Container With Most Water - Leetcode 11.java new file mode 100644 index 0000000..b48cec4 --- /dev/null +++ b/Container With Most Water - Leetcode 11/Container With Most Water - Leetcode 11.java @@ -0,0 +1,23 @@ +public class Solution { + public int maxArea(int[] height) { + int n = height.length; + int l = 0; + int r = n - 1; + int maxArea = 0; + + while (l < r) { + int w = r - l; + int h = Math.min(height[l], height[r]); + int a = w * h; + maxArea = Math.max(maxArea, a); + + if (height[l] < height[r]) { + l++; + } else { + r--; + } + } + + return maxArea; + } +} diff --git a/Container With Most Water - Leetcode 11/Container With Most Water - Leetcode 11.js b/Container With Most Water - Leetcode 11/Container With Most Water - Leetcode 11.js new file mode 100644 index 0000000..d4918af --- /dev/null +++ b/Container With Most Water - Leetcode 11/Container With Most Water - Leetcode 11.js @@ -0,0 +1,24 @@ +/** + * @param {number[]} height + * @return {number} + */ +var maxArea = function(height) { + let l = 0; + let r = height.length - 1; + let maxArea = 0; + + while (l < r) { + const w = r - l; + const h = Math.min(height[l], height[r]); + const a = w * h; + maxArea = Math.max(maxArea, a); + + if (height[l] < height[r]) { + l++; + } else { + r--; + } + } + + return maxArea; +}; diff --git a/Container With Most Water - Leetcode 11.py b/Container With Most Water - Leetcode 11/Container With Most Water - Leetcode 11.py similarity index 100% rename from Container With Most Water - Leetcode 11.py rename to Container With Most Water - Leetcode 11/Container With Most Water - Leetcode 11.py diff --git a/Contains Duplicate - Leetcode 217.py b/Contains Duplicate - Leetcode 217.py deleted file mode 100644 index c3897ef..0000000 --- a/Contains Duplicate - Leetcode 217.py +++ /dev/null @@ -1,12 +0,0 @@ -class Solution: - def containsDuplicate(self, nums: list[int]) -> bool: - h = set() - for num in nums: - if num in h: - return True - else: - h.add(num) - return False - -# Time Complexity: O(n) -# Space Complexity: O(n) diff --git a/Contains Duplicate - Leetcode 217/Contains Duplicate - Leetcode 217.cpp b/Contains Duplicate - Leetcode 217/Contains Duplicate - Leetcode 217.cpp new file mode 100644 index 0000000..4f16e3f --- /dev/null +++ b/Contains Duplicate - Leetcode 217/Contains Duplicate - Leetcode 217.cpp @@ -0,0 +1,17 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool containsDuplicate(vector& nums) { + unordered_set seen; + for (int num : nums) { + if (seen.find(num) != seen.end()) { + return true; + } + seen.insert(num); + } + return false; + } +}; diff --git a/Contains Duplicate - Leetcode 217/Contains Duplicate - Leetcode 217.java b/Contains Duplicate - Leetcode 217/Contains Duplicate - Leetcode 217.java new file mode 100644 index 0000000..6efdcf2 --- /dev/null +++ b/Contains Duplicate - Leetcode 217/Contains Duplicate - Leetcode 217.java @@ -0,0 +1,15 @@ +import java.util.HashSet; +import java.util.Set; + +public class Solution { + public boolean containsDuplicate(int[] nums) { + Set seen = new HashSet<>(); + for (int num : nums) { + if (seen.contains(num)) { + return true; + } + seen.add(num); + } + return false; + } +} diff --git a/Contains Duplicate - Leetcode 217/Contains Duplicate - Leetcode 217.js b/Contains Duplicate - Leetcode 217/Contains Duplicate - Leetcode 217.js new file mode 100644 index 0000000..69bb877 --- /dev/null +++ b/Contains Duplicate - Leetcode 217/Contains Duplicate - Leetcode 217.js @@ -0,0 +1,14 @@ +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function(nums) { + const seen = new Set(); + for (const num of nums) { + if (seen.has(num)) { + return true; + } + seen.add(num); + } + return false; +}; diff --git a/Contains Duplicate - Leetcode 217/Contains Duplicate - Leetcode 217.py b/Contains Duplicate - Leetcode 217/Contains Duplicate - Leetcode 217.py new file mode 100644 index 0000000..2d506f9 --- /dev/null +++ b/Contains Duplicate - Leetcode 217/Contains Duplicate - Leetcode 217.py @@ -0,0 +1,39 @@ +# Brute Force Solution +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + n = len(nums) + + for i in range(n): + for j in range(n): + if nums[i] == nums[j] and i != j: + return True + return False + # Time Complexity: O(n^2) + # Space Complexity: O(1) + +# Better Brute Force Solution +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + n = len(nums) + + for i in range(n): + for j in range(i+1, n): + if nums[i] == nums[j]: + return True + return False + # Time Complexity: O(n^2) + # Space Complexity: O(1) + +# Optimal Solution +class Solution: + def containsDuplicate(self, nums: list[int]) -> bool: + s = set() + for num in nums: + if num in s: + return True + else: + s.add(num) + return False + +# Time Complexity: O(n) +# Space Complexity: O(n) diff --git a/Copy List with Random Pointer - Leetcode 138/Copy List with Random Pointer - Leetcode 138.cpp b/Copy List with Random Pointer - Leetcode 138/Copy List with Random Pointer - Leetcode 138.cpp new file mode 100644 index 0000000..6daa0bc --- /dev/null +++ b/Copy List with Random Pointer - Leetcode 138/Copy List with Random Pointer - Leetcode 138.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; + +class Solution { +public: + Node* copyRandomList(Node* head) { + if (!head) return nullptr; + + unordered_map oldToNew; + Node* curr = head; + + // First pass: create all nodes and put them in the map + while (curr) { + oldToNew[curr] = new Node(curr->val); + curr = curr->next; + } + + // Second pass: set next and random pointers + curr = head; + while (curr) { + Node* newNode = oldToNew[curr]; + newNode->next = oldToNew[curr->next]; + newNode->random = oldToNew[curr->random]; + curr = curr->next; + } + + return oldToNew[head]; + } +}; diff --git a/Copy List with Random Pointer - Leetcode 138/Copy List with Random Pointer - Leetcode 138.java b/Copy List with Random Pointer - Leetcode 138/Copy List with Random Pointer - Leetcode 138.java new file mode 100644 index 0000000..8900034 --- /dev/null +++ b/Copy List with Random Pointer - Leetcode 138/Copy List with Random Pointer - Leetcode 138.java @@ -0,0 +1,28 @@ +import java.util.HashMap; +import java.util.Map; + +public class Solution { + public Node copyRandomList(Node head) { + if (head == null) return null; + + Map oldToNew = new HashMap<>(); + Node curr = head; + + // First pass: create all nodes and put them in the map + while (curr != null) { + oldToNew.put(curr, new Node(curr.val)); + curr = curr.next; + } + + // Second pass: set next and random pointers + curr = head; + while (curr != null) { + Node newNode = oldToNew.get(curr); + newNode.next = oldToNew.get(curr.next); + newNode.random = oldToNew.get(curr.random); + curr = curr.next; + } + + return oldToNew.get(head); + } +} diff --git a/Copy List with Random Pointer - Leetcode 138/Copy List with Random Pointer - Leetcode 138.js b/Copy List with Random Pointer - Leetcode 138/Copy List with Random Pointer - Leetcode 138.js new file mode 100644 index 0000000..f5605b8 --- /dev/null +++ b/Copy List with Random Pointer - Leetcode 138/Copy List with Random Pointer - Leetcode 138.js @@ -0,0 +1,36 @@ +/** + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function(head) { + if (!head) return null; + + const oldToNew = new Map(); + let curr = head; + + // First pass: create all nodes and put them in the map + while (curr) { + oldToNew.set(curr, new Node(curr.val)); + curr = curr.next; + } + + // Second pass: set next and random pointers + curr = head; + while (curr) { + const newNode = oldToNew.get(curr); + newNode.next = oldToNew.get(curr.next) || null; + newNode.random = oldToNew.get(curr.random) || null; + curr = curr.next; + } + + return oldToNew.get(head); +}; + +/** + * Definition for a Node. + * function Node(val, next, random) { + * this.val = val; + * this.next = next; + * this.random = random; + * } + */ diff --git a/Copy List with Random Pointer - Leetcode 138.py b/Copy List with Random Pointer - Leetcode 138/Copy List with Random Pointer - Leetcode 138.py similarity index 100% rename from Copy List with Random Pointer - Leetcode 138.py rename to Copy List with Random Pointer - Leetcode 138/Copy List with Random Pointer - Leetcode 138.py diff --git a/Count Good Nodes in Binary Tree - Leetcode 1448/Count Good Nodes in Binary Tree - Leetcode 1448.cpp b/Count Good Nodes in Binary Tree - Leetcode 1448/Count Good Nodes in Binary Tree - Leetcode 1448.cpp new file mode 100644 index 0000000..8fbf66a --- /dev/null +++ b/Count Good Nodes in Binary Tree - Leetcode 1448/Count Good Nodes in Binary Tree - Leetcode 1448.cpp @@ -0,0 +1,29 @@ +#include +#include +using namespace std; + +class Solution { +public: + int goodNodes(TreeNode* root) { + if (!root) return 0; + + int goodNodes = 0; + stack> stk; + stk.push({root, INT_MIN}); + + while (!stk.empty()) { + auto [node, largest] = stk.top(); + stk.pop(); + + if (largest <= node->val) { + goodNodes++; + } + + largest = max(largest, node->val); + if (node->right) stk.push({node->right, largest}); + if (node->left) stk.push({node->left, largest}); + } + + return goodNodes; + } +}; diff --git a/Count Good Nodes in Binary Tree - Leetcode 1448/Count Good Nodes in Binary Tree - Leetcode 1448.java b/Count Good Nodes in Binary Tree - Leetcode 1448/Count Good Nodes in Binary Tree - Leetcode 1448.java new file mode 100644 index 0000000..9baec3f --- /dev/null +++ b/Count Good Nodes in Binary Tree - Leetcode 1448/Count Good Nodes in Binary Tree - Leetcode 1448.java @@ -0,0 +1,27 @@ +import java.util.Stack; + +public class Solution { + public int goodNodes(TreeNode root) { + if (root == null) return 0; + + int goodNodes = 0; + Stack> stk = new Stack<>(); + stk.push(new Pair<>(root, Integer.MIN_VALUE)); + + while (!stk.isEmpty()) { + Pair pair = stk.pop(); + TreeNode node = pair.getKey(); + int largest = pair.getValue(); + + if (largest <= node.val) { + goodNodes++; + } + + largest = Math.max(largest, node.val); + if (node.right != null) stk.push(new Pair<>(node.right, largest)); + if (node.left != null) stk.push(new Pair<>(node.left, largest)); + } + + return goodNodes; + } +} diff --git a/Count Good Nodes in Binary Tree - Leetcode 1448/Count Good Nodes in Binary Tree - Leetcode 1448.js b/Count Good Nodes in Binary Tree - Leetcode 1448/Count Good Nodes in Binary Tree - Leetcode 1448.js new file mode 100644 index 0000000..369e972 --- /dev/null +++ b/Count Good Nodes in Binary Tree - Leetcode 1448/Count Good Nodes in Binary Tree - Leetcode 1448.js @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + */ + +/** + * @param {TreeNode} root + * @return {number} + */ +var goodNodes = function(root) { + if (!root) return 0; + + let goodNodes = 0; + const stk = [[root, -Infinity]]; + + while (stk.length > 0) { + const [node, largest] = stk.pop(); + + if (largest <= node.val) { + goodNodes++; + } + + const newLargest = Math.max(largest, node.val); + if (node.right) stk.push([node.right, newLargest]); + if (node.left) stk.push([node.left, newLargest]); + } + + return goodNodes; +}; diff --git a/Count Good Nodes in Binary Tree - Leetcode 1448.py b/Count Good Nodes in Binary Tree - Leetcode 1448/Count Good Nodes in Binary Tree - Leetcode 1448.py similarity index 100% rename from Count Good Nodes in Binary Tree - Leetcode 1448.py rename to Count Good Nodes in Binary Tree - Leetcode 1448/Count Good Nodes in Binary Tree - Leetcode 1448.py diff --git a/Count Nodes Equal to Average of Subtree - Leetcode 2265/Count Nodes Equal to Average of Subtree - Leetcode 2265.cpp b/Count Nodes Equal to Average of Subtree - Leetcode 2265/Count Nodes Equal to Average of Subtree - Leetcode 2265.cpp new file mode 100644 index 0000000..dfa0c55 --- /dev/null +++ b/Count Nodes Equal to Average of Subtree - Leetcode 2265/Count Nodes Equal to Average of Subtree - Leetcode 2265.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; + +class Solution { +private: + int numNodes = 0; + +public: + int averageOfSubtree(TreeNode* root) { + dfs(root); + return numNodes; + } + + // Returns a pair: {number of nodes, sum of values} + pair dfs(TreeNode* root) { + if (!root) return {0, 0}; + + auto left = dfs(root->left); + auto right = dfs(root->right); + + int nodeCount = 1 + left.first + right.first; + int sum = root->val + left.second + right.second; + int avg = sum / nodeCount; + + if (root->val == avg) numNodes++; + + return {nodeCount, sum}; + } +}; diff --git a/Count Nodes Equal to Average of Subtree - Leetcode 2265/Count Nodes Equal to Average of Subtree - Leetcode 2265.java b/Count Nodes Equal to Average of Subtree - Leetcode 2265/Count Nodes Equal to Average of Subtree - Leetcode 2265.java new file mode 100644 index 0000000..6626517 --- /dev/null +++ b/Count Nodes Equal to Average of Subtree - Leetcode 2265/Count Nodes Equal to Average of Subtree - Leetcode 2265.java @@ -0,0 +1,23 @@ +public class Solution { + private int numNodes = 0; + + public int averageOfSubtree(TreeNode root) { + dfs(root); + return numNodes; + } + + private int[] dfs(TreeNode root) { + if (root == null) return new int[] {0, 0}; // {node count, sum of values} + + int[] left = dfs(root.left); + int[] right = dfs(root.right); + + int nodeCount = 1 + left[0] + right[0]; + int sum = root.val + left[1] + right[1]; + int avg = sum / nodeCount; + + if (root.val == avg) numNodes++; + + return new int[] {nodeCount, sum}; + } +} diff --git a/Count Nodes Equal to Average of Subtree - Leetcode 2265/Count Nodes Equal to Average of Subtree - Leetcode 2265.js b/Count Nodes Equal to Average of Subtree - Leetcode 2265/Count Nodes Equal to Average of Subtree - Leetcode 2265.js new file mode 100644 index 0000000..3413961 --- /dev/null +++ b/Count Nodes Equal to Average of Subtree - Leetcode 2265/Count Nodes Equal to Average of Subtree - Leetcode 2265.js @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + */ + +/** + * @param {TreeNode} root + * @return {number} + */ +var averageOfSubtree = function(root) { + let numNodes = 0; + + function dfs(node) { + if (!node) return [0, 0]; // [node count, sum of values] + + let [leftCount, leftSum] = dfs(node.left); + let [rightCount, rightSum] = dfs(node.right); + + let nodeCount = 1 + leftCount + rightCount; + let sum = node.val + leftSum + rightSum; + let avg = Math.floor(sum / nodeCount); + + if (node.val === avg) numNodes++; + + return [nodeCount, sum]; + } + + dfs(root); + return numNodes; +}; diff --git a/Count Nodes Equal to Average of Subtree - Leetcode 2265/Count Nodes Equal to Average of Subtree - Leetcode 2265.py b/Count Nodes Equal to Average of Subtree - Leetcode 2265/Count Nodes Equal to Average of Subtree - Leetcode 2265.py new file mode 100644 index 0000000..0fbfe13 --- /dev/null +++ b/Count Nodes Equal to Average of Subtree - Leetcode 2265/Count Nodes Equal to Average of Subtree - Leetcode 2265.py @@ -0,0 +1,26 @@ +class Solution: + def averageOfSubtree(self, root: TreeNode) -> int: + num_nodes = [0] + + def dfs(root): + if not root: + return (0, 0) + + N_left, summ_left = dfs(root.left) + N_right, summ_right = dfs(root.right) + + N = 1 + N_left + N_right + summ = root.val + summ_left + summ_right + avg = summ // N + + if root.val == avg: + num_nodes[0] += 1 + + return (N, summ) + + dfs(root) + return num_nodes[0] + # Time: O(N) + # Space: O(N) + + diff --git a/Course Schedule - Leetcode 207/Course Schedule - Leetcode 207.cpp b/Course Schedule - Leetcode 207/Course Schedule - Leetcode 207.cpp new file mode 100644 index 0000000..be629fe --- /dev/null +++ b/Course Schedule - Leetcode 207/Course Schedule - Leetcode 207.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool canFinish(int numCourses, vector>& prerequisites) { + unordered_map> graph; + for (const auto& pair : prerequisites) { + graph[pair[0]].push_back(pair[1]); + } + + vector states(numCourses, 0); // 0: UNVISITED, 1: VISITING, 2: VISITED + + for (int i = 0; i < numCourses; ++i) { + if (!dfs(i, graph, states)) { + return false; + } + } + + return true; + } + +private: + bool dfs(int node, unordered_map>& graph, vector& states) { + if (states[node] == 1) return false; // Cycle detected + if (states[node] == 2) return true; // Already visited + + states[node] = 1; // Mark as visiting + + for (int neighbor : graph[node]) { + if (!dfs(neighbor, graph, states)) { + return false; + } + } + + states[node] = 2; // Mark as visited + return true; + } +}; diff --git a/Course Schedule - Leetcode 207/Course Schedule - Leetcode 207.java b/Course Schedule - Leetcode 207/Course Schedule - Leetcode 207.java new file mode 100644 index 0000000..a528a4c --- /dev/null +++ b/Course Schedule - Leetcode 207/Course Schedule - Leetcode 207.java @@ -0,0 +1,41 @@ +import java.util.*; + +public class Solution { + public boolean canFinish(int numCourses, int[][] prerequisites) { + Map> graph = new HashMap<>(); + for (int[] pair : prerequisites) { + graph.computeIfAbsent(pair[0], k -> new ArrayList<>()).add(pair[1]); + } + + final int UNVISITED = 0; + final int VISITING = 1; + final int VISITED = 2; + int[] states = new int[numCourses]; + + for (int i = 0; i < numCourses; i++) { + if (!dfs(i, graph, states)) { + return false; + } + } + + return true; + } + + private boolean dfs(int node, Map> graph, int[] states) { + if (states[node] == 1) return false; // Cycle detected + if (states[node] == 2) return true; // Already visited + + states[node] = 1; // Mark as visiting + + if (graph.containsKey(node)) { + for (int neighbor : graph.get(node)) { + if (!dfs(neighbor, graph, states)) { + return false; + } + } + } + + states[node] = 2; // Mark as visited + return true; + } +} diff --git a/Course Schedule - Leetcode 207/Course Schedule - Leetcode 207.js b/Course Schedule - Leetcode 207/Course Schedule - Leetcode 207.js new file mode 100644 index 0000000..704b009 --- /dev/null +++ b/Course Schedule - Leetcode 207/Course Schedule - Leetcode 207.js @@ -0,0 +1,45 @@ +/** + * @param {number} numCourses + * @param {number[][]} prerequisites + * @return {boolean} + */ +var canFinish = function(numCourses, prerequisites) { + const graph = new Map(); + for (const [course, prereq] of prerequisites) { + if (!graph.has(course)) { + graph.set(course, []); + } + graph.get(course).push(prereq); + } + + const UNVISITED = 0; + const VISITING = 1; + const VISITED = 2; + const states = new Array(numCourses).fill(UNVISITED); + + const dfs = (node) => { + if (states[node] === VISITING) return false; // Cycle detected + if (states[node] === VISITED) return true; // Already visited + + states[node] = VISITING; // Mark as visiting + + if (graph.has(node)) { + for (const neighbor of graph.get(node)) { + if (!dfs(neighbor)) { + return false; + } + } + } + + states[node] = VISITED; // Mark as visited + return true; + }; + + for (let i = 0; i < numCourses; i++) { + if (!dfs(i)) { + return false; + } + } + + return true; +}; diff --git a/Course Schedule - Leetcode 207.py b/Course Schedule - Leetcode 207/Course Schedule - Leetcode 207.py similarity index 100% rename from Course Schedule - Leetcode 207.py rename to Course Schedule - Leetcode 207/Course Schedule - Leetcode 207.py diff --git a/Course Schedule II - Leetcode 210/Course Schedule II - Leetcode 210.cpp b/Course Schedule II - Leetcode 210/Course Schedule II - Leetcode 210.cpp new file mode 100644 index 0000000..91face3 --- /dev/null +++ b/Course Schedule II - Leetcode 210/Course Schedule II - Leetcode 210.cpp @@ -0,0 +1,34 @@ +class Solution { +public: + vector findOrder(int numCourses, vector>& prerequisites) { + vector order, inDegree(numCourses, 0); + unordered_map> map; + queue queue; + + for (auto& pre : prerequisites) { + int target = pre[0], preCourse = pre[1]; + map[preCourse].push_back(target); + inDegree[target] += 1; + } + for (int i = 0; i < numCourses; ++i) { + if (inDegree[i] == 0) { + queue.push(i); + } + } + while (!queue.empty()) { + int node = queue.front(); + queue.pop(); + order.push_back(node); + + if (map.find(node) != map.end()) { + for (int target : map[node]) { + inDegree[target] -= 1; + if (inDegree[target] == 0) { + queue.push(target); + } + } + } + } + return order.size() == numCourses ? order : vector(); + } +}; \ No newline at end of file diff --git a/Course Schedule II - Leetcode 210/Course Schedule II - Leetcode 210.java b/Course Schedule II - Leetcode 210/Course Schedule II - Leetcode 210.java new file mode 100644 index 0000000..64397a6 --- /dev/null +++ b/Course Schedule II - Leetcode 210/Course Schedule II - Leetcode 210.java @@ -0,0 +1,35 @@ +class Solution { + public int[] findOrder(int numCourses, int[][] prerequisites) { + int[] order = new int[numCourses]; + int[] inDegree = new int[numCourses]; + Map> map = new HashMap<>(); + Queue queue = new LinkedList<>(); + // Initialize the graph + for (int[] pre : prerequisites) { + int target = pre[0], preCourse = pre[1]; + map.computeIfAbsent(preCourse, k -> new ArrayList<>()).add(target); + inDegree[target] += 1; + } + // Find all courses with no prerequisites + for (int i = 0; i < numCourses; ++i) { + if (inDegree[i] == 0) { + queue.offer(i); + } + } + int index = 0; + while (!queue.isEmpty()) { + int node = queue.poll(); + order[index++] = node; + + if (map.containsKey(node)) { + for (int target : map.get(node)) { + inDegree[target] -= 1; + if (inDegree[target] == 0) { + queue.offer(target); + } + } + } + } + return index == numCourses ? order : new int[0]; + } +} \ No newline at end of file diff --git a/Course Schedule II - Leetcode 210/Course Schedule II - Leetcode 210.js b/Course Schedule II - Leetcode 210/Course Schedule II - Leetcode 210.js new file mode 100644 index 0000000..2bcd858 --- /dev/null +++ b/Course Schedule II - Leetcode 210/Course Schedule II - Leetcode 210.js @@ -0,0 +1,29 @@ +var findOrder = function (numCourses, prerequisites) { + const order = [], queue = [] + const inDegree = new Array(numCourses).fill(0) + const map = new Map() + for (let [target, pre] of prerequisites) { + map.has(pre) ? map.get(pre).push(target) : map.set(pre, [target]) + inDegree[target] += 1 + } + console.log(map) + for (let i = 0; i < numCourses; i++) { + if (inDegree[i] == 0) { + queue.push(i) + } + } + while (queue.length != 0) { + let node = queue.shift() + order.push(node) + console.log(node, map.get(node)) + if (map.has(node)) { + for (let tar of map.get(node)) { + inDegree[tar] -= 1 + if (inDegree[tar] == 0) { + queue.push(tar) + } + } + } + } + return order.length==numCourses?order:[] +}; \ No newline at end of file diff --git a/Course Schedule II - Leetcode 210.py b/Course Schedule II - Leetcode 210/Course Schedule II - Leetcode 210.py similarity index 99% rename from Course Schedule II - Leetcode 210.py rename to Course Schedule II - Leetcode 210/Course Schedule II - Leetcode 210.py index ed8bfab..cd8d244 100644 --- a/Course Schedule II - Leetcode 210.py +++ b/Course Schedule II - Leetcode 210/Course Schedule II - Leetcode 210.py @@ -7,7 +7,6 @@ def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int UNVISITED, VISITING, VISITED = 0, 1, 2 states = [UNVISITED] * numCourses - def dfs(i): if states[i] == VISITING: diff --git a/Daily Temperatures - Leetcode 739/Daily Temperatures - Leetcode 739.cpp b/Daily Temperatures - Leetcode 739/Daily Temperatures - Leetcode 739.cpp new file mode 100644 index 0000000..1e03bfe --- /dev/null +++ b/Daily Temperatures - Leetcode 739/Daily Temperatures - Leetcode 739.cpp @@ -0,0 +1,22 @@ +#include +#include + +class Solution { +public: + std::vector dailyTemperatures(std::vector& temperatures) { + int n = temperatures.size(); + std::vector answer(n, 0); + std::stack> stk; // pair + + for (int i = 0; i < n; ++i) { + int temp = temperatures[i]; + while (!stk.empty() && stk.top().first < temp) { + auto [stk_temp, stk_index] = stk.top(); + stk.pop(); + answer[stk_index] = i - stk_index; + } + stk.push({temp, i}); + } + return answer; + } +}; diff --git a/Daily Temperatures - Leetcode 739/Daily Temperatures - Leetcode 739.java b/Daily Temperatures - Leetcode 739/Daily Temperatures - Leetcode 739.java new file mode 100644 index 0000000..f01173e --- /dev/null +++ b/Daily Temperatures - Leetcode 739/Daily Temperatures - Leetcode 739.java @@ -0,0 +1,19 @@ +import java.util.*; + +public class Solution { + public int[] dailyTemperatures(int[] temperatures) { + int n = temperatures.length; + int[] answer = new int[n]; + Stack stack = new Stack<>(); + + for (int i = 0; i < n; i++) { + int temp = temperatures[i]; + while (!stack.isEmpty() && stack.peek()[0] < temp) { + int[] prev = stack.pop(); + answer[prev[1]] = i - prev[1]; + } + stack.push(new int[]{temp, i}); + } + return answer; + } +} diff --git a/Daily Temperatures - Leetcode 739/Daily Temperatures - Leetcode 739.js b/Daily Temperatures - Leetcode 739/Daily Temperatures - Leetcode 739.js new file mode 100644 index 0000000..5972b78 --- /dev/null +++ b/Daily Temperatures - Leetcode 739/Daily Temperatures - Leetcode 739.js @@ -0,0 +1,23 @@ +/** + * @param {number[]} temperatures + * @return {number[]} + */ +var dailyTemperatures = function(temperatures) { + const n = temperatures.length; + const answer = new Array(n).fill(0); + const stk = []; + + for (let i = 0; i < n; i++) { + const t = temperatures[i]; + while (stk.length > 0 && stk[stk.length - 1][0] < t) { + const [stkT, stkI] = stk.pop(); + answer[stkI] = i - stkI; + } + stk.push([t, i]); + } + + return answer; +}; + +// Time Complexity: O(n) +// Space Complexity: O(n) diff --git a/Daily Temperatures - Leetcode 739.py b/Daily Temperatures - Leetcode 739/Daily Temperatures - Leetcode 739.py similarity index 100% rename from Daily Temperatures - Leetcode 739.py rename to Daily Temperatures - Leetcode 739/Daily Temperatures - Leetcode 739.py diff --git a/Diameter of Binary Tree - Leetcode 543/Diameter of Binary Tree - Leetcode 543.cpp b/Diameter of Binary Tree - Leetcode 543/Diameter of Binary Tree - Leetcode 543.cpp new file mode 100644 index 0000000..8eab733 --- /dev/null +++ b/Diameter of Binary Tree - Leetcode 543/Diameter of Binary Tree - Leetcode 543.cpp @@ -0,0 +1,37 @@ +#include // For std::max +using namespace std; + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +class Solution { +public: + int diameterOfBinaryTree(TreeNode* root) { + int largestDiameter = 0; + height(root, largestDiameter); + return largestDiameter; + } + +private: + int height(TreeNode* node, int& largestDiameter) { + if (!node) return 0; + + int leftHeight = height(node->left, largestDiameter); + int rightHeight = height(node->right, largestDiameter); + int diameter = leftHeight + rightHeight; + + largestDiameter = max(largestDiameter, diameter); + + return 1 + max(leftHeight, rightHeight); + } +}; + +// Time Complexity: O(n) +// Space Complexity: O(h) // "h" is the height of the tree diff --git a/Diameter of Binary Tree - Leetcode 543/Diameter of Binary Tree - Leetcode 543.java b/Diameter of Binary Tree - Leetcode 543/Diameter of Binary Tree - Leetcode 543.java new file mode 100644 index 0000000..5b95702 --- /dev/null +++ b/Diameter of Binary Tree - Leetcode 543/Diameter of Binary Tree - Leetcode 543.java @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ + + public class Solution { + private int largestDiameter = 0; + + public int diameterOfBinaryTree(TreeNode root) { + height(root); + return largestDiameter; + } + + private int height(TreeNode node) { + if (node == null) return 0; + + int leftHeight = height(node.left); + int rightHeight = height(node.right); + int diameter = leftHeight + rightHeight; + + largestDiameter = Math.max(largestDiameter, diameter); + + return 1 + Math.max(leftHeight, rightHeight); + } +} + +// Time Complexity: O(n) +// Space Complexity: O(h) // "h" is the height of the tree diff --git a/Diameter of Binary Tree - Leetcode 543/Diameter of Binary Tree - Leetcode 543.js b/Diameter of Binary Tree - Leetcode 543/Diameter of Binary Tree - Leetcode 543.js new file mode 100644 index 0000000..2d3ff41 --- /dev/null +++ b/Diameter of Binary Tree - Leetcode 543/Diameter of Binary Tree - Leetcode 543.js @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val); + * this.left = (left===undefined ? null : left); + * this.right = (right===undefined ? null : right); + * } + */ + +/** + * @param {TreeNode} root + * @return {number} + */ +var diameterOfBinaryTree = function(root) { + let largestDiameter = 0; + + function height(node) { + if (!node) return 0; + + const leftHeight = height(node.left); + const rightHeight = height(node.right); + const diameter = leftHeight + rightHeight; + + largestDiameter = Math.max(largestDiameter, diameter); + + return 1 + Math.max(leftHeight, rightHeight); + } + + height(root); + return largestDiameter; +}; + +// Time Complexity: O(n) +// Space Complexity: O(h) // "h" is the height of the tree diff --git a/Diameter of Binary Tree - Leetcode 543.py b/Diameter of Binary Tree - Leetcode 543/Diameter of Binary Tree - Leetcode 543.py similarity index 100% rename from Diameter of Binary Tree - Leetcode 543.py rename to Diameter of Binary Tree - Leetcode 543/Diameter of Binary Tree - Leetcode 543.py diff --git a/Evaluate Reverse Polish Notation (RPN) - Leetcode 150/Evaluate Reverse Polish Notation (RPN) - Leetcode 150.cpp b/Evaluate Reverse Polish Notation (RPN) - Leetcode 150/Evaluate Reverse Polish Notation (RPN) - Leetcode 150.cpp new file mode 100644 index 0000000..6e2639a --- /dev/null +++ b/Evaluate Reverse Polish Notation (RPN) - Leetcode 150/Evaluate Reverse Polish Notation (RPN) - Leetcode 150.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include // For std::ceil and std::floor +using namespace std; + +/** + * @param tokens: A vector of strings representing the RPN expression + * @return: The result of the RPN expression + */ +class Solution { +public: + int evalRPN(vector& tokens) { + stack stk; + + for (const auto& t : tokens) { + if (t == "+" || t == "-" || t == "*" || t == "/") { + int b = stk.top(); stk.pop(); + int a = stk.top(); stk.pop(); + + if (t == "+") stk.push(a + b); + else if (t == "-") stk.push(a - b); + else if (t == "*") stk.push(a * b); + else { + double division = static_cast(a) / b; + stk.push(division < 0 ? static_cast(ceil(division)) : static_cast(floor(division))); + } + } else { + stk.push(stoi(t)); + } + } + + return stk.top(); + } +}; + +// Time Complexity: O(n) +// Space Complexity: O(n) diff --git a/Evaluate Reverse Polish Notation (RPN) - Leetcode 150/Evaluate Reverse Polish Notation (RPN) - Leetcode 150.java b/Evaluate Reverse Polish Notation (RPN) - Leetcode 150/Evaluate Reverse Polish Notation (RPN) - Leetcode 150.java new file mode 100644 index 0000000..c056fdc --- /dev/null +++ b/Evaluate Reverse Polish Notation (RPN) - Leetcode 150/Evaluate Reverse Polish Notation (RPN) - Leetcode 150.java @@ -0,0 +1,37 @@ +import java.util.Stack; + +public class Solution { + public int evalRPN(String[] tokens) { + Stack stack = new Stack<>(); + + for (String token : tokens) { + if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) { + int b = stack.pop(); + int a = stack.pop(); + + switch (token) { + case "+": + stack.push(a + b); + break; + case "-": + stack.push(a - b); + break; + case "*": + stack.push(a * b); + break; + case "/": + double division = (double) a / b; + stack.push(division < 0 ? (int) Math.ceil(division) : (int) Math.floor(division)); + break; + } + } else { + stack.push(Integer.parseInt(token)); + } + } + + return stack.pop(); + } +} + +// Time Complexity: O(n) +// Space Complexity: O(n) diff --git a/Evaluate Reverse Polish Notation (RPN) - Leetcode 150/Evaluate Reverse Polish Notation (RPN) - Leetcode 150.js b/Evaluate Reverse Polish Notation (RPN) - Leetcode 150/Evaluate Reverse Polish Notation (RPN) - Leetcode 150.js new file mode 100644 index 0000000..2b59702 --- /dev/null +++ b/Evaluate Reverse Polish Notation (RPN) - Leetcode 150/Evaluate Reverse Polish Notation (RPN) - Leetcode 150.js @@ -0,0 +1,37 @@ +/** + * @param {string[]} tokens + * @return {number} + */ +var evalRPN = function(tokens) { + let stack = []; + + for (let token of tokens) { + if (token === '+' || token === '-' || token === '*' || token === '/') { + let b = stack.pop(); + let a = stack.pop(); + + switch (token) { + case '+': + stack.push(a + b); + break; + case '-': + stack.push(a - b); + break; + case '*': + stack.push(a * b); + break; + case '/': + let division = a / b; + stack.push(division < 0 ? Math.ceil(division) : Math.floor(division)); + break; + } + } else { + stack.push(parseInt(token)); + } + } + + return stack[0]; +}; + +// Time Complexity: O(n) +// Space Complexity: O(n) diff --git a/Evaluate Reverse Polish Notation (RPN) - Leetcode 150.py b/Evaluate Reverse Polish Notation (RPN) - Leetcode 150/Evaluate Reverse Polish Notation (RPN) - Leetcode 150.py similarity index 100% rename from Evaluate Reverse Polish Notation (RPN) - Leetcode 150.py rename to Evaluate Reverse Polish Notation (RPN) - Leetcode 150/Evaluate Reverse Polish Notation (RPN) - Leetcode 150.py diff --git a/Fibonacci Number - Leetcode 509/Fibonacci Number - Leetcode 509.cpp b/Fibonacci Number - Leetcode 509/Fibonacci Number - Leetcode 509.cpp new file mode 100644 index 0000000..2996704 --- /dev/null +++ b/Fibonacci Number - Leetcode 509/Fibonacci Number - Leetcode 509.cpp @@ -0,0 +1,86 @@ +class Solution { +public: + int fib(int n) { + if (n == 0) return 0; + if (n == 1) return 1; + return fib(n - 1) + fib(n - 2); + } + + // Time: O(2^n) + // Space: O(n) + // Naive Recursive Solution +}; + + + + +#include + +class Solution { + std::unordered_map memo; +public: + int fib(int n) { + if (n == 0) return 0; + if (n == 1) return 1; + if (memo.count(n)) return memo[n]; + memo[n] = fib(n - 1) + fib(n - 2); + return memo[n]; + } + + // Time: O(n) + // Space: O(n) + // Top Down DP With Memoization +}; + + + + +class Solution { +public: + int fib(int n) { + if (n == 0) return 0; + if (n == 1) return 1; + + std::vector dp(n + 1); + dp[0] = 0; + dp[1] = 1; + + for (int i = 2; i <= n; ++i) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; + } + + // Time: O(n) + // Space: O(n) + // Bottom Up DP With Tabulation +}; + + + +class Solution { +public: + int fib(int n) { + if (n == 0) return 0; + if (n == 1) return 1; + + int prev = 0; + int cur = 1; + + for (int i = 2; i <= n; ++i) { + int next = prev + cur; + prev = cur; + cur = next; + } + + return cur; + } + + // Time: O(n) + // Space: O(1) + // Bottom Up DP With Constant Space +}; + + + diff --git a/Fibonacci Number - Leetcode 509/Fibonacci Number - Leetcode 509.java b/Fibonacci Number - Leetcode 509/Fibonacci Number - Leetcode 509.java new file mode 100644 index 0000000..c0ff195 --- /dev/null +++ b/Fibonacci Number - Leetcode 509/Fibonacci Number - Leetcode 509.java @@ -0,0 +1,92 @@ +public class Solution { + public int fib(int n) { + if (n == 0) { + return 0; + } else if (n == 1) { + return 1; + } else { + return fib(n - 1) + fib(n - 2); + } + } + // Naive Recursive Solution + // Time: O(2^n) + // Space: O(n) + +} + + +import java.util.HashMap; +import java.util.Map; + +public class Solution { + private Map memo = new HashMap<>(); + + public int fib(int n) { + if (n == 0) { + return 0; + } else if (n == 1) { + return 1; + } + + if (memo.containsKey(n)) { + return memo.get(n); + } + + int result = fib(n - 1) + fib(n - 2); + memo.put(n, result); + return result; + } + + // Top Down DP With Memoization + // Time: O(n) + // Space: O(n) +} + + +public class Solution { + public int fib(int n) { + if (n == 0) { + return 0; + } else if (n == 1) { + return 1; + } + + int[] dp = new int[n + 1]; + dp[0] = 0; + dp[1] = 1; + + for (int i = 2; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; + } + // Bottom Up DP With Tabulation + // Time: O(n) + // Space: O(n) +} + + +public class Solution { + public int fib(int n) { + if (n == 0) { + return 0; + } else if (n == 1) { + return 1; + } + + int prev = 0; + int cur = 1; + + for (int i = 2; i <= n; i++) { + int next = prev + cur; + prev = cur; + cur = next; + } + + return cur; + } + // Bottom Up DP With Constant Space + // Time: O(n) + // Space: O(1) +} diff --git a/Fibonacci Number - Leetcode 509/Fibonacci Number - Leetcode 509.js b/Fibonacci Number - Leetcode 509/Fibonacci Number - Leetcode 509.js new file mode 100644 index 0000000..ba095ca --- /dev/null +++ b/Fibonacci Number - Leetcode 509/Fibonacci Number - Leetcode 509.js @@ -0,0 +1,65 @@ +var fib = function(n) { + if (n === 0) return 0; + if (n === 1) return 1; + return fib(n - 1) + fib(n - 2); +}; + +// Naive Recursive Solution +// Time: O(2^n) +// Space: O(n) + + + +var fib = function(n) { + const memo = {}; + + const helper = (x) => { + if (x === 0) return 0; + if (x === 1) return 1; + if (memo[x]) return memo[x]; + memo[x] = helper(x - 1) + helper(x - 2); + return memo[x]; + }; + + return helper(n); +}; +// Top Down DP with Memoization +// Time: O(n) +// Space: O(n) + + + +var fib = function(n) { + if (n === 0) return 0; + if (n === 1) return 1; + + const dp = [0, 1]; + for (let i = 2; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; +}; +// Bottom Up DP With Tabulation +// Time: O(n) +// Space: O(n) + + + +var fib = function(n) { + if (n === 0) return 0; + if (n === 1) return 1; + + let prev = 0, cur = 1; + for (let i = 2; i <= n; i++) { + let next = prev + cur; + prev = cur; + cur = next; + } + + return cur; +}; +// Bottom Up DP With Constant Space +// Time: O(n) +// Space: O(1) + diff --git a/Fibonacci Number - Leetcode 509.py b/Fibonacci Number - Leetcode 509/Fibonacci Number - Leetcode 509.py similarity index 100% rename from Fibonacci Number - Leetcode 509.py rename to Fibonacci Number - Leetcode 509/Fibonacci Number - Leetcode 509.py diff --git a/Find Closest Number to Zero - Leetcode 2239/Find Closest Number to Zero - Leetcode 2239.cpp b/Find Closest Number to Zero - Leetcode 2239/Find Closest Number to Zero - Leetcode 2239.cpp new file mode 100644 index 0000000..13dfe62 --- /dev/null +++ b/Find Closest Number to Zero - Leetcode 2239/Find Closest Number to Zero - Leetcode 2239.cpp @@ -0,0 +1,22 @@ +#include +#include +#include + +class Solution { +public: + int findClosestNumber(const std::vector& nums) { + int closest = nums[0]; + + for (int x : nums) { + if (std::abs(x) < std::abs(closest)) { + closest = x; + } + } + + if (closest < 0 && std::find(nums.begin(), nums.end(), std::abs(closest)) != nums.end()) { + return std::abs(closest); + } else { + return closest; + } + } +}; diff --git a/Find Closest Number to Zero - Leetcode 2239/Find Closest Number to Zero - Leetcode 2239.java b/Find Closest Number to Zero - Leetcode 2239/Find Closest Number to Zero - Leetcode 2239.java new file mode 100644 index 0000000..f3a72f9 --- /dev/null +++ b/Find Closest Number to Zero - Leetcode 2239/Find Closest Number to Zero - Leetcode 2239.java @@ -0,0 +1,29 @@ +import java.util.HashSet; +import java.util.Set; + +public class Solution { + public int findClosestNumber(int[] nums) { + int closest = nums[0]; + + for (int x : nums) { + if (Math.abs(x) < Math.abs(closest)) { + closest = x; + } + } + + if (closest < 0 && contains(nums, Math.abs(closest))) { + return Math.abs(closest); + } else { + return closest; + } + } + + private boolean contains(int[] nums, int value) { + for (int num : nums) { + if (num == value) { + return true; + } + } + return false; + } +} diff --git a/Find Closest Number to Zero - Leetcode 2239/Find Closest Number to Zero - Leetcode 2239.js b/Find Closest Number to Zero - Leetcode 2239/Find Closest Number to Zero - Leetcode 2239.js new file mode 100644 index 0000000..194f1e8 --- /dev/null +++ b/Find Closest Number to Zero - Leetcode 2239/Find Closest Number to Zero - Leetcode 2239.js @@ -0,0 +1,19 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var findClosestNumber = function(nums) { + let closest = nums[0]; + + for (let x of nums) { + if (Math.abs(x) < Math.abs(closest)) { + closest = x; + } + } + + if (closest < 0 && nums.includes(Math.abs(closest))) { + return Math.abs(closest); + } else { + return closest; + } +}; diff --git a/Find Closest Number to Zero - Leetcode 2239/Find Closest Number to Zero - Leetcode 2239.py b/Find Closest Number to Zero - Leetcode 2239/Find Closest Number to Zero - Leetcode 2239.py new file mode 100644 index 0000000..874c2e0 --- /dev/null +++ b/Find Closest Number to Zero - Leetcode 2239/Find Closest Number to Zero - Leetcode 2239.py @@ -0,0 +1,16 @@ +from typing import List + +class Solution: + def findClosestNumber(self, nums: List[int]) -> int: + closest = nums[0] + for x in nums: + if abs(x) < abs(closest): + closest = x + + if closest < 0 and abs(closest) in nums: + return abs(closest) + else: + return closest + + # Time: O(n) + # Space: O(1) diff --git a/Find Minimum in Rotated Sorted Array - Leetcode 153/Find Minimum in Rotated Sorted Array - Leetcode 153.cpp b/Find Minimum in Rotated Sorted Array - Leetcode 153/Find Minimum in Rotated Sorted Array - Leetcode 153.cpp new file mode 100644 index 0000000..7814970 --- /dev/null +++ b/Find Minimum in Rotated Sorted Array - Leetcode 153/Find Minimum in Rotated Sorted Array - Leetcode 153.cpp @@ -0,0 +1,22 @@ +#include + +class Solution { +public: + int findMin(std::vector& nums) { + int l = 0; + int r = nums.size() - 1; + + while (l < r) { + int m = l + (r - l) / 2; + + if (nums[m] > nums[r]) { + l = m + 1; + } else { + r = m; + } + } + + return nums[l]; + } +}; + diff --git a/Find Minimum in Rotated Sorted Array - Leetcode 153/Find Minimum in Rotated Sorted Array - Leetcode 153.java b/Find Minimum in Rotated Sorted Array - Leetcode 153/Find Minimum in Rotated Sorted Array - Leetcode 153.java new file mode 100644 index 0000000..0283dd7 --- /dev/null +++ b/Find Minimum in Rotated Sorted Array - Leetcode 153/Find Minimum in Rotated Sorted Array - Leetcode 153.java @@ -0,0 +1,18 @@ +class Solution { + public int findMin(int[] nums) { + int l = 0; + int r = nums.length - 1; + + while (l < r) { + int m = l + (r - l) / 2; + + if (nums[m] > nums[r]) { + l = m + 1; + } else { + r = m; + } + } + + return nums[l]; + } +} diff --git a/Find Minimum in Rotated Sorted Array - Leetcode 153/Find Minimum in Rotated Sorted Array - Leetcode 153.js b/Find Minimum in Rotated Sorted Array - Leetcode 153/Find Minimum in Rotated Sorted Array - Leetcode 153.js new file mode 100644 index 0000000..44a1338 --- /dev/null +++ b/Find Minimum in Rotated Sorted Array - Leetcode 153/Find Minimum in Rotated Sorted Array - Leetcode 153.js @@ -0,0 +1,20 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var findMin = function(nums) { + let l = 0; + let r = nums.length - 1; + + while (l < r) { + let m = Math.floor((l + r) / 2); + + if (nums[m] > nums[r]) { + l = m + 1; + } else { + r = m; + } + } + + return nums[l]; +}; diff --git a/Find Minimum in Rotated Sorted Array - Leetcode 153.py b/Find Minimum in Rotated Sorted Array - Leetcode 153/Find Minimum in Rotated Sorted Array - Leetcode 153.py similarity index 57% rename from Find Minimum in Rotated Sorted Array - Leetcode 153.py rename to Find Minimum in Rotated Sorted Array - Leetcode 153/Find Minimum in Rotated Sorted Array - Leetcode 153.py index eb84c44..d95496d 100644 --- a/Find Minimum in Rotated Sorted Array - Leetcode 153.py +++ b/Find Minimum in Rotated Sorted Array - Leetcode 153/Find Minimum in Rotated Sorted Array - Leetcode 153.py @@ -1,3 +1,16 @@ +# Brute Force Solution +class Solution: + def findMin(self, nums: List[int]) -> int: + minn = float('inf') + for num in nums: + if num < minn: + minn = num + return minn + +# Time: O(n) +# Space: O(1) + +# Optimal Solution class Solution: def findMin(self, nums: List[int]) -> int: n = len(nums) diff --git a/Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.cpp b/Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.cpp new file mode 100644 index 0000000..19cbbbd --- /dev/null +++ b/Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.cpp @@ -0,0 +1,119 @@ +// Recursive DFS + +#include +#include +#include + +using namespace std; + +class Solution { +public: + bool validPath(int n, vector>& edges, int source, int destination) { + if (source == destination) return true; + + unordered_map> graph; + for (const auto& edge : edges) { + graph[edge[0]].push_back(edge[1]); + graph[edge[1]].push_back(edge[0]); + } + + unordered_set seen; + seen.insert(source); + + return dfs(source, destination, graph, seen); + } + +private: + bool dfs(int node, int destination, unordered_map>& graph, unordered_set& seen) { + if (node == destination) return true; + + for (int neighbor : graph[node]) { + if (seen.find(neighbor) == seen.end()) { + seen.insert(neighbor); + if (dfs(neighbor, destination, graph, seen)) return true; + } + } + return false; + } +}; + +// Iterative DFS With Stack + +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + bool validPath(int n, vector>& edges, int source, int destination) { + if (source == destination) return true; + + unordered_map> graph; + for (const auto& edge : edges) { + graph[edge[0]].push_back(edge[1]); + graph[edge[1]].push_back(edge[0]); + } + + unordered_set seen; + stack stack; + stack.push(source); + seen.insert(source); + + while (!stack.empty()) { + int node = stack.top(); + stack.pop(); + if (node == destination) return true; + + for (int neighbor : graph[node]) { + if (seen.find(neighbor) == seen.end()) { + seen.insert(neighbor); + stack.push(neighbor); + } + } + } + return false; + } +}; + +// BFS With Queue +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + bool validPath(int n, vector>& edges, int source, int destination) { + if (source == destination) return true; + + unordered_map> graph; + for (const auto& edge : edges) { + graph[edge[0]].push_back(edge[1]); + graph[edge[1]].push_back(edge[0]); + } + + unordered_set seen; + queue queue; + queue.push(source); + seen.insert(source); + + while (!queue.empty()) { + int node = queue.front(); + queue.pop(); + if (node == destination) return true; + + for (int neighbor : graph[node]) { + if (seen.find(neighbor) == seen.end()) { + seen.insert(neighbor); + queue.push(neighbor); + } + } + } + return false; + } +}; diff --git a/Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.java b/Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.java new file mode 100644 index 0000000..3e9a792 --- /dev/null +++ b/Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.java @@ -0,0 +1,97 @@ +// Recurisve DFS + +import java.util.*; + +public class Solution { + public boolean validPath(int n, int[][] edges, int source, int destination) { + if (source == destination) return true; + + Map> graph = new HashMap<>(); + for (int[] edge : edges) { + graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]); + graph.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]); + } + + Set seen = new HashSet<>(); + seen.add(source); + + return dfs(source, destination, graph, seen); + } + + private boolean dfs(int node, int destination, Map> graph, Set seen) { + if (node == destination) return true; + + for (int neighbor : graph.getOrDefault(node, Collections.emptyList())) { + if (!seen.contains(neighbor)) { + seen.add(neighbor); + if (dfs(neighbor, destination, graph, seen)) return true; + } + } + return false; + } +} + + +// Iterative DFS With Stack +import java.util.*; + +public class Solution { + public boolean validPath(int n, int[][] edges, int source, int destination) { + if (source == destination) return true; + + Map> graph = new HashMap<>(); + for (int[] edge : edges) { + graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]); + graph.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]); + } + + Set seen = new HashSet<>(); + Stack stack = new Stack<>(); + stack.push(source); + seen.add(source); + + while (!stack.isEmpty()) { + int node = stack.pop(); + if (node == destination) return true; + for (int neighbor : graph.getOrDefault(node, Collections.emptyList())) { + if (!seen.contains(neighbor)) { + seen.add(neighbor); + stack.push(neighbor); + } + } + } + return false; + } +} + +// BFS With Queue +import java.util.*; + +public class Solution { + public boolean validPath(int n, int[][] edges, int source, int destination) { + if (source == destination) return true; + + Map> graph = new HashMap<>(); + for (int[] edge : edges) { + graph.computeIfAbsent(edge[0], k -> new ArrayList<>()).add(edge[1]); + graph.computeIfAbsent(edge[1], k -> new ArrayList<>()).add(edge[0]); + } + + Set seen = new HashSet<>(); + Queue queue = new LinkedList<>(); + queue.offer(source); + seen.add(source); + + while (!queue.isEmpty()) { + int node = queue.poll(); + if (node == destination) return true; + for (int neighbor : graph.getOrDefault(node, Collections.emptyList())) { + if (!seen.contains(neighbor)) { + seen.add(neighbor); + queue.offer(neighbor); + } + } + } + return false; + } +} diff --git a/Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.js b/Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.js new file mode 100644 index 0000000..2d88478 --- /dev/null +++ b/Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.js @@ -0,0 +1,93 @@ +// Recursive DFS +var validPath = function(n, edges, source, destination) { + if (source === destination) return true; + + const graph = new Map(); + for (const [u, v] of edges) { + if (!graph.has(u)) graph.set(u, []); + if (!graph.has(v)) graph.set(v, []); + graph.get(u).push(v); + graph.get(v).push(u); + } + + const seen = new Set(); + seen.add(source); + + const dfs = (node) => { + if (node === destination) return true; + + for (const neighbor of graph.get(node) || []) { + if (!seen.has(neighbor)) { + seen.add(neighbor); + if (dfs(neighbor)) return true; + } + } + return false; + }; + + return dfs(source); +} + + +// Iterative DFS With Stack +var validPath = function(n, edges, source, destination) { + if (source === destination) return true; + + const graph = new Map(); + for (const [u, v] of edges) { + if (!graph.has(u)) graph.set(u, []); + if (!graph.has(v)) graph.set(v, []); + graph.get(u).push(v); + graph.get(v).push(u); + } + + const seen = new Set(); + const stack = [source]; + seen.add(source); + + while (stack.length > 0) { + const node = stack.pop(); + if (node === destination) return true; + + for (const neighbor of graph.get(node) || []) { + if (!seen.has(neighbor)) { + seen.add(neighbor); + stack.push(neighbor); + } + } + } + + return false; +}; + + +// BFS With Queue +var validPath = function(n, edges, source, destination) { + if (source === destination) return true; + + const graph = new Map(); + for (const [u, v] of edges) { + if (!graph.has(u)) graph.set(u, []); + if (!graph.has(v)) graph.set(v, []); + graph.get(u).push(v); + graph.get(v).push(u); + } + + const seen = new Set(); + const queue = [source]; + seen.add(source); + + while (queue.length > 0) { + const node = queue.shift(); + if (node === destination) return true; + + for (const neighbor of graph.get(node) || []) { + if (!seen.has(neighbor)) { + seen.add(neighbor); + queue.push(neighbor); + } + } + } + + return false; +}; diff --git a/Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.py b/Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.py new file mode 100644 index 0000000..0323bef --- /dev/null +++ b/Find if Path Exists in Graph - Leetcode 1971/Find if Path Exists in Graph - Leetcode 1971.py @@ -0,0 +1,84 @@ +# Recursive DFS +class Solution: + def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: + if source == destination: + return True + + graph = defaultdict(list) + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + seen = set() + seen.add(source) + + def dfs(i): + if i == destination: + return True + + for nei_node in graph[i]: + if nei_node not in seen: + seen.add(nei_node) + if dfs(nei_node): + return True + + return False + + return dfs(source) + + +# Iterative DFS with Stack +class Solution: + def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: + if source == destination: + return True + + graph = defaultdict(list) + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + seen = set() + seen.add(source) + stack = [source] + + while stack: + node = stack.pop() + if node == destination: + return True + for nei_node in graph[node]: + if nei_node not in seen: + seen.add(nei_node) + stack.append(nei_node) + + return False + + + +# BFS With Queue +from collections import deque +class Solution: + def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: + if source == destination: + return True + + graph = defaultdict(list) + for u, v in edges: + graph[u].append(v) + graph[v].append(u) + + seen = set() + seen.add(source) + q = deque() + q.append(source) + + while q: + node = q.popleft() + if node == destination: + return True + for nei_node in graph[node]: + if nei_node not in seen: + seen.add(nei_node) + q.append(nei_node) + + return False # Time: O(N + E), Space: O(N + E) diff --git a/First Bad Version - Leetcode 278/First Bad Version - Leetcode 278.cpp b/First Bad Version - Leetcode 278/First Bad Version - Leetcode 278.cpp new file mode 100644 index 0000000..02e511b --- /dev/null +++ b/First Bad Version - Leetcode 278/First Bad Version - Leetcode 278.cpp @@ -0,0 +1,25 @@ +// The API isBadVersion is defined for you. +// bool isBadVersion(int version); + +class Solution { +public: + int firstBadVersion(int n) { + int i,j,k,c=0; + int h=n,l=0,m; + + while(l<=h) + { + m=l+(h-l)/2; + int res=isBadVersion(m); + if(res==1 and (m==0 or isBadVersion(m-1)!=1)){ + return m; + } + else if(res==0){ + l=m+1; + }else + h=m-1; + } + return m; + + } +}; \ No newline at end of file diff --git a/First Bad Version - Leetcode 278/First Bad Version - Leetcode 278.java b/First Bad Version - Leetcode 278/First Bad Version - Leetcode 278.java new file mode 100644 index 0000000..98ca70f --- /dev/null +++ b/First Bad Version - Leetcode 278/First Bad Version - Leetcode 278.java @@ -0,0 +1,22 @@ +/* The isBadVersion API is defined in the parent class VersionControl. + boolean isBadVersion(int version); */ + + public class Solution extends VersionControl { + public int firstBadVersion(int n) { + if(n==1) return n; + + int start =1; + int end = n; + int badVersion = 1; + while(start <= end){ + int mid = start +(end-start)/2; + if(isBadVersion(mid)){ + badVersion = mid; + end = mid-1; + } + else start=mid+1; + } + return badVersion; + + } + } \ No newline at end of file diff --git a/First Bad Version - Leetcode 278/First Bad Version - Leetcode 278.js b/First Bad Version - Leetcode 278/First Bad Version - Leetcode 278.js new file mode 100644 index 0000000..2d59ba9 --- /dev/null +++ b/First Bad Version - Leetcode 278/First Bad Version - Leetcode 278.js @@ -0,0 +1,15 @@ +var solution = function (isBadVersion) { + + return function (n) { + let low = 1; + let high = n; + let mid; + while (low <= high) { + mid = ~~(low + (high - low) / 2); + if (isBadVersion(mid)) { + if (isBadVersion(mid - 1)) high = mid - 1; + else return mid; + } else low = mid + 1; + } + } +}; \ No newline at end of file diff --git a/First Bad Version - Leetcode 278.py b/First Bad Version - Leetcode 278/First Bad Version - Leetcode 278.py similarity index 52% rename from First Bad Version - Leetcode 278.py rename to First Bad Version - Leetcode 278/First Bad Version - Leetcode 278.py index a215336..c6b9559 100644 --- a/First Bad Version - Leetcode 278.py +++ b/First Bad Version - Leetcode 278/First Bad Version - Leetcode 278.py @@ -1,6 +1,15 @@ +# Brute Force Solution +class Solution: + def firstBadVersion(self, n: int) -> int: + for version in range(1, n+1): + if isBadVersion(version): + return version + # Time: O(n) + # Space: O(1) + +# Optimal Solution # The isBadVersion API is already defined for you. # def isBadVersion(version: int) -> bool: - class Solution: def firstBadVersion(self, n: int) -> int: L = 1 @@ -13,4 +22,6 @@ def firstBadVersion(self, n: int) -> int: else: L = M + 1 - return L # Time: O(Log n), Space: O(1) + return L + # Time: O(Log n) + # Space: O(1) diff --git a/Generate Parentheses - Leetcode 22/Generate Parentheses - Leetcode 22.cpp b/Generate Parentheses - Leetcode 22/Generate Parentheses - Leetcode 22.cpp new file mode 100644 index 0000000..1aab13c --- /dev/null +++ b/Generate Parentheses - Leetcode 22/Generate Parentheses - Leetcode 22.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + vector generateParenthesis(int n) { + vector res; + dfs(0, 0, "", n, res); + return res; + } + +private: + void dfs(int openP, int closeP, string s, int n, vector& res) { + if (openP == closeP && openP + closeP == n * 2) { + res.push_back(s); + return; + } + + if (openP < n) { + dfs(openP + 1, closeP, s + "(", n, res); + } + + if (closeP < openP) { + dfs(openP, closeP + 1, s + ")", n, res); + } + } +}; \ No newline at end of file diff --git a/Generate Parentheses - Leetcode 22/Generate Parentheses - Leetcode 22.java b/Generate Parentheses - Leetcode 22/Generate Parentheses - Leetcode 22.java new file mode 100644 index 0000000..51d8ed7 --- /dev/null +++ b/Generate Parentheses - Leetcode 22/Generate Parentheses - Leetcode 22.java @@ -0,0 +1,24 @@ +class Solution { + public List generateParenthesis(int n) { + List res = new ArrayList<>(); + + dfs(0, 0, "", n, res); + + return res; + } + + private void dfs(int openP, int closeP, String s, int n, List res) { + if (openP == closeP && openP + closeP == n * 2) { + res.add(s); + return; + } + + if (openP < n) { + dfs(openP + 1, closeP, s + "(", n, res); + } + + if (closeP < openP) { + dfs(openP, closeP + 1, s + ")", n, res); + } + } +} \ No newline at end of file diff --git a/Generate Parentheses - Leetcode 22/Generate Parentheses - Leetcode 22.js b/Generate Parentheses - Leetcode 22/Generate Parentheses - Leetcode 22.js new file mode 100644 index 0000000..6e9ba7a --- /dev/null +++ b/Generate Parentheses - Leetcode 22/Generate Parentheses - Leetcode 22.js @@ -0,0 +1,22 @@ +var generateParenthesis = function(n) { + const res = []; + + function dfs(openP, closeP, s) { + if (openP === closeP && openP + closeP === n * 2) { + res.push(s); + return; + } + + if (openP < n) { + dfs(openP + 1, closeP, s + "("); + } + + if (closeP < openP) { + dfs(openP, closeP + 1, s + ")"); + } + } + + dfs(0, 0, ""); + + return res; +}; \ No newline at end of file diff --git a/Generate Parentheses - Leetcode 22.py b/Generate Parentheses - Leetcode 22/Generate Parentheses - Leetcode 22.py similarity index 100% rename from Generate Parentheses - Leetcode 22.py rename to Generate Parentheses - Leetcode 22/Generate Parentheses - Leetcode 22.py diff --git a/Group Anagrams - Leetcode 49/Group Anagrams - Leetcode 49.cpp b/Group Anagrams - Leetcode 49/Group Anagrams - Leetcode 49.cpp new file mode 100644 index 0000000..f656fe6 --- /dev/null +++ b/Group Anagrams - Leetcode 49/Group Anagrams - Leetcode 49.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> anagramsMap; + + for (const string& s : strs) { + string count = getCount(s); + anagramsMap[count].push_back(s); + } + + vector> result; + for (const auto& entry : anagramsMap) { + result.push_back(entry.second); + } + + return result; + } + +private: + string getCount(const string& s) { + vector count(26, 0); + for (char c : s) { + count[c - 'a']++; + } + string countStr; + for (int i : count) { + countStr += to_string(i) + '#'; + } + return countStr; + } +}; diff --git a/Group Anagrams - Leetcode 49/Group Anagrams - Leetcode 49.java b/Group Anagrams - Leetcode 49/Group Anagrams - Leetcode 49.java new file mode 100644 index 0000000..08b3534 --- /dev/null +++ b/Group Anagrams - Leetcode 49/Group Anagrams - Leetcode 49.java @@ -0,0 +1,22 @@ +import java.util.*; + +class Solution { + public List> groupAnagrams(String[] strs) { + Map> anagramsMap = new HashMap<>(); + + for (String s : strs) { + int[] count = new int[26]; + for (char c : s.toCharArray()) { + count[c - 'a']++; + } + StringBuilder key = new StringBuilder(); + for (int num : count) { + key.append('#').append(num); + } + String keyStr = key.toString(); + anagramsMap.computeIfAbsent(keyStr, k -> new ArrayList<>()).add(s); + } + + return new ArrayList<>(anagramsMap.values()); + } +} diff --git a/Group Anagrams - Leetcode 49/Group Anagrams - Leetcode 49.js b/Group Anagrams - Leetcode 49/Group Anagrams - Leetcode 49.js new file mode 100644 index 0000000..a32e5f2 --- /dev/null +++ b/Group Anagrams - Leetcode 49/Group Anagrams - Leetcode 49.js @@ -0,0 +1,21 @@ +/** + * @param {string[]} strs + * @return {string[][]} + */ +var groupAnagrams = function(strs) { + const anagramsMap = new Map(); + + strs.forEach(s => { + const count = new Array(26).fill(0); + for (let c of s) { + count[c.charCodeAt(0) - 'a'.charCodeAt(0)]++; + } + const key = count.join(','); + if (!anagramsMap.has(key)) { + anagramsMap.set(key, []); + } + anagramsMap.get(key).push(s); + }); + + return Array.from(anagramsMap.values()); +}; diff --git a/Group Anagrams - Leetcode 49.py b/Group Anagrams - Leetcode 49/Group Anagrams - Leetcode 49.py similarity index 57% rename from Group Anagrams - Leetcode 49.py rename to Group Anagrams - Leetcode 49/Group Anagrams - Leetcode 49.py index 28e4bda..06af914 100644 --- a/Group Anagrams - Leetcode 49.py +++ b/Group Anagrams - Leetcode 49/Group Anagrams - Leetcode 49.py @@ -1,3 +1,17 @@ +# Brute Force Solution +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + ans = defaultdict(list) + for s in strs: + key = ''.join(sorted(s)) + ans[key].append(s) + + return list(ans.values()) +# Time: O(n * (m log m)) +# Space: O(n * m) +# n is the number of strings, m is the length of largest string + +# Optimal Solution from collections import defaultdict class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: diff --git a/H-Index - Leetcode 274/H-Index - Leetcode 274.cpp b/H-Index - Leetcode 274/H-Index - Leetcode 274.cpp new file mode 100644 index 0000000..68f079e --- /dev/null +++ b/H-Index - Leetcode 274/H-Index - Leetcode 274.cpp @@ -0,0 +1,24 @@ +#include +#include + +class Solution { +public: + int hIndex(std::vector& citations) { + int n = citations.size(); + std::vector paperCounts(n + 1, 0); + + for (int c : citations) { + paperCounts[std::min(n, c)]++; + } + + int h = n; + int papers = paperCounts[n]; + + while (papers < h) { + h--; + papers += paperCounts[h]; + } + + return h; + } +}; diff --git a/H-Index - Leetcode 274/H-Index - Leetcode 274.java b/H-Index - Leetcode 274/H-Index - Leetcode 274.java new file mode 100644 index 0000000..c7848ea --- /dev/null +++ b/H-Index - Leetcode 274/H-Index - Leetcode 274.java @@ -0,0 +1,20 @@ +public class Solution { + public int hIndex(int[] citations) { + int n = citations.length; + int[] paperCounts = new int[n + 1]; + + for (int c : citations) { + paperCounts[Math.min(n, c)]++; + } + + int h = n; + int papers = paperCounts[n]; + + while (papers < h) { + h--; + papers += paperCounts[h]; + } + + return h; + } +} diff --git a/H-Index - Leetcode 274/H-Index - Leetcode 274.js b/H-Index - Leetcode 274/H-Index - Leetcode 274.js new file mode 100644 index 0000000..f6ddc06 --- /dev/null +++ b/H-Index - Leetcode 274/H-Index - Leetcode 274.js @@ -0,0 +1,18 @@ +var hIndex = function(citations) { + var n = citations.length; + var paperCounts = new Array(n + 1).fill(0); + + for (var c of citations) { + paperCounts[Math.min(n, c)]++; + } + + var h = n; + var papers = paperCounts[n]; + + while (papers < h) { + h--; + papers += paperCounts[h]; + } + + return h; +}; diff --git a/H-Index - Leetcode 274/H-Index - Leetcode 274.py b/H-Index - Leetcode 274/H-Index - Leetcode 274.py new file mode 100644 index 0000000..97bb4a7 --- /dev/null +++ b/H-Index - Leetcode 274/H-Index - Leetcode 274.py @@ -0,0 +1,17 @@ +class Solution: + def hIndex(self, citations: List[int]) -> int: + n = len(citations) + paper_counts = [0] * (n+1) + + for c in citations: + paper_counts[min(n, c)] += 1 + + h = n + papers = paper_counts[n] + + while papers < h: + h -= 1 + papers += paper_counts[h] + + return h + # Time: O(n), Space: O(n) \ No newline at end of file diff --git a/House Robber - Leetcode 198/House Robber - Leetcode 198.cpp b/House Robber - Leetcode 198/House Robber - Leetcode 198.cpp new file mode 100644 index 0000000..0675677 --- /dev/null +++ b/House Robber - Leetcode 198/House Robber - Leetcode 198.cpp @@ -0,0 +1,24 @@ +#include +#include + +using namespace std; + +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + if (n == 1) return nums[0]; + if (n == 2) return max(nums[0], nums[1]); + + int prev = nums[0]; + int curr = max(nums[0], nums[1]); + + for (int i = 2; i < n; i++) { + int temp = curr; + curr = max(nums[i] + prev, curr); + prev = temp; + } + + return curr; + } +}; diff --git a/House Robber - Leetcode 198/House Robber - Leetcode 198.java b/House Robber - Leetcode 198/House Robber - Leetcode 198.java new file mode 100644 index 0000000..129bc6d --- /dev/null +++ b/House Robber - Leetcode 198/House Robber - Leetcode 198.java @@ -0,0 +1,18 @@ +class Solution { + public int rob(int[] nums) { + int n = nums.length; + if (n == 1) return nums[0]; + if (n == 2) return Math.max(nums[0], nums[1]); + + int prev = nums[0]; + int curr = Math.max(nums[0], nums[1]); + + for (int i = 2; i < n; i++) { + int temp = curr; + curr = Math.max(nums[i] + prev, curr); + prev = temp; + } + + return curr; + } +} diff --git a/House Robber - Leetcode 198/House Robber - Leetcode 198.js b/House Robber - Leetcode 198/House Robber - Leetcode 198.js new file mode 100644 index 0000000..12d4724 --- /dev/null +++ b/House Robber - Leetcode 198/House Robber - Leetcode 198.js @@ -0,0 +1,16 @@ +var rob = function(nums) { + const n = nums.length; + if (n === 1) return nums[0]; + if (n === 2) return Math.max(nums[0], nums[1]); + + let prev = nums[0]; + let curr = Math.max(nums[0], nums[1]); + + for (let i = 2; i < n; i++) { + const temp = curr; + curr = Math.max(nums[i] + prev, curr); + prev = temp; + } + + return curr; +}; diff --git a/House Robber - Leetcode 198/House Robber - Leetcode 198.py b/House Robber - Leetcode 198/House Robber - Leetcode 198.py new file mode 100644 index 0000000..81e6426 --- /dev/null +++ b/House Robber - Leetcode 198/House Robber - Leetcode 198.py @@ -0,0 +1,81 @@ +# Recursive Solution +class Solution: + def rob(self, nums: List[int]) -> int: + n = len(nums) + + def helper(i): + if i == 0: + return nums[0] + if i == 1: + return max(nums[0], nums[1]) + + return max(nums[i] + helper(i-2), + helper(i-1)) + + return helper(n-1) + # Time: O(2^n) + # Space: O(n) + + +# Top Down DP (Memoization) +class Solution: + def rob(self, nums: List[int]) -> int: + n = len(nums) + if n == 1: + return nums[0] + if n == 2: + return max(nums[0], nums[1]) + + memo = {0:nums[0], 1:max(nums[0], nums[1])} + + def helper(i): + if i in memo: + return memo[i] + else: + memo[i] = max(nums[i] + helper(i-2), + helper(i-1)) + return memo[i] + + return helper(n-1) + # Time: O(n) + # Space: O(n) + + + +# Bottom Up DP (Tabulation) +class Solution: + def rob(self, nums: List[int]) -> int: + n = len(nums) + if n == 1: + return nums[0] + if n == 2: + return max(nums[0], nums[1]) + + dp = [0] * n + dp[0] = nums[0] + dp[1] = max(nums[0], nums[1]) + for i in range(2, n): + dp[i] = max(nums[i] + dp[i-2], dp[i-1]) + + return dp[n-1] + # Time: O(n) + # Space: O(n) + + +# Bottom Up DP (Constant Space) +class Solution: + def rob(self, nums: List[int]) -> int: + n = len(nums) + if n == 1: + return nums[0] + if n == 2: + return max(nums[0], nums[1]) + + prev = nums[0] + curr = max(nums[0], nums[1]) + for i in range(2, n): + prev, curr = curr, max(nums[i] + prev, curr) + + return curr + # Time: O(n) + # Space: O(1) diff --git a/Implement Trie (Prefix Tree) - Leetcode 208/Implement Trie (Prefix Tree) - Leetcode 208.cpp b/Implement Trie (Prefix Tree) - Leetcode 208/Implement Trie (Prefix Tree) - Leetcode 208.cpp new file mode 100644 index 0000000..ddc1c1b --- /dev/null +++ b/Implement Trie (Prefix Tree) - Leetcode 208/Implement Trie (Prefix Tree) - Leetcode 208.cpp @@ -0,0 +1,49 @@ +#include +#include +using namespace std; + +class Trie { +public: + Trie() : root(new TrieNode()) {} + + void insert(string word) { + TrieNode* node = root; + for (char c : word) { + if (node->children.find(c) == node->children.end()) { + node->children[c] = new TrieNode(); + } + node = node->children[c]; + } + node->isEndOfWord = true; + } + + bool search(string word) { + TrieNode* node = root; + for (char c : word) { + if (node->children.find(c) == node->children.end()) { + return false; + } + node = node->children[c]; + } + return node->isEndOfWord; + } + + bool startsWith(string prefix) { + TrieNode* node = root; + for (char c : prefix) { + if (node->children.find(c) == node->children.end()) { + return false; + } + node = node->children[c]; + } + return true; + } + +private: + struct TrieNode { + unordered_map children; + bool isEndOfWord = false; + }; + + TrieNode* root; +}; diff --git a/Implement Trie (Prefix Tree) - Leetcode 208/Implement Trie (Prefix Tree) - Leetcode 208.java b/Implement Trie (Prefix Tree) - Leetcode 208/Implement Trie (Prefix Tree) - Leetcode 208.java new file mode 100644 index 0000000..d8c94fa --- /dev/null +++ b/Implement Trie (Prefix Tree) - Leetcode 208/Implement Trie (Prefix Tree) - Leetcode 208.java @@ -0,0 +1,51 @@ +import java.util.HashMap; +import java.util.Map; + +class Trie { + + private class TrieNode { + Map children = new HashMap<>(); + boolean isEndOfWord = false; + } + + private TrieNode root; + + /** Initialize your data structure here. */ + public Trie() { + root = new TrieNode(); + } + + /** Inserts a word into the trie. */ + public void insert(String word) { + TrieNode node = root; + for (char c : word.toCharArray()) { + node.children.putIfAbsent(c, new TrieNode()); + node = node.children.get(c); + } + node.isEndOfWord = true; + } + + /** Returns if the word is in the trie. */ + public boolean search(String word) { + TrieNode node = root; + for (char c : word.toCharArray()) { + if (!node.children.containsKey(c)) { + return false; + } + node = node.children.get(c); + } + return node.isEndOfWord; + } + + /** Returns if there is any word in the trie that starts with the given prefix. */ + public boolean startsWith(String prefix) { + TrieNode node = root; + for (char c : prefix.toCharArray()) { + if (!node.children.containsKey(c)) { + return false; + } + node = node.children.get(c); + } + return true; + } +} diff --git a/Implement Trie (Prefix Tree) - Leetcode 208/Implement Trie (Prefix Tree) - Leetcode 208.js b/Implement Trie (Prefix Tree) - Leetcode 208/Implement Trie (Prefix Tree) - Leetcode 208.js new file mode 100644 index 0000000..22d99da --- /dev/null +++ b/Implement Trie (Prefix Tree) - Leetcode 208/Implement Trie (Prefix Tree) - Leetcode 208.js @@ -0,0 +1,45 @@ +class TrieNode { + constructor() { + this.children = {}; + this.isEndOfWord = false; + } +} + +class Trie { + constructor() { + this.root = new TrieNode(); + } + + insert(word) { + let node = this.root; + for (let char of word) { + if (!node.children[char]) { + node.children[char] = new TrieNode(); + } + node = node.children[char]; + } + node.isEndOfWord = true; + } + + search(word) { + let node = this.root; + for (let char of word) { + if (!node.children[char]) { + return false; + } + node = node.children[char]; + } + return node.isEndOfWord; + } + + startsWith(prefix) { + let node = this.root; + for (let char of prefix) { + if (!node.children[char]) { + return false; + } + node = node.children[char]; + } + return true; + } +} diff --git a/Implement Trie (Prefix Tree) - Leetcode 208/Implement Trie (Prefix Tree) - Leetcode 208.py b/Implement Trie (Prefix Tree) - Leetcode 208/Implement Trie (Prefix Tree) - Leetcode 208.py new file mode 100644 index 0000000..4c2280e --- /dev/null +++ b/Implement Trie (Prefix Tree) - Leetcode 208/Implement Trie (Prefix Tree) - Leetcode 208.py @@ -0,0 +1,36 @@ +class Trie: + def __init__(self): + self.trie = {} + + def insert(self, word: str) -> None: + d = self.trie + + for c in word: + if c not in d: + d[c] = {} + d = d[c] + + d['.'] = '.' + + def search(self, word: str) -> bool: + d = self.trie + + for c in word: + if c not in d: + return False + d = d[c] + + return '.' in d + + def startsWith(self, prefix: str) -> bool: + d = self.trie + + for c in prefix: + if c not in d: + return False + d = d[c] + + return True + + # Time: O(N) where N is the length of any string + # Space: O(T) where T is the total number of stored characters diff --git a/Insert GCDs in Linked List - Leetcode 2807/Insert GCDs in Linked List - Leetcode 2807.cpp b/Insert GCDs in Linked List - Leetcode 2807/Insert GCDs in Linked List - Leetcode 2807.cpp new file mode 100644 index 0000000..1c5577f --- /dev/null +++ b/Insert GCDs in Linked List - Leetcode 2807/Insert GCDs in Linked List - Leetcode 2807.cpp @@ -0,0 +1,20 @@ +#include // for std::gcd + +class Solution { +public: + ListNode* insertGreatestCommonDivisors(ListNode* head) { + ListNode* prev = head; + ListNode* cur = head->next; + + while (cur != nullptr) { + int gcd = std::gcd(cur->val, prev->val); // A + ListNode* g = new ListNode(gcd); + prev->next = g; + g->next = cur; + prev = cur; + cur = cur->next; + } + + return head; + } +}; diff --git a/Insert GCDs in Linked List - Leetcode 2807/Insert GCDs in Linked List - Leetcode 2807.java b/Insert GCDs in Linked List - Leetcode 2807/Insert GCDs in Linked List - Leetcode 2807.java new file mode 100644 index 0000000..0be18a1 --- /dev/null +++ b/Insert GCDs in Linked List - Leetcode 2807/Insert GCDs in Linked List - Leetcode 2807.java @@ -0,0 +1,23 @@ +import java.math.BigInteger; + +public class Solution { + public ListNode insertGreatestCommonDivisors(ListNode head) { + ListNode prev = head; + ListNode cur = head.next; + + while (cur != null) { + int gcd = gcd(cur.val, prev.val); // A + ListNode g = new ListNode(gcd); + prev.next = g; + g.next = cur; + prev = cur; + cur = cur.next; + } + + return head; + } + + private int gcd(int a, int b) { + return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).intValue(); + } +} diff --git a/Insert GCDs in Linked List - Leetcode 2807/Insert GCDs in Linked List - Leetcode 2807.js b/Insert GCDs in Linked List - Leetcode 2807/Insert GCDs in Linked List - Leetcode 2807.js new file mode 100644 index 0000000..8387fc2 --- /dev/null +++ b/Insert GCDs in Linked List - Leetcode 2807/Insert GCDs in Linked List - Leetcode 2807.js @@ -0,0 +1,31 @@ +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var insertGreatestCommonDivisors = function(head) { + let current = head + while(current.next){ + let next = current.next + let hcf = gcd(current.val,next.val) + let node = new ListNode(hcf,next) + current.next = node; + current = next + } + return head +}; + +let gcd = function(num1,num2){ + let smaller = Math.min(num1,num2) + let hcf = 1 + for(let i = 1 ;i<=smaller;i++){ + if(num1%i == 0 && num2%i == 0) hcf = i + } + return hcf +} \ No newline at end of file diff --git a/Insert GCDs in Linked List - Leetcode 2807.py b/Insert GCDs in Linked List - Leetcode 2807/Insert GCDs in Linked List - Leetcode 2807.py similarity index 100% rename from Insert GCDs in Linked List - Leetcode 2807.py rename to Insert GCDs in Linked List - Leetcode 2807/Insert GCDs in Linked List - Leetcode 2807.py diff --git a/Invert Binary Tree - Leetcode 226.py b/Invert Binary Tree - Leetcode 226.py deleted file mode 100644 index a6ea203..0000000 --- a/Invert Binary Tree - Leetcode 226.py +++ /dev/null @@ -1,15 +0,0 @@ -class Solution: - def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: - - if not root: - return None - - root.left, root.right = root.right, root.left - - self.invertTree(root.left) - self.invertTree(root.right) - - return root - -# Time Complexity: O(n) -# Space Complexity: O(h) { here "h" is the height of the tree } diff --git a/Invert Binary Tree - Leetcode 226/Invert Binary Tree - Leetcode 226.cpp b/Invert Binary Tree - Leetcode 226/Invert Binary Tree - Leetcode 226.cpp new file mode 100644 index 0000000..a4a9bd6 --- /dev/null +++ b/Invert Binary Tree - Leetcode 226/Invert Binary Tree - Leetcode 226.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + TreeNode* invertTree(TreeNode* root) { + if (root == nullptr) { + return nullptr; + } + + TreeNode* temp = root->left; + root->left = root->right; + root->right = temp; + + invertTree(root->left); + invertTree(root->right); + + return root; + } +}; \ No newline at end of file diff --git a/Invert Binary Tree - Leetcode 226/Invert Binary Tree - Leetcode 226.java b/Invert Binary Tree - Leetcode 226/Invert Binary Tree - Leetcode 226.java new file mode 100644 index 0000000..620f9c0 --- /dev/null +++ b/Invert Binary Tree - Leetcode 226/Invert Binary Tree - Leetcode 226.java @@ -0,0 +1,16 @@ +class Solution { + public TreeNode invertTree(TreeNode root) { + if (root == null) { + return null; + } + + TreeNode temp = root.left; + root.left = root.right; + root.right = temp; + + invertTree(root.left); + invertTree(root.right); + + return root; + } +} \ No newline at end of file diff --git a/Invert Binary Tree - Leetcode 226/Invert Binary Tree - Leetcode 226.js b/Invert Binary Tree - Leetcode 226/Invert Binary Tree - Leetcode 226.js new file mode 100644 index 0000000..e895616 --- /dev/null +++ b/Invert Binary Tree - Leetcode 226/Invert Binary Tree - Leetcode 226.js @@ -0,0 +1,14 @@ +var invertTree = function(root) { + if (root === null) { + return null; + } + + const temp = root.left; + root.left = root.right; + root.right = temp; + + invertTree(root.left); + invertTree(root.right); + + return root; +}; \ No newline at end of file diff --git a/Invert Binary Tree - Leetcode 226/Invert Binary Tree - Leetcode 226.py b/Invert Binary Tree - Leetcode 226/Invert Binary Tree - Leetcode 226.py new file mode 100644 index 0000000..1cc0217 --- /dev/null +++ b/Invert Binary Tree - Leetcode 226/Invert Binary Tree - Leetcode 226.py @@ -0,0 +1,34 @@ +# YouTube Solution +class Solution: + def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + + if not root: + return None + + root.left, root.right = root.right, root.left + + self.invertTree(root.left) + self.invertTree(root.right) + + return root + +# Time Complexity: O(n) +# Space Complexity: O(h) { here "h" is the height of the tree } + + +# Solution for Bootcamp +class Solution: + def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + def invert(node): + if not node: + return + + node.left, node.right = node.right, node.left + invert(node.left) + invert(node.right) + + invert(root) + return root + +# Time Complexity: O(n) +# Space Complexity: O(h) { here "h" is the height of the tree } diff --git a/Is Subsequence - Leetcode 392/Is Subsequence - Leetcode 392.cpp b/Is Subsequence - Leetcode 392/Is Subsequence - Leetcode 392.cpp new file mode 100644 index 0000000..43ea4b5 --- /dev/null +++ b/Is Subsequence - Leetcode 392/Is Subsequence - Leetcode 392.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + bool isSubsequence(string s, string t) { + int sp = 0; + int tp = 0; + + while (sp < s.length() && tp < t.length()) { + if (s[sp] == t[tp]) { + sp++; + } + tp++; + } + + return sp == s.length(); + } +}; \ No newline at end of file diff --git a/Is Subsequence - Leetcode 392/Is Subsequence - Leetcode 392.java b/Is Subsequence - Leetcode 392/Is Subsequence - Leetcode 392.java new file mode 100644 index 0000000..d660a74 --- /dev/null +++ b/Is Subsequence - Leetcode 392/Is Subsequence - Leetcode 392.java @@ -0,0 +1,15 @@ +class Solution { + public boolean isSubsequence(String s, String t) { + int sp = 0; + int tp = 0; + + while (sp < s.length() && tp < t.length()) { + if (s.charAt(sp) == t.charAt(tp)) { + sp++; + } + tp++; + } + + return sp == s.length(); + } +} \ No newline at end of file diff --git a/Is Subsequence - Leetcode 392/Is Subsequence - Leetcode 392.js b/Is Subsequence - Leetcode 392/Is Subsequence - Leetcode 392.js new file mode 100644 index 0000000..3dcac7e --- /dev/null +++ b/Is Subsequence - Leetcode 392/Is Subsequence - Leetcode 392.js @@ -0,0 +1,18 @@ +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isSubsequence = function(s, t) { + let sp = 0; + let tp = 0; + + while (sp < s.length && tp < t.length) { + if (s[sp] === t[tp]) { + sp++; + } + tp++; + } + + return sp === s.length; +}; \ No newline at end of file diff --git a/Is Subsequence - Leetcode 392/Is Subsequence - Leetcode 392.py b/Is Subsequence - Leetcode 392/Is Subsequence - Leetcode 392.py new file mode 100644 index 0000000..b4704a0 --- /dev/null +++ b/Is Subsequence - Leetcode 392/Is Subsequence - Leetcode 392.py @@ -0,0 +1,17 @@ +class Solution: + def isSubsequence(self, s: str, t: str) -> bool: + S = len(s) + T = len(t) + if s == '': return True + if S > T: return False + + j = 0 + for i in range(T): + if t[i] == s[j]: + if j == S-1: + return True + j += 1 + + return False + # Time: O(T) + # Space: O(1) diff --git a/Jewels and Stones - Leetcode 771.py b/Jewels and Stones - Leetcode 771.py deleted file mode 100644 index 1b5c794..0000000 --- a/Jewels and Stones - Leetcode 771.py +++ /dev/null @@ -1,12 +0,0 @@ -class Solution: - def numJewelsInStones (self, jewels: str, stones: str) -> int: - # O(n + m) - s = set(jewels) - count = 0 - for stone in stones: - if stone in s: - count += 1 - return count - -# Time Complexity: O(n + m) -# Space Complexity: O(n) diff --git a/Jewels and Stones - Leetcode 771/Jewels and Stones - Leetcode 771.cpp b/Jewels and Stones - Leetcode 771/Jewels and Stones - Leetcode 771.cpp new file mode 100644 index 0000000..db2df9d --- /dev/null +++ b/Jewels and Stones - Leetcode 771/Jewels and Stones - Leetcode 771.cpp @@ -0,0 +1,18 @@ +#include +#include + +class Solution { +public: + int numJewelsInStones(std::string jewels, std::string stones) { + std::unordered_set jewelSet(jewels.begin(), jewels.end()); + + int count = 0; + for (char stone : stones) { + if (jewelSet.find(stone) != jewelSet.end()) { + count++; + } + } + + return count; + } +}; diff --git a/Jewels and Stones - Leetcode 771/Jewels and Stones - Leetcode 771.java b/Jewels and Stones - Leetcode 771/Jewels and Stones - Leetcode 771.java new file mode 100644 index 0000000..7d1dd86 --- /dev/null +++ b/Jewels and Stones - Leetcode 771/Jewels and Stones - Leetcode 771.java @@ -0,0 +1,19 @@ +import java.util.HashSet; + +class Solution { + public int numJewelsInStones(String jewels, String stones) { + HashSet jewelSet = new HashSet<>(); + for (char j : jewels.toCharArray()) { + jewelSet.add(j); + } + + int count = 0; + for (char s : stones.toCharArray()) { + if (jewelSet.contains(s)) { + count++; + } + } + + return count; + } +} diff --git a/Jewels and Stones - Leetcode 771/Jewels and Stones - Leetcode 771.js b/Jewels and Stones - Leetcode 771/Jewels and Stones - Leetcode 771.js new file mode 100644 index 0000000..03dbc42 --- /dev/null +++ b/Jewels and Stones - Leetcode 771/Jewels and Stones - Leetcode 771.js @@ -0,0 +1,12 @@ +var numJewelsInStones = function(jewels, stones) { + const jewelSet = new Set(jewels); + let count = 0; + + for (const stone of stones) { + if (jewelSet.has(stone)) { + count++; + } + } + + return count; +}; diff --git a/Jewels and Stones - Leetcode 771/Jewels and Stones - Leetcode 771.py b/Jewels and Stones - Leetcode 771/Jewels and Stones - Leetcode 771.py new file mode 100644 index 0000000..2aa2180 --- /dev/null +++ b/Jewels and Stones - Leetcode 771/Jewels and Stones - Leetcode 771.py @@ -0,0 +1,26 @@ +# Brute Force Solution +class Solution: + def numJewelsInStones (self, jewels: str, stones: str) -> int: + count = 0 + for stone in stones: + if stone in jewels: + count += 1 + return count + +# Time Complexity: O(n * m) +# Space Complexity: O(1) + + +# Optimal Solution +class Solution: + def numJewelsInStones (self, jewels: str, stones: str) -> int: + # O(n + m) + s = set(jewels) + count = 0 + for stone in stones: + if stone in s: + count += 1 + return count + +# Time Complexity: O(n + m) +# Space Complexity: O(n) diff --git a/Jump Game - Leetcode 55/Jump Game - Leetcode 55.cpp b/Jump Game - Leetcode 55/Jump Game - Leetcode 55.cpp new file mode 100644 index 0000000..abf3e8a --- /dev/null +++ b/Jump Game - Leetcode 55/Jump Game - Leetcode 55.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + bool canJump(vector& nums) { + int n = nums.size(); + int target = n - 1; + + for (int i = n - 1; i >= 0; --i) { + if (i + nums[i] >= target) { + target = i; + } + } + + return target == 0; + } +}; diff --git a/Jump Game - Leetcode 55/Jump Game - Leetcode 55.java b/Jump Game - Leetcode 55/Jump Game - Leetcode 55.java new file mode 100644 index 0000000..9568d1b --- /dev/null +++ b/Jump Game - Leetcode 55/Jump Game - Leetcode 55.java @@ -0,0 +1,14 @@ +class Solution { + public boolean canJump(int[] nums) { + int n = nums.length; + int target = n - 1; + + for (int i = n - 1; i >= 0; i--) { + if (i + nums[i] >= target) { + target = i; + } + } + + return target == 0; + } +} diff --git a/Jump Game - Leetcode 55/Jump Game - Leetcode 55.js b/Jump Game - Leetcode 55/Jump Game - Leetcode 55.js new file mode 100644 index 0000000..6b5af05 --- /dev/null +++ b/Jump Game - Leetcode 55/Jump Game - Leetcode 55.js @@ -0,0 +1,12 @@ +var canJump = function(nums) { + const n = nums.length; + let target = n - 1; + + for (let i = n - 1; i >= 0; i--) { + if (i + nums[i] >= target) { + target = i; + } + } + + return target === 0; +}; diff --git a/Jump Game - Leetcode 55/Jump Game - Leetcode 55.py b/Jump Game - Leetcode 55/Jump Game - Leetcode 55.py new file mode 100644 index 0000000..83187bd --- /dev/null +++ b/Jump Game - Leetcode 55/Jump Game - Leetcode 55.py @@ -0,0 +1,57 @@ +class Solution: + def canJump(self, nums: List[int]) -> bool: + # Recursive Solution + # Time: O(Max(nums) ^ n) + # Space: O(n) + n = len(nums) + + def can_reach(i): + if i == n-1: + return True + + for jump in range(1, nums[i]+1): + if can_reach(i+jump): + return True + + return False + + return can_reach(0) + + +class Solution: + def canJump(self, nums: List[int]) -> bool: + # Top Down DP (Memoization) + # Time: O(n^2) + # Space: O(n) + n = len(nums) + memo = {n-1: True} + + def can_reach(i): + if i in memo: + return memo[i] + + for jump in range(1, nums[i]+1): + if can_reach(i+jump): + memo[i] = True + return True + + memo[i] = False + return False + + return can_reach(0) + + +class Solution: + def canJump(self, nums: List[int]) -> bool: + # Greedy - Start at end + # Time: O(n) + # Space: O(1) + n = len(nums) + target = n - 1 + + for i in range(n-1, -1, -1): + max_jump = nums[i] + if i + max_jump >= target: + target = i + + return target == 0 diff --git a/Jump Game II - Leetcode 45/Jump Game II - Leetcode 45.cpp b/Jump Game II - Leetcode 45/Jump Game II - Leetcode 45.cpp new file mode 100644 index 0000000..61e4296 --- /dev/null +++ b/Jump Game II - Leetcode 45/Jump Game II - Leetcode 45.cpp @@ -0,0 +1,56 @@ +// Brute Force +#include +#include +#include + +class Solution { +public: + int jump(std::vector& nums) { + int n = nums.size(); + int smallest = INT_MAX; + + backtrack(0, 0, nums, n, smallest); + return smallest; + } + +private: + void backtrack(int i, int jumps, std::vector& nums, int n, int& smallest) { + if (i == n - 1) { + smallest = std::min(smallest, jumps); + return; + } + + int maxJump = nums[i]; + int maxReachableIndex = std::min(i + maxJump, n - 1); + + for (int newIndex = maxReachableIndex; newIndex > i; newIndex--) { + backtrack(newIndex, jumps + 1, nums, n, smallest); + } + } +}; + + +// Optimal +#include +#include + +class Solution { +public: + int jump(std::vector& nums) { + int smallest = 0; + int n = nums.size(); + int end = 0; + int far = 0; + + for (int i = 0; i < n - 1; i++) { + far = std::max(far, i + nums[i]); + + if (i == end) { + smallest++; + end = far; + } + } + + return smallest; + } +}; diff --git a/Jump Game II - Leetcode 45/Jump Game II - Leetcode 45.java b/Jump Game II - Leetcode 45/Jump Game II - Leetcode 45.java new file mode 100644 index 0000000..964bce4 --- /dev/null +++ b/Jump Game II - Leetcode 45/Jump Game II - Leetcode 45.java @@ -0,0 +1,46 @@ +// Brute Force +public class Solution { + public int jump(int[] nums) { + int n = nums.length; + int[] smallest = {Integer.MAX_VALUE}; + + backtrack(0, 0, nums, n, smallest); + return smallest[0]; + } + + private void backtrack(int i, int jumps, int[] nums, int n, int[] smallest) { + if (i == n - 1) { + smallest[0] = Math.min(smallest[0], jumps); + return; + } + + int maxJump = nums[i]; + int maxReachableIndex = Math.min(i + maxJump, n - 1); + + for (int newIndex = maxReachableIndex; newIndex > i; newIndex--) { + backtrack(newIndex, jumps + 1, nums, n, smallest); + } + } +} + + +// Optimal +class Solution { + public int jump(int[] nums) { + int smallest = 0; + int n = nums.length; + int end = 0; + int far = 0; + + for (int i = 0; i < n - 1; i++) { + far = Math.max(far, i + nums[i]); + + if (i == end) { + smallest++; + end = far; + } + } + + return smallest; + } +} diff --git a/Jump Game II - Leetcode 45/Jump Game II - Leetcode 45.js b/Jump Game II - Leetcode 45/Jump Game II - Leetcode 45.js new file mode 100644 index 0000000..e06e503 --- /dev/null +++ b/Jump Game II - Leetcode 45/Jump Game II - Leetcode 45.js @@ -0,0 +1,42 @@ +// Brute Force +var jump = function(nums) { + var n = nums.length; + var smallest = [Infinity]; + + function backtrack(i, jumps) { + if (i === n - 1) { + smallest[0] = Math.min(smallest[0], jumps); + return; + } + + var maxJump = nums[i]; + var maxReachableIndex = Math.min(i + maxJump, n - 1); + + for (var newIndex = maxReachableIndex; newIndex > i; newIndex--) { + backtrack(newIndex, jumps + 1); + } + } + + backtrack(0, 0); + return smallest[0]; +}; + + +// Optimal +var jump = function(nums) { + var smallest = 0; + var n = nums.length; + var end = 0; + var far = 0; + + for (var i = 0; i < n - 1; i++) { + far = Math.max(far, i + nums[i]); + + if (i == end) { + smallest++; + end = far; + } + } + + return smallest; +}; diff --git a/Jump Game II - Leetcode 45/Jump Game II - Leetcode 45.py b/Jump Game II - Leetcode 45/Jump Game II - Leetcode 45.py new file mode 100644 index 0000000..cec375e --- /dev/null +++ b/Jump Game II - Leetcode 45/Jump Game II - Leetcode 45.py @@ -0,0 +1,39 @@ +# Brute Force +class Solution: + def jump(self, nums: List[int]) -> int: + n = len(nums) + smallest = [float('inf')] + + def backtrack(i=0, jumps=0): + if i == n-1: + smallest[0] = min(smallest[0], jumps) + return + + max_jump = nums[i] + max_reachable_index = min(i+max_jump, n-1) + + for new_index in range(max_reachable_index, i, -1): + backtrack(new_index, jumps+1) + + backtrack() + return smallest[0] + + +# Optimal +class Solution: + def jump(self, nums: List[int]) -> int: + smallest = 0 + n = len(nums) + end, far = 0, 0 + + for i in range(n-1): + far = max(far, i+nums[i]) + + if i == end: + smallest += 1 + end = far + + return smallest + # Time: O(n) + # Space: O(1) + \ No newline at end of file diff --git a/K Closest Points to Origin - Leetcode 973/K Closest Points to Origin - Leetcode 973.cpp b/K Closest Points to Origin - Leetcode 973/K Closest Points to Origin - Leetcode 973.cpp new file mode 100644 index 0000000..4406574 --- /dev/null +++ b/K Closest Points to Origin - Leetcode 973/K Closest Points to Origin - Leetcode 973.cpp @@ -0,0 +1,34 @@ +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector> kClosest(vector>& points, int k) { + auto dist = [](const vector& point) { + return point[0] * point[0] + point[1] * point[1]; + }; + + priority_queue, vector>, function&, const vector&)>> maxHeap( + [&dist](const vector& a, const vector& b) { + return dist(a) < dist(b); + } + ); + + for (const auto& point : points) { + maxHeap.push(point); + if (maxHeap.size() > k) { + maxHeap.pop(); + } + } + + vector> result; + while (!maxHeap.empty()) { + result.push_back(maxHeap.top()); + maxHeap.pop(); + } + return result; + } +}; diff --git a/K Closest Points to Origin - Leetcode 973/K Closest Points to Origin - Leetcode 973.java b/K Closest Points to Origin - Leetcode 973/K Closest Points to Origin - Leetcode 973.java new file mode 100644 index 0000000..c40ba16 --- /dev/null +++ b/K Closest Points to Origin - Leetcode 973/K Closest Points to Origin - Leetcode 973.java @@ -0,0 +1,28 @@ +import java.util.PriorityQueue; +import java.util.Arrays; + +class Solution { + public int[][] kClosest(int[][] points, int k) { + // Custom comparator to sort based on distance + PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> { + int distA = a[0] * a[0] + a[1] * a[1]; + int distB = b[0] * b[0] + b[1] * b[1]; + return Integer.compare(distB, distA); // Max-heap + }); + + for (int[] point : points) { + maxHeap.add(point); + if (maxHeap.size() > k) { + maxHeap.poll(); // Remove the farthest point + } + } + + // Convert the heap to an array + int[][] result = new int[k][2]; + for (int i = 0; i < k; i++) { + result[i] = maxHeap.poll(); + } + + return result; + } +} diff --git a/K Closest Points to Origin - Leetcode 973/K Closest Points to Origin - Leetcode 973.js b/K Closest Points to Origin - Leetcode 973/K Closest Points to Origin - Leetcode 973.js new file mode 100644 index 0000000..0c944c4 --- /dev/null +++ b/K Closest Points to Origin - Leetcode 973/K Closest Points to Origin - Leetcode 973.js @@ -0,0 +1,70 @@ +/* +max heap approach: +have a max heap of size k, so we would do N insertions that take log(k) +for this case we would need to implement heapify up (insert) and heapify down (remove) + +runtime: O(N log(k)) +space: O(k) +*/ +var kClosest = function(points, k) { + let heap = [] + + // now we need to try to add all points to the heap + for(let i=0; i= k && distance(points[i]) > distance(heap[0])) { // it's bigger than the max, we can just skip it + continue + } + add(heap, points[i], distance) + if(heap.length > k) { + remove(heap, distance) + } + } + + return heap + + // add at end, heapify up + function add(heap, node, weightFunction) { + heap.push(node) + heapifyUp(heap, heap.length - 1, weightFunction) + } + + // compare with parent and swap if needed, repeat + function heapifyUp(heap, idx, weightFunction) { + if(idx === 0) return + let parent = Math.floor((idx-1) / 2) + if(weightFunction(heap[idx]) > weightFunction(heap[parent])) { + [heap[idx], heap[parent]] = [heap[parent], heap[idx]] + heapifyUp(heap, parent, weightFunction) + } + } + + // read 0, replace 0 with last position, heapifyDown + function remove(heap, weightFunction) { + let val = heap[0] + heap[0] = heap.pop() + heapifyDown(heap, 0, weightFunction) + return val + } + + // compare with children, swap with biggest, repeat + function heapifyDown(heap, idx, weightFunction) { + let left = 2*idx + 1 + let right = 2*idx + 2 + let biggest = left + + if(left >= heap.length) return + + if(right < heap.length && weightFunction(heap[left]) < weightFunction(heap[right])) { + biggest = right + } + + if (weightFunction(heap[idx]) < weightFunction(heap[biggest])) { + [heap[idx], heap[biggest]] = [heap[biggest], heap[idx]] + heapifyDown(heap, biggest, weightFunction) + } + } + + function distance(point) { + return point[0] * point[0] + point[1] * point[1] + } +} \ No newline at end of file diff --git a/K Closest Points to Origin - Leetcode 973.py b/K Closest Points to Origin - Leetcode 973/K Closest Points to Origin - Leetcode 973.py similarity index 100% rename from K Closest Points to Origin - Leetcode 973.py rename to K Closest Points to Origin - Leetcode 973/K Closest Points to Origin - Leetcode 973.py diff --git a/Koko Eating Bananas - Leetcode 875/Koko Eating Bananas - Leetcode 875.cpp b/Koko Eating Bananas - Leetcode 875/Koko Eating Bananas - Leetcode 875.cpp new file mode 100644 index 0000000..2e42f15 --- /dev/null +++ b/Koko Eating Bananas - Leetcode 875/Koko Eating Bananas - Leetcode 875.cpp @@ -0,0 +1,32 @@ +#include +#include +#include + +class Solution { +public: + int minEatingSpeed(std::vector& piles, int h) { + int left = 1; + int right = *std::max_element(piles.begin(), piles.end()); + + while (left < right) { + int mid = left + (right - left) / 2; + + if (canFinish(piles, h, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; + } + +private: + bool canFinish(const std::vector& piles, int h, int k) { + int hours = 0; + for (int pile : piles) { + hours += std::ceil(static_cast(pile) / k); + } + return hours <= h; + } +}; diff --git a/Koko Eating Bananas - Leetcode 875/Koko Eating Bananas - Leetcode 875.java b/Koko Eating Bananas - Leetcode 875/Koko Eating Bananas - Leetcode 875.java new file mode 100644 index 0000000..13ab41a --- /dev/null +++ b/Koko Eating Bananas - Leetcode 875/Koko Eating Bananas - Leetcode 875.java @@ -0,0 +1,28 @@ +import java.util.*; + +class Solution { + public int minEatingSpeed(int[] piles, int h) { + int left = 1; + int right = Arrays.stream(piles).max().orElse(1); // maximum pile + + while (left < right) { + int mid = (left + right) / 2; + + if (canFinish(piles, h, mid)) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; + } + + private boolean canFinish(int[] piles, int h, int k) { + int hours = 0; + for (int pile : piles) { + hours += (pile + k - 1) / k; // Equivalent to ceil(pile / k) + } + return hours <= h; + } +} diff --git a/Koko Eating Bananas - Leetcode 875/Koko Eating Bananas - Leetcode 875.js b/Koko Eating Bananas - Leetcode 875/Koko Eating Bananas - Leetcode 875.js new file mode 100644 index 0000000..4b4a642 --- /dev/null +++ b/Koko Eating Bananas - Leetcode 875/Koko Eating Bananas - Leetcode 875.js @@ -0,0 +1,24 @@ +var minEatingSpeed = function(piles, h) { + const canFinish = (k) => { + let hours = 0; + for (const pile of piles) { + hours += Math.ceil(pile / k); + } + return hours <= h; + }; + + let left = 1; + let right = Math.max(...piles); + + while (left < right) { + const mid = Math.floor((left + right) / 2); + + if (canFinish(mid)) { + right = mid; + } else { + left = mid + 1; + } + } + + return left; +}; diff --git a/Koko Eating Bananas - Leetcode 875.py b/Koko Eating Bananas - Leetcode 875/Koko Eating Bananas - Leetcode 875.py similarity index 100% rename from Koko Eating Bananas - Leetcode 875.py rename to Koko Eating Bananas - Leetcode 875/Koko Eating Bananas - Leetcode 875.py diff --git a/Kth Largest Element in an Array - Leetcode 215/Kth Largest Element in an Array - Leetcode 215.cpp b/Kth Largest Element in an Array - Leetcode 215/Kth Largest Element in an Array - Leetcode 215.cpp new file mode 100644 index 0000000..9bc4f19 --- /dev/null +++ b/Kth Largest Element in an Array - Leetcode 215/Kth Largest Element in an Array - Leetcode 215.cpp @@ -0,0 +1,39 @@ +#include +#include +#include + +class Solution { +public: + int findKthLargest(std::vector& nums, int k) { + std::priority_queue maxHeap(nums.begin(), nums.end()); + + for (int i = 0; i < k - 1; ++i) { + maxHeap.pop(); + } + + return maxHeap.top(); + } +}; + + +#include +#include +#include + +class Solution { +public: + int findKthLargest(std::vector& nums, int k) { + std::priority_queue, std::greater> minHeap; + + for (int num : nums) { + if (minHeap.size() < k) { + minHeap.push(num); + } else if (num > minHeap.top()) { + minHeap.pop(); + minHeap.push(num); + } + } + + return minHeap.top(); + } +}; diff --git a/Kth Largest Element in an Array - Leetcode 215/Kth Largest Element in an Array - Leetcode 215.java b/Kth Largest Element in an Array - Leetcode 215/Kth Largest Element in an Array - Leetcode 215.java new file mode 100644 index 0000000..e27ba1e --- /dev/null +++ b/Kth Largest Element in an Array - Leetcode 215/Kth Largest Element in an Array - Leetcode 215.java @@ -0,0 +1,36 @@ +import java.util.*; + +class Solution { + public int findKthLargest(int[] nums, int k) { + PriorityQueue maxHeap = new PriorityQueue<>(Collections.reverseOrder()); + for (int num : nums) { + maxHeap.add(num); + } + + int result = 0; + for (int i = 0; i < k; i++) { + result = maxHeap.poll(); + } + return result; + } +} + + +import java.util.*; + +class Solution { + public int findKthLargest(int[] nums, int k) { + PriorityQueue minHeap = new PriorityQueue<>(); + for (int num : nums) { + if (minHeap.size() < k) { + minHeap.add(num); + } else { + if (num > minHeap.peek()) { + minHeap.poll(); + minHeap.add(num); + } + } + } + return minHeap.peek(); + } +} diff --git a/Kth Largest Element in an Array - Leetcode 215/Kth Largest Element in an Array - Leetcode 215.js b/Kth Largest Element in an Array - Leetcode 215/Kth Largest Element in an Array - Leetcode 215.js new file mode 100644 index 0000000..e8a2672 --- /dev/null +++ b/Kth Largest Element in an Array - Leetcode 215/Kth Largest Element in an Array - Leetcode 215.js @@ -0,0 +1,81 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +class MinHeap { + constructor() { + this.heap = []; + } + push(val) { + this.heap.push(val); + this.bubbleUp(); + } + pop() { + const max = this.heap[0]; + const end = this.heap.pop(); + if (this.heap.length > 0) { + this.heap[0] = end; + this.bubbleDown(); + } + return max; + } + peek() { + return this.heap[0]; + } + bubbleUp() { + let idx = this.heap.length - 1; + const element = this.heap[idx]; + while (idx > 0) { + let parentIdx = Math.floor((idx - 1) / 2); + let parent = this.heap[parentIdx]; + if (element >= parent) break; + this.heap[parentIdx] = element; + this.heap[idx] = parent; + idx = parentIdx; + } + } + bubbleDown() { + let idx = 0; + const length = this.heap.length; + const element = this.heap[0]; + while (true) { + let leftChildIdx = 2 * idx + 1; + let rightChildIdx = 2 * idx + 2; + let leftChild, rightChild; + let swap = null; + if (leftChildIdx < length) { + leftChild = this.heap[leftChildIdx]; + if (leftChild < element) { + swap = leftChildIdx; + } + } + if (rightChildIdx < length) { + rightChild = this.heap[rightChildIdx]; + if ( + (swap === null && rightChild < element) || + (swap !== null && rightChild < leftChild) + ) { + swap = rightChildIdx; + } + } + if (swap === null) break; + this.heap[idx] = this.heap[swap]; + this.heap[swap] = element; + idx = swap; + } + } +} +var findKthLargest = function(nums, k) { + let heap = new MinHeap(); + for (let i = 0; i < k; i++) { + heap.push(nums[i]); + } + for (let i = k; i < nums.length; i++) { + if (nums[i] > heap.peek()) { + heap.pop(); + heap.push(nums[i]); + } + } + return heap.peek(); +}; \ No newline at end of file diff --git a/Kth Largest Element in an Array - Leetcode 215/Kth Largest Element in an Array - Leetcode 215.py b/Kth Largest Element in an Array - Leetcode 215/Kth Largest Element in an Array - Leetcode 215.py new file mode 100644 index 0000000..31354d6 --- /dev/null +++ b/Kth Largest Element in an Array - Leetcode 215/Kth Largest Element in an Array - Leetcode 215.py @@ -0,0 +1,41 @@ +# Brute Force Solution +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + nums.sort() + return nums[-k] + +# Time: O(n log n) +# Space: O(1) + +import heapq +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + for i in range(len(nums)): + nums[i] = -nums[i] # Max Heap + + heapq.heapify(nums) + + for _ in range(k-1): + heapq.heappop(nums) + + return -heapq.heappop(nums) + # Max Heap of size n + # Time: O(n + k log n) + # Space: O(1) + +import heapq +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + min_heap = [] + + for num in nums: + if len(min_heap) < k: + heapq.heappush(min_heap, num) + else: + heapq.heappushpop(min_heap, num) + + return min_heap[0] + # Min heap of size k + # Time: O(n log k) + # Space: O(k) + diff --git a/Kth Smallest Element in a BST - Leetcode 230/Kth Smallest Element in a BST - Leetcode 230.cpp b/Kth Smallest Element in a BST - Leetcode 230/Kth Smallest Element in a BST - Leetcode 230.cpp new file mode 100644 index 0000000..1f1bb44 --- /dev/null +++ b/Kth Smallest Element in a BST - Leetcode 230/Kth Smallest Element in a BST - Leetcode 230.cpp @@ -0,0 +1,31 @@ +#include +#include + +class Solution { +public: + int kthSmallest(TreeNode* root, int k) { + count = k; + ans = 0; + dfs(root); + return ans; + } + +private: + int count; + int ans; + + void dfs(TreeNode* node) { + if (!node) return; + + dfs(node->left); + + if (count == 1) { + ans = node->val; + } + + count--; + if (count > 0) { + dfs(node->right); + } + } +}; diff --git a/Kth Smallest Element in a BST - Leetcode 230/Kth Smallest Element in a BST - Leetcode 230.java b/Kth Smallest Element in a BST - Leetcode 230/Kth Smallest Element in a BST - Leetcode 230.java new file mode 100644 index 0000000..416adde --- /dev/null +++ b/Kth Smallest Element in a BST - Leetcode 230/Kth Smallest Element in a BST - Leetcode 230.java @@ -0,0 +1,30 @@ +import java.util.*; + +public class Solution { + private int count; + private int ans; + + public int kthSmallest(TreeNode root, int k) { + count = k; + ans = 0; + dfs(root); + return ans; + } + + private void dfs(TreeNode node) { + if (node == null) { + return; + } + + dfs(node.left); + + if (count == 1) { + ans = node.val; + } + + count--; + if (count > 0) { + dfs(node.right); + } + } +} diff --git a/Kth Smallest Element in a BST - Leetcode 230/Kth Smallest Element in a BST - Leetcode 230.js b/Kth Smallest Element in a BST - Leetcode 230/Kth Smallest Element in a BST - Leetcode 230.js new file mode 100644 index 0000000..e655d92 --- /dev/null +++ b/Kth Smallest Element in a BST - Leetcode 230/Kth Smallest Element in a BST - Leetcode 230.js @@ -0,0 +1,22 @@ +var kthSmallest = function(root, k) { + let count = k; + let ans = 0; + + function dfs(node) { + if (!node) return; + + dfs(node.left); + + if (count === 1) { + ans = node.val; + } + + count--; + if (count > 0) { + dfs(node.right); + } + } + + dfs(root); + return ans; +}; diff --git a/Kth Smallest Element in a BST - Leetcode 230/Kth Smallest Element in a BST - Leetcode 230.py b/Kth Smallest Element in a BST - Leetcode 230/Kth Smallest Element in a BST - Leetcode 230.py new file mode 100644 index 0000000..6e67105 --- /dev/null +++ b/Kth Smallest Element in a BST - Leetcode 230/Kth Smallest Element in a BST - Leetcode 230.py @@ -0,0 +1,28 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: + count = [k] + ans = [0] + + def dfs(node): + if not node: + return + + dfs(node.left) + + if count[0] == 1: + ans[0] = node.val + + count[0] = count[0] - 1 + if count[0] > 0: + dfs(node.right) + + dfs(root) + return ans[0] + # Time: O(n) + # Space: O(n) diff --git a/Largest Rectangle in Histogram - Leetcode 84/Largest Rectangle in Histogram - Leetcode 84.cpp b/Largest Rectangle in Histogram - Leetcode 84/Largest Rectangle in Histogram - Leetcode 84.cpp new file mode 100644 index 0000000..3fe7d6e --- /dev/null +++ b/Largest Rectangle in Histogram - Leetcode 84/Largest Rectangle in Histogram - Leetcode 84.cpp @@ -0,0 +1,32 @@ +#include +#include +#include + +class Solution { +public: + int largestRectangleArea(std::vector& heights) { + int n = heights.size(); + std::stack> stk; + int maxArea = 0; + + for (int i = 0; i < n; i++) { + int height = heights[i]; + int start = i; + while (!stk.empty() && height < stk.top().first) { + auto [h, j] = stk.top(); stk.pop(); + int w = i - j; + maxArea = std::max(maxArea, h * w); + start = j; + } + stk.push({height, start}); + } + + while (!stk.empty()) { + auto [h, j] = stk.top(); stk.pop(); + int w = n - j; + maxArea = std::max(maxArea, h * w); + } + + return maxArea; + } +}; diff --git a/Largest Rectangle in Histogram - Leetcode 84/Largest Rectangle in Histogram - Leetcode 84.java b/Largest Rectangle in Histogram - Leetcode 84/Largest Rectangle in Histogram - Leetcode 84.java new file mode 100644 index 0000000..68d2b17 --- /dev/null +++ b/Largest Rectangle in Histogram - Leetcode 84/Largest Rectangle in Histogram - Leetcode 84.java @@ -0,0 +1,31 @@ +class Solution { + public int largestRectangleArea(int[] heights) { + int n = heights.length; + Stack stk = new Stack<>(); + int maxArea = 0; + + for (int i = 0; i < n; i++) { + int height = heights[i]; + int start = i; + while (!stk.isEmpty() && height < stk.peek()[0]) { + int[] popped = stk.pop(); + int h = popped[0]; + int j = popped[1]; + int w = i - j; + maxArea = Math.max(maxArea, h * w); + start = j; + } + stk.push(new int[]{height, start}); + } + + while (!stk.isEmpty()) { + int[] popped = stk.pop(); + int h = popped[0]; + int j = popped[1]; + int w = n - j; + maxArea = Math.max(maxArea, h * w); + } + + return maxArea; + } +} diff --git a/Largest Rectangle in Histogram - Leetcode 84/Largest Rectangle in Histogram - Leetcode 84.js b/Largest Rectangle in Histogram - Leetcode 84/Largest Rectangle in Histogram - Leetcode 84.js new file mode 100644 index 0000000..0ce2fea --- /dev/null +++ b/Largest Rectangle in Histogram - Leetcode 84/Largest Rectangle in Histogram - Leetcode 84.js @@ -0,0 +1,26 @@ +var largestRectangleArea = function(heights) { + var n = heights.length; + var stk = []; + var maxArea = 0; + + for (var i = 0; i < n; i++) { + var height = heights[i]; + var start = i; + while (stk.length > 0 && height < stk[stk.length - 1][0]) { + var [h, j] = stk.pop(); + var w = i - j; + var a = h * w; + maxArea = Math.max(maxArea, a); + start = j; + } + stk.push([height, start]); + } + + while (stk.length > 0) { + var [h, j] = stk.pop(); + var w = n - j; + maxArea = Math.max(maxArea, h * w); + } + + return maxArea; +}; diff --git a/Largest Rectangle in Histogram - Leetcode 84/Largest Rectangle in Histogram - Leetcode 84.py b/Largest Rectangle in Histogram - Leetcode 84/Largest Rectangle in Histogram - Leetcode 84.py new file mode 100644 index 0000000..deec9e3 --- /dev/null +++ b/Largest Rectangle in Histogram - Leetcode 84/Largest Rectangle in Histogram - Leetcode 84.py @@ -0,0 +1,24 @@ +class Solution: + def largestRectangleArea(self, heights: List[int]) -> int: + n = len(heights) + stk = [] + max_area = 0 + + for i, height in enumerate(heights): + start = i + while stk and height < stk[-1][0]: + h, j = stk.pop() + w = i - j + a = h*w + max_area = max(max_area, a) + start = j + stk.append((height, start)) + + while stk: + h, j = stk.pop() + w = n - j + max_area = max(max_area, h*w) + + return max_area + # Time: O(n) + # Space: O(n) \ No newline at end of file diff --git a/Last Stone Weight - Leetcode 1046/Last Stone Weight - Leetcode 1046.cpp b/Last Stone Weight - Leetcode 1046/Last Stone Weight - Leetcode 1046.cpp new file mode 100644 index 0000000..772b408 --- /dev/null +++ b/Last Stone Weight - Leetcode 1046/Last Stone Weight - Leetcode 1046.cpp @@ -0,0 +1,23 @@ +#include +#include +#include + +class Solution { +public: + int lastStoneWeight(std::vector& stones) { + std::priority_queue maxHeap(stones.begin(), stones.end()); + + while (maxHeap.size() > 1) { + int largest = maxHeap.top(); + maxHeap.pop(); + int nextLargest = maxHeap.top(); + maxHeap.pop(); + + if (largest != nextLargest) { + maxHeap.push(largest - nextLargest); + } + } + + return maxHeap.empty() ? 0 : maxHeap.top(); + } +}; diff --git a/Last Stone Weight - Leetcode 1046/Last Stone Weight - Leetcode 1046.java b/Last Stone Weight - Leetcode 1046/Last Stone Weight - Leetcode 1046.java new file mode 100644 index 0000000..51079ff --- /dev/null +++ b/Last Stone Weight - Leetcode 1046/Last Stone Weight - Leetcode 1046.java @@ -0,0 +1,22 @@ +import java.util.PriorityQueue; + +public class Solution { + public int lastStoneWeight(int[] stones) { + PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b - a); + + for (int stone : stones) { + maxHeap.offer(stone); + } + + while (maxHeap.size() > 1) { + int largest = maxHeap.poll(); + int nextLargest = maxHeap.poll(); + + if (largest != nextLargest) { + maxHeap.offer(largest - nextLargest); + } + } + + return maxHeap.isEmpty() ? 0 : maxHeap.peek(); + } +} diff --git a/Last Stone Weight - Leetcode 1046/Last Stone Weight - Leetcode 1046.js b/Last Stone Weight - Leetcode 1046/Last Stone Weight - Leetcode 1046.js new file mode 100644 index 0000000..ff07bb7 --- /dev/null +++ b/Last Stone Weight - Leetcode 1046/Last Stone Weight - Leetcode 1046.js @@ -0,0 +1,18 @@ +var lastStoneWeight = function(stones) { + const maxHeap = new MaxPriorityQueue(); + + for (const stone of stones) { + maxHeap.enqueue(stone); + } + + while (maxHeap.size() > 1) { + const largest = maxHeap.dequeue().element; + const nextLargest = maxHeap.dequeue().element; + + if (largest !== nextLargest) { + maxHeap.enqueue(largest - nextLargest); + } + } + + return maxHeap.size() === 0 ? 0 : maxHeap.front().element; +}; diff --git a/Last Stone Weight - Leetcode 1046/Last Stone Weight - Leetcode 1046.py b/Last Stone Weight - Leetcode 1046/Last Stone Weight - Leetcode 1046.py new file mode 100644 index 0000000..f0966b5 --- /dev/null +++ b/Last Stone Weight - Leetcode 1046/Last Stone Weight - Leetcode 1046.py @@ -0,0 +1,37 @@ +# Brute Force Solution +class Solution: + def lastStoneWeight(self, stones: List[int]) -> int: + + def remove_largest(): + index_of_largest = stones.index(max(stones)) + return stones.pop(index_of_largest) + + while len(stones) > 1: + stone_1 = remove_largest() + stone_2 = remove_largest() + if stone_1 != stone_2: + stones.append(stone_1 - stone_2) + + return stones[0] if stones else 0 +# Time: O(n^2) +# Space: O(1) + +# Optimal Solution +class Solution: + def lastStoneWeight(self, stones: List[int]) -> int: + for i in range(len(stones)): + stones[i] *= -1 # Negate to force Max Heap + + heapq.heapify(stones) + + while len(stones) > 1: + largest = heapq.heappop(stones) + next_largest = heapq.heappop(stones) + + if largest != next_largest: + heapq.heappush(stones, largest - next_largest) + + return -heapq.heappop(stones) if stones else 0 + # Time: O(n log n) + # Space: O(1) + diff --git a/Letter Combinations of a Phone Number - Leetcode 17/Letter Combinations of a Phone Number - Leetcode 17.cpp b/Letter Combinations of a Phone Number - Leetcode 17/Letter Combinations of a Phone Number - Leetcode 17.cpp new file mode 100644 index 0000000..965a066 --- /dev/null +++ b/Letter Combinations of a Phone Number - Leetcode 17/Letter Combinations of a Phone Number - Leetcode 17.cpp @@ -0,0 +1,37 @@ +#include +#include +#include + +class Solution { +public: + std::vector letterCombinations(std::string digits) { + std::vector ans; + if (digits.empty()) return ans; + + std::unordered_map letterMap = { + {'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, {'6', "mno"}, + {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"} + }; + + std::string path; + backtrack(digits, 0, path, letterMap, ans); + return ans; + } + +private: + void backtrack(const std::string& digits, int index, std::string& path, + const std::unordered_map& letterMap, + std::vector& ans) { + if (index == digits.size()) { + ans.push_back(path); + return; + } + + const std::string& letters = letterMap.at(digits[index]); + for (char letter : letters) { + path.push_back(letter); + backtrack(digits, index + 1, path, letterMap, ans); + path.pop_back(); + } + } +}; diff --git a/Letter Combinations of a Phone Number - Leetcode 17/Letter Combinations of a Phone Number - Leetcode 17.java b/Letter Combinations of a Phone Number - Leetcode 17/Letter Combinations of a Phone Number - Leetcode 17.java new file mode 100644 index 0000000..ef41a02 --- /dev/null +++ b/Letter Combinations of a Phone Number - Leetcode 17/Letter Combinations of a Phone Number - Leetcode 17.java @@ -0,0 +1,40 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Solution { + public List letterCombinations(String digits) { + List ans = new ArrayList<>(); + if (digits.isEmpty()) { + return ans; + } + + Map letterMap = new HashMap<>(); + letterMap.put('2', "abc"); + letterMap.put('3', "def"); + letterMap.put('4', "ghi"); + letterMap.put('5', "jkl"); + letterMap.put('6', "mno"); + letterMap.put('7', "pqrs"); + letterMap.put('8', "tuv"); + letterMap.put('9', "wxyz"); + + backtrack(digits, 0, new StringBuilder(), letterMap, ans); + return ans; + } + + private void backtrack(String digits, int index, StringBuilder path, Map letterMap, List ans) { + if (index == digits.length()) { + ans.add(path.toString()); + return; + } + + String letters = letterMap.get(digits.charAt(index)); + for (char letter : letters.toCharArray()) { + path.append(letter); + backtrack(digits, index + 1, path, letterMap, ans); + path.deleteCharAt(path.length() - 1); + } + } +} diff --git a/Letter Combinations of a Phone Number - Leetcode 17/Letter Combinations of a Phone Number - Leetcode 17.js b/Letter Combinations of a Phone Number - Leetcode 17/Letter Combinations of a Phone Number - Leetcode 17.js new file mode 100644 index 0000000..02ce624 --- /dev/null +++ b/Letter Combinations of a Phone Number - Leetcode 17/Letter Combinations of a Phone Number - Leetcode 17.js @@ -0,0 +1,26 @@ +var letterCombinations = function(digits) { + if (!digits) return []; + + const letterMap = { + '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', + '7': 'pqrs', '8': 'tuv', '9': 'wxyz' + }; + + const ans = []; + const backtrack = (index, path) => { + if (index === digits.length) { + ans.push(path.join('')); + return; + } + + const letters = letterMap[digits[index]]; + for (const letter of letters) { + path.push(letter); + backtrack(index + 1, path); + path.pop(); + } + }; + + backtrack(0, []); + return ans; +}; diff --git a/Letter Combinations of a Phone Number - Leetcode 17.py b/Letter Combinations of a Phone Number - Leetcode 17/Letter Combinations of a Phone Number - Leetcode 17.py similarity index 100% rename from Letter Combinations of a Phone Number - Leetcode 17.py rename to Letter Combinations of a Phone Number - Leetcode 17/Letter Combinations of a Phone Number - Leetcode 17.py diff --git a/Linked List Cycle - Leetcode 141/Linked List Cycle - Leetcode 141.cpp b/Linked List Cycle - Leetcode 141/Linked List Cycle - Leetcode 141.cpp new file mode 100644 index 0000000..1aea931 --- /dev/null +++ b/Linked List Cycle - Leetcode 141/Linked List Cycle - Leetcode 141.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + bool hasCycle(ListNode *head) { + ListNode dummy; + dummy.next = head; + ListNode *slow = &dummy, *fast = &dummy; + + while (fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + + if (slow == fast) { + return true; + } + } + + return false; + } +}; diff --git a/Linked List Cycle - Leetcode 141/Linked List Cycle - Leetcode 141.java b/Linked List Cycle - Leetcode 141/Linked List Cycle - Leetcode 141.java new file mode 100644 index 0000000..316592b --- /dev/null +++ b/Linked List Cycle - Leetcode 141/Linked List Cycle - Leetcode 141.java @@ -0,0 +1,18 @@ +public class Solution { + public boolean hasCycle(ListNode head) { + ListNode dummy = new ListNode(0); + dummy.next = head; + ListNode slow = dummy, fast = dummy; + + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + + if (slow == fast) { + return true; + } + } + + return false; + } +} diff --git a/Linked List Cycle - Leetcode 141/Linked List Cycle - Leetcode 141.js b/Linked List Cycle - Leetcode 141/Linked List Cycle - Leetcode 141.js new file mode 100644 index 0000000..8dcc794 --- /dev/null +++ b/Linked List Cycle - Leetcode 141/Linked List Cycle - Leetcode 141.js @@ -0,0 +1,16 @@ +var hasCycle = function(head) { + const dummy = new ListNode(0); + dummy.next = head; + let slow = dummy, fast = dummy; + + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + + if (slow === fast) { + return true; + } + } + + return false; +}; diff --git a/Linked List Cycle - Leetcode 141.py b/Linked List Cycle - Leetcode 141/Linked List Cycle - Leetcode 141.py similarity index 78% rename from Linked List Cycle - Leetcode 141.py rename to Linked List Cycle - Leetcode 141/Linked List Cycle - Leetcode 141.py index da86af6..d0b3fd7 100644 --- a/Linked List Cycle - Leetcode 141.py +++ b/Linked List Cycle - Leetcode 141/Linked List Cycle - Leetcode 141.py @@ -1,8 +1,6 @@ class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: - dummy = ListNode() - dummy.next = head - slow = fast = dummy + slow = fast = head while fast and fast.next: fast = fast.next.next diff --git a/Longest Common Prefix - Leetcode 14/Longest Common Prefix - Leetcode 14.cpp b/Longest Common Prefix - Leetcode 14/Longest Common Prefix - Leetcode 14.cpp new file mode 100644 index 0000000..098b9e4 --- /dev/null +++ b/Longest Common Prefix - Leetcode 14/Longest Common Prefix - Leetcode 14.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + string longestCommonPrefix(vector& strs) { + if (strs.empty()) return ""; + + int minLength = INT_MAX; + for (const string& s : strs) { + minLength = min(minLength, (int)s.length()); + } + + int i = 0; + while (i < minLength) { + for (const string& s : strs) { + if (s[i] != strs[0][i]) { + return strs[0].substr(0, i); + } + } + i++; + } + + return strs[0].substr(0, i); + } +}; diff --git a/Longest Common Prefix - Leetcode 14/Longest Common Prefix - Leetcode 14.java b/Longest Common Prefix - Leetcode 14/Longest Common Prefix - Leetcode 14.java new file mode 100644 index 0000000..45eece4 --- /dev/null +++ b/Longest Common Prefix - Leetcode 14/Longest Common Prefix - Leetcode 14.java @@ -0,0 +1,26 @@ +public class Solution { + public String longestCommonPrefix(String[] strs) { + if (strs == null || strs.length == 0) { + return ""; + } + + int minLength = Integer.MAX_VALUE; + for (String s : strs) { + if (s.length() < minLength) { + minLength = s.length(); + } + } + + int i = 0; + while (i < minLength) { + for (String s : strs) { + if (s.charAt(i) != strs[0].charAt(i)) { + return strs[0].substring(0, i); + } + } + i++; + } + + return strs[0].substring(0, i); + } +} diff --git a/Longest Common Prefix - Leetcode 14/Longest Common Prefix - Leetcode 14.js b/Longest Common Prefix - Leetcode 14/Longest Common Prefix - Leetcode 14.js new file mode 100644 index 0000000..75feb59 --- /dev/null +++ b/Longest Common Prefix - Leetcode 14/Longest Common Prefix - Leetcode 14.js @@ -0,0 +1,20 @@ +var longestCommonPrefix = function(strs) { + if (strs.length === 0) return ""; + + let minLength = Infinity; + for (const s of strs) { + minLength = Math.min(minLength, s.length); + } + + let i = 0; + while (i < minLength) { + for (const s of strs) { + if (s[i] !== strs[0][i]) { + return strs[0].substring(0, i); + } + } + i++; + } + + return strs[0].substring(0, i); +}; diff --git a/Longest Common Prefix - Leetcode 14/Longest Common Prefix - Leetcode 14.py b/Longest Common Prefix - Leetcode 14/Longest Common Prefix - Leetcode 14.py new file mode 100644 index 0000000..b24e6bd --- /dev/null +++ b/Longest Common Prefix - Leetcode 14/Longest Common Prefix - Leetcode 14.py @@ -0,0 +1,18 @@ +class Solution: + def longestCommonPrefix(self, strs: List[str]) -> str: + min_length = float('inf') + + for s in strs: + if len(s) < min_length: + min_length = len(s) + + i = 0 + while i < min_length: + for s in strs: + if s[i] != strs[0][i]: + return s[:i] + i += 1 + + return strs[0][:i] + # Time: O(n * m) where n is the number of strings, m is the min word length + # Space: O(1) diff --git a/Longest Common Subsequence - Leetcode 1143/Longest Common Subsequence - Leetcode 1143.cpp b/Longest Common Subsequence - Leetcode 1143/Longest Common Subsequence - Leetcode 1143.cpp new file mode 100644 index 0000000..961c881 --- /dev/null +++ b/Longest Common Subsequence - Leetcode 1143/Longest Common Subsequence - Leetcode 1143.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int longestCommonSubsequence(string text1, string text2) { + int m = text1.size(); + int n = text2.size(); + + vector> dp(m + 1, vector(n + 1, 0)); + + for (int i = 1; i <= m; ++i) { + for (int j = 1; j <= n; ++j) { + if (text1[i - 1] == text2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + + return dp[m][n]; + } +}; diff --git a/Longest Common Subsequence - Leetcode 1143/Longest Common Subsequence - Leetcode 1143.java b/Longest Common Subsequence - Leetcode 1143/Longest Common Subsequence - Leetcode 1143.java new file mode 100644 index 0000000..2c8f9f8 --- /dev/null +++ b/Longest Common Subsequence - Leetcode 1143/Longest Common Subsequence - Leetcode 1143.java @@ -0,0 +1,20 @@ +public class Solution { + public int longestCommonSubsequence(String text1, String text2) { + int m = text1.length(); + int n = text2.length(); + + int[][] dp = new int[m + 1][n + 1]; + + for (int i = 1; i <= m; i++) { + for (int j = 1; j <= n; j++) { + if (text1.charAt(i - 1) == text2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + + return dp[m][n]; + } +} diff --git a/Longest Common Subsequence - Leetcode 1143/Longest Common Subsequence - Leetcode 1143.js b/Longest Common Subsequence - Leetcode 1143/Longest Common Subsequence - Leetcode 1143.js new file mode 100644 index 0000000..ee2fbcf --- /dev/null +++ b/Longest Common Subsequence - Leetcode 1143/Longest Common Subsequence - Leetcode 1143.js @@ -0,0 +1,18 @@ +var longestCommonSubsequence = function(text1, text2) { + const m = text1.length; + const n = text2.length; + + const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); + + for (let i = 1; i <= m; i++) { + for (let j = 1; j <= n; j++) { + if (text1[i - 1] === text2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + + return dp[m][n]; +}; diff --git a/Longest Common Subsequence - Leetcode 1143/Longest Common Subsequence - Leetcode 1143.py b/Longest Common Subsequence - Leetcode 1143/Longest Common Subsequence - Leetcode 1143.py new file mode 100644 index 0000000..e838570 --- /dev/null +++ b/Longest Common Subsequence - Leetcode 1143/Longest Common Subsequence - Leetcode 1143.py @@ -0,0 +1,39 @@ +class Solution: + def longestCommonSubsequence(self, text1: str, text2: str) -> int: + # Top Down DP (Memoization) + # Time: O(m*n) + # Space: O(m*n) + + m, n = len(text1), len(text2) + + @cache + def longest(i, j): + if i == m or j == n: + return 0 + elif text1[i] == text2[j]: + return 1 + longest(i+1, j+1) + else: + return max(longest(i, j+1), longest(i+1, j)) + + return longest(0, 0) + +class Solution: + def longestCommonSubsequence(self, text1: str, text2: str) -> int: + # Bottom Up DP (Tabulation) + # Time: O(m*n) + # Space: O(m*n) + + m, n = len(text1), len(text2) + dp = [[0] * (n+1) for _ in range(m + 1)] + + for i in range(1, m+1): + for j in range(1, n+1): + if text1[i-1] == text2[j-1]: + dp[i][j] = dp[i-1][j-1] + 1 + else: + dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + + return dp[m][n] + + + diff --git a/Longest Consecutive Sequence - Leetcode 128/Longest Consecutive Sequence - Leetcode 128.cpp b/Longest Consecutive Sequence - Leetcode 128/Longest Consecutive Sequence - Leetcode 128.cpp new file mode 100644 index 0000000..c9ee4b5 --- /dev/null +++ b/Longest Consecutive Sequence - Leetcode 128/Longest Consecutive Sequence - Leetcode 128.cpp @@ -0,0 +1,25 @@ +#include +#include +using namespace std; + +class Solution { +public: + int longestConsecutive(vector& nums) { + unordered_set set(nums.begin(), nums.end()); + int longest = 0; + + for (int num : set) { + if (set.find(num - 1) == set.end()) { + int length = 1; + int nextNum = num + 1; + while (set.find(nextNum) != set.end()) { + length++; + nextNum++; + } + longest = max(longest, length); + } + } + + return longest; + } +}; diff --git a/Longest Consecutive Sequence - Leetcode 128/Longest Consecutive Sequence - Leetcode 128.java b/Longest Consecutive Sequence - Leetcode 128/Longest Consecutive Sequence - Leetcode 128.java new file mode 100644 index 0000000..002a5dc --- /dev/null +++ b/Longest Consecutive Sequence - Leetcode 128/Longest Consecutive Sequence - Leetcode 128.java @@ -0,0 +1,27 @@ +import java.util.HashSet; +import java.util.Set; + +public class Solution { + public int longestConsecutive(int[] nums) { + Set set = new HashSet<>(); + for (int num : nums) { + set.add(num); + } + + int longest = 0; + + for (int num : set) { + if (!set.contains(num - 1)) { + int length = 1; + int nextNum = num + 1; + while (set.contains(nextNum)) { + length++; + nextNum++; + } + longest = Math.max(longest, length); + } + } + + return longest; + } +} diff --git a/Longest Consecutive Sequence - Leetcode 128/Longest Consecutive Sequence - Leetcode 128.js b/Longest Consecutive Sequence - Leetcode 128/Longest Consecutive Sequence - Leetcode 128.js new file mode 100644 index 0000000..a891fa0 --- /dev/null +++ b/Longest Consecutive Sequence - Leetcode 128/Longest Consecutive Sequence - Leetcode 128.js @@ -0,0 +1,18 @@ +var longestConsecutive = function(nums) { + const set = new Set(nums); + let longest = 0; + + for (const num of set) { + if (!set.has(num - 1)) { + let length = 1; + let nextNum = num + 1; + while (set.has(nextNum)) { + length++; + nextNum++; + } + longest = Math.max(longest, length); + } + } + + return longest; +}; diff --git a/Longest Consecutive Sequence - Leetcode 128.py b/Longest Consecutive Sequence - Leetcode 128/Longest Consecutive Sequence - Leetcode 128.py similarity index 94% rename from Longest Consecutive Sequence - Leetcode 128.py rename to Longest Consecutive Sequence - Leetcode 128/Longest Consecutive Sequence - Leetcode 128.py index 792add9..f260f54 100644 --- a/Longest Consecutive Sequence - Leetcode 128.py +++ b/Longest Consecutive Sequence - Leetcode 128/Longest Consecutive Sequence - Leetcode 128.py @@ -3,7 +3,7 @@ def longestConsecutive(self, nums: List[int]) -> int: s = set(nums) longest = 0 - for num in nums: + for num in s: if num - 1 not in s: next_num = num + 1 length = 1 diff --git a/Longest Increasing Subsequence - Leetcode 300/Longest Increasing Subsequence - Leetcode 300.cpp b/Longest Increasing Subsequence - Leetcode 300/Longest Increasing Subsequence - Leetcode 300.cpp new file mode 100644 index 0000000..77c76be --- /dev/null +++ b/Longest Increasing Subsequence - Leetcode 300/Longest Increasing Subsequence - Leetcode 300.cpp @@ -0,0 +1,21 @@ +#include +#include +using namespace std; + +class Solution { +public: + int lengthOfLIS(vector& nums) { + int n = nums.size(); + vector dp(n, 1); + + for (int i = 1; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + dp[i] = max(dp[i], dp[j] + 1); + } + } + } + + return *max_element(dp.begin(), dp.end()); + } +}; diff --git a/Longest Increasing Subsequence - Leetcode 300/Longest Increasing Subsequence - Leetcode 300.java b/Longest Increasing Subsequence - Leetcode 300/Longest Increasing Subsequence - Leetcode 300.java new file mode 100644 index 0000000..97cca0f --- /dev/null +++ b/Longest Increasing Subsequence - Leetcode 300/Longest Increasing Subsequence - Leetcode 300.java @@ -0,0 +1,22 @@ +public class Solution { + public int lengthOfLIS(int[] nums) { + int n = nums.length; + int[] dp = new int[n]; + java.util.Arrays.fill(dp, 1); + + for (int i = 1; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + } + + int maxLength = 0; + for (int length : dp) { + maxLength = Math.max(maxLength, length); + } + + return maxLength; + } +} diff --git a/Longest Increasing Subsequence - Leetcode 300/Longest Increasing Subsequence - Leetcode 300.js b/Longest Increasing Subsequence - Leetcode 300/Longest Increasing Subsequence - Leetcode 300.js new file mode 100644 index 0000000..c9a1d36 --- /dev/null +++ b/Longest Increasing Subsequence - Leetcode 300/Longest Increasing Subsequence - Leetcode 300.js @@ -0,0 +1,14 @@ +var lengthOfLIS = function(nums) { + const n = nums.length; + const dp = new Array(n).fill(1); + + for (let i = 1; i < n; i++) { + for (let j = 0; j < i; j++) { + if (nums[i] > nums[j]) { + dp[i] = Math.max(dp[i], dp[j] + 1); + } + } + } + + return Math.max(...dp); +}; diff --git a/Longest Increasing Subsequence - Leetcode 300/Longest Increasing Subsequence - Leetcode 300.py b/Longest Increasing Subsequence - Leetcode 300/Longest Increasing Subsequence - Leetcode 300.py new file mode 100644 index 0000000..d9f8d29 --- /dev/null +++ b/Longest Increasing Subsequence - Leetcode 300/Longest Increasing Subsequence - Leetcode 300.py @@ -0,0 +1,15 @@ +class Solution: + def lengthOfLIS(self, nums: List[int]) -> int: + # Bottom Up DP (Tabulation) + # Time: O(n^2) + # Space: O(n) + + n = len(nums) + dp = [1] * n + + for i in range(1, n): + for j in range(i): + if nums[i] > nums[j]: + dp[i] = max(dp[i], dp[j] + 1) + + return max(dp) diff --git a/Longest Repeating Character Replacement - Leetcode 424/Longest Repeating Character Replacement - Leetcode 424.cpp b/Longest Repeating Character Replacement - Leetcode 424/Longest Repeating Character Replacement - Leetcode 424.cpp new file mode 100644 index 0000000..a60c7b2 --- /dev/null +++ b/Longest Repeating Character Replacement - Leetcode 424/Longest Repeating Character Replacement - Leetcode 424.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int characterReplacement(string s, int k) { + vector counts(26, 0); + int l = 0, longest = 0, maxCount = 0; + + for (int r = 0; r < s.size(); r++) { + maxCount = max(maxCount, ++counts[s[r] - 'A']); + + while ((r - l + 1) - maxCount > k) { + counts[s[l] - 'A']--; + l++; + } + + longest = max(longest, r - l + 1); + } + + return longest; + } +}; diff --git a/Longest Repeating Character Replacement - Leetcode 424/Longest Repeating Character Replacement - Leetcode 424.java b/Longest Repeating Character Replacement - Leetcode 424/Longest Repeating Character Replacement - Leetcode 424.java new file mode 100644 index 0000000..c27e74f --- /dev/null +++ b/Longest Repeating Character Replacement - Leetcode 424/Longest Repeating Character Replacement - Leetcode 424.java @@ -0,0 +1,20 @@ +public class Solution { + public int characterReplacement(String s, int k) { + int[] counts = new int[26]; + int l = 0, longest = 0; + int maxCount = 0; + + for (int r = 0; r < s.length(); r++) { + maxCount = Math.max(maxCount, ++counts[s.charAt(r) - 'A']); + + while ((r - l + 1) - maxCount > k) { + counts[s.charAt(l) - 'A']--; + l++; + } + + longest = Math.max(longest, r - l + 1); + } + + return longest; + } +} diff --git a/Longest Repeating Character Replacement - Leetcode 424/Longest Repeating Character Replacement - Leetcode 424.js b/Longest Repeating Character Replacement - Leetcode 424/Longest Repeating Character Replacement - Leetcode 424.js new file mode 100644 index 0000000..281cc51 --- /dev/null +++ b/Longest Repeating Character Replacement - Leetcode 424/Longest Repeating Character Replacement - Leetcode 424.js @@ -0,0 +1,17 @@ +var characterReplacement = function(s, k) { + const counts = new Array(26).fill(0); + let l = 0, longest = 0, maxCount = 0; + + for (let r = 0; r < s.length; r++) { + maxCount = Math.max(maxCount, ++counts[s.charCodeAt(r) - 65]); + + while ((r - l + 1) - maxCount > k) { + counts[s.charCodeAt(l) - 65]--; + l++; + } + + longest = Math.max(longest, r - l + 1); + } + + return longest; +}; diff --git a/Longest Repeating Character Replacement - Leetcode 424.py b/Longest Repeating Character Replacement - Leetcode 424/Longest Repeating Character Replacement - Leetcode 424.py similarity index 100% rename from Longest Repeating Character Replacement - Leetcode 424.py rename to Longest Repeating Character Replacement - Leetcode 424/Longest Repeating Character Replacement - Leetcode 424.py diff --git a/Longest Substring Without Repeating Characters - Leetcode 3/Longest Substring Without Repeating Characters - Leetcode 3.cpp b/Longest Substring Without Repeating Characters - Leetcode 3/Longest Substring Without Repeating Characters - Leetcode 3.cpp new file mode 100644 index 0000000..1932b34 --- /dev/null +++ b/Longest Substring Without Repeating Characters - Leetcode 3/Longest Substring Without Repeating Characters - Leetcode 3.cpp @@ -0,0 +1,47 @@ +#include +#include +using namespace std; + + + +class Solution { +public: + int lengthOfLongestSubstring(const string s) { + + int longest = 0; + + for (auto i = 0; i < s.size(); ++i) { + for (auto substr_len = 1; i + substr_len <= s.size(); ++substr_len) { + unordered_set seen{s.cbegin() + i, s.cbegin() + i + substr_len}; + if (seen.size() == substr_len) + longest = max(longest, substr_len); + } + } + + return longest; + } +}; +// Time Complexity: O(n^3) +// Space Complexity: O(n) + + + +class Solution { +public: + int lengthOfLongestSubstring(string s) { + unordered_set set; + int l = 0, longest = 0; + + for (int r = 0; r < s.size(); r++) { + while (set.find(s[r]) != set.end()) { + set.erase(s[l]); + l++; + } + + longest = max(longest, r - l + 1); + set.insert(s[r]); + } + + return longest; + } +}; diff --git a/Longest Substring Without Repeating Characters - Leetcode 3/Longest Substring Without Repeating Characters - Leetcode 3.java b/Longest Substring Without Repeating Characters - Leetcode 3/Longest Substring Without Repeating Characters - Leetcode 3.java new file mode 100644 index 0000000..1fdaaac --- /dev/null +++ b/Longest Substring Without Repeating Characters - Leetcode 3/Longest Substring Without Repeating Characters - Leetcode 3.java @@ -0,0 +1,46 @@ +import java.util.HashSet; + + +// brute force +// Time Complexity: O(n^3) +// Space Complexity: O(n) +public class Solution { + public int lengthOfLongestSubstring(String s) { + int longest = 0; + int n = s.length(); + for (int i = 0; i < n; i++) { + for (int substr_len = 1; i + substr_len <= n; ++substr_len) { + HashSet seen = new HashSet<>(); + for (int j = i; j < i + substr_len; ++j) + seen.add(s.charAt(j)); + + if (seen.size() == substr_len) + longest = Math.max(longest, substr_len); + } + } + + return longest; + } +} + + + + +public class Solution { + public int lengthOfLongestSubstring(String s) { + HashSet set = new HashSet<>(); + int l = 0, longest = 0; + + for (int r = 0; r < s.length(); r++) { + while (set.contains(s.charAt(r))) { + set.remove(s.charAt(l)); + l++; + } + + longest = Math.max(longest, r - l + 1); + set.add(s.charAt(r)); + } + + return longest; + } +} diff --git a/Longest Substring Without Repeating Characters - Leetcode 3/Longest Substring Without Repeating Characters - Leetcode 3.js b/Longest Substring Without Repeating Characters - Leetcode 3/Longest Substring Without Repeating Characters - Leetcode 3.js new file mode 100644 index 0000000..499fccf --- /dev/null +++ b/Longest Substring Without Repeating Characters - Leetcode 3/Longest Substring Without Repeating Characters - Leetcode 3.js @@ -0,0 +1,39 @@ +// brute force +// Time Complexity: O(n^3) +// Space Complexity: O(n) +var lengthOfLongestSubstring = function(s) { + + let longest = 0; + let n = s.length; + for (let i = 0; i < n; ++i) { + for (let substr_len = 1; i + substr_len <= n; ++substr_len) { + var seen = new Set(); + for (let j = i; j < i + substr_len; ++j) { + seen.add(s[j]); + } + if (seen.size == substr_len) { + longest = Math.max(longest, substr_len); + } + } + } + + return longest; +}; + + +var lengthOfLongestSubstring = function(s) { + const set = new Set(); + let l = 0, longest = 0; + + for (let r = 0; r < s.length; r++) { + while (set.has(s[r])) { + set.delete(s[l]); + l++; + } + + longest = Math.max(longest, r - l + 1); + set.add(s[r]); + } + + return longest; +}; diff --git a/Longest Substring Without Repeating Characters - Leetcode 3.py b/Longest Substring Without Repeating Characters - Leetcode 3/Longest Substring Without Repeating Characters - Leetcode 3.py similarity index 57% rename from Longest Substring Without Repeating Characters - Leetcode 3.py rename to Longest Substring Without Repeating Characters - Leetcode 3/Longest Substring Without Repeating Characters - Leetcode 3.py index ee06243..52010ff 100644 --- a/Longest Substring Without Repeating Characters - Leetcode 3.py +++ b/Longest Substring Without Repeating Characters - Leetcode 3/Longest Substring Without Repeating Characters - Leetcode 3.py @@ -1,3 +1,17 @@ +# Brute Force +def length_of_longest_substring(s: str) -> int: + max_length = 0 + + for i in range(len(s)): + for j in range(i, len(s)): + if s[j] in s[i:j]: # Check if the character already appeared in the substring + break + max_length = max(max_length, j - i + 1) + + return max_length + # Time: O(n^3) + # Space: O(n) + class Solution: def lengthOfLongestSubstring(self, s: str) -> int: l = 0 diff --git a/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235.cpp b/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235.cpp new file mode 100644 index 0000000..2782bad --- /dev/null +++ b/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + TreeNode* lca = root; + + while (root != nullptr) { + if (root->val < p->val && root->val < q->val) { + root = root->right; + } else if (root->val > p->val && root->val > q->val) { + root = root->left; + } else { + lca = root; + break; + } + } + + return lca; + } +}; diff --git a/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235.java b/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235.java new file mode 100644 index 0000000..259ed41 --- /dev/null +++ b/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235.java @@ -0,0 +1,18 @@ +public class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + TreeNode lca = root; + + while (root != null) { + if (root.val < p.val && root.val < q.val) { + root = root.right; + } else if (root.val > p.val && root.val > q.val) { + root = root.left; + } else { + lca = root; + break; + } + } + + return lca; + } +} diff --git a/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235.js b/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235.js new file mode 100644 index 0000000..5795eb4 --- /dev/null +++ b/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235.js @@ -0,0 +1,16 @@ +var lowestCommonAncestor = function(root, p, q) { + let lca = root; + + while (root !== null) { + if (root.val < p.val && root.val < q.val) { + root = root.right; + } else if (root.val > p.val && root.val > q.val) { + root = root.left; + } else { + lca = root; + break; + } + } + + return lca; +}; diff --git a/Lowest Common Ancestor of a Binary Tree - Leetcode 235.py b/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235.py similarity index 100% rename from Lowest Common Ancestor of a Binary Tree - Leetcode 235.py rename to Lowest Common Ancestor of a Binary Search Tree - Leetcode 235/Lowest Common Ancestor of a Binary Search Tree - Leetcode 235.py diff --git a/Majority Element - Leetcode 169/Majority Element - Leetcode 169.cpp b/Majority Element - Leetcode 169/Majority Element - Leetcode 169.cpp new file mode 100644 index 0000000..f4e9384 --- /dev/null +++ b/Majority Element - Leetcode 169/Majority Element - Leetcode 169.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int majorityElement(vector& nums) { + int candidate = nums[0]; + int count = 0; + + for (int num : nums) { + if (count == 0) { + candidate = num; + } + count += (candidate == num) ? 1 : -1; + } + + return candidate; + } +}; diff --git a/Majority Element - Leetcode 169/Majority Element - Leetcode 169.java b/Majority Element - Leetcode 169/Majority Element - Leetcode 169.java new file mode 100644 index 0000000..adbe88b --- /dev/null +++ b/Majority Element - Leetcode 169/Majority Element - Leetcode 169.java @@ -0,0 +1,15 @@ +public class Solution { + public int majorityElement(int[] nums) { + int candidate = nums[0]; + int count = 0; + + for (int num : nums) { + if (count == 0) { + candidate = num; + } + count += (candidate == num) ? 1 : -1; + } + + return candidate; + } +} diff --git a/Majority Element - Leetcode 169/Majority Element - Leetcode 169.js b/Majority Element - Leetcode 169/Majority Element - Leetcode 169.js new file mode 100644 index 0000000..d975d6b --- /dev/null +++ b/Majority Element - Leetcode 169/Majority Element - Leetcode 169.js @@ -0,0 +1,13 @@ +var majorityElement = function(nums) { + let candidate = nums[0]; + let count = 0; + + for (const num of nums) { + if (count === 0) { + candidate = num; + } + count += (candidate === num) ? 1 : -1; + } + + return candidate; +}; diff --git a/Majority Element - Leetcode 169/Majority Element - Leetcode 169.py b/Majority Element - Leetcode 169/Majority Element - Leetcode 169.py new file mode 100644 index 0000000..9c238e8 --- /dev/null +++ b/Majority Element - Leetcode 169/Majority Element - Leetcode 169.py @@ -0,0 +1,35 @@ +class Solution: + def majorityElement(self, nums): + counter = {} + for num in nums: + if num in counter: + counter[num] += 1 + else: + counter[num] = 1 + + max_count = -1 + ans = -1 + for key, val in counter.items(): + if val > max_count: + max_count = val + ans = key + + return ans + # Time: O(n) + # Space: O(n) + + +class Solution: + def majorityElement(self, nums: List[int]) -> int: + candidate = None + count = 0 + + for num in nums: + if count == 0: + candidate = num + + count += 1 if candidate == num else -1 + + return candidate + # Time: O(n) + # Space: O(1) diff --git a/Max Area of Island - Leetcode 695/Max Area of Island - Leetcode 695.cpp b/Max Area of Island - Leetcode 695/Max Area of Island - Leetcode 695.cpp new file mode 100644 index 0000000..7eb1c3c --- /dev/null +++ b/Max Area of Island - Leetcode 695/Max Area of Island - Leetcode 695.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int maxAreaOfIsland(vector>& grid) { + int m = grid.size(); + int n = grid[0].size(); + int maxArea = 0; + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == 1) { + maxArea = max(maxArea, dfs(grid, i, j)); + } + } + } + + return maxArea; + } + +private: + int dfs(vector>& grid, int i, int j) { + // Directions for moving in the grid (right, left, down, up) + static const vector> directions = { + {0, 1}, {0, -1}, {1, 0}, {-1, 0} + }; + + if (i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] != 1) { + return 0; + } + + grid[i][j] = 0; // Mark as visited + int area = 1; + for (const auto& dir : directions) { + int ni = i + dir.first; + int nj = j + dir.second; + area += dfs(grid, ni, nj); + } + return area; + } +}; diff --git a/Max Area of Island - Leetcode 695/Max Area of Island - Leetcode 695.java b/Max Area of Island - Leetcode 695/Max Area of Island - Leetcode 695.java new file mode 100644 index 0000000..7c0f307 --- /dev/null +++ b/Max Area of Island - Leetcode 695/Max Area of Island - Leetcode 695.java @@ -0,0 +1,30 @@ +class Solution { + public int maxAreaOfIsland(int[][] grid) { + int m = grid.length; + int n = grid[0].length; + int maxArea = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + maxArea = Math.max(maxArea, dfs(grid, i, j)); + } + } + } + + return maxArea; + } + + private int dfs(int[][] grid, int i, int j) { + if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != 1) { + return 0; + } + grid[i][j] = 0; // Mark as visited + int area = 1; + area += dfs(grid, i + 1, j); // Down + area += dfs(grid, i - 1, j); // Up + area += dfs(grid, i, j + 1); // Right + area += dfs(grid, i, j - 1); // Left + return area; + } +} diff --git a/Max Area of Island - Leetcode 695/Max Area of Island - Leetcode 695.js b/Max Area of Island - Leetcode 695/Max Area of Island - Leetcode 695.js new file mode 100644 index 0000000..7843f2b --- /dev/null +++ b/Max Area of Island - Leetcode 695/Max Area of Island - Leetcode 695.js @@ -0,0 +1,31 @@ +var maxAreaOfIsland = function(grid) { + const m = grid.length; + const n = grid[0].length; + let maxArea = 0; + + const directions = [0, 1, 0, -1, 0]; // directions for moving right, down, left, up + + function dfs(i, j) { + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] !== 1) { + return 0; + } + grid[i][j] = 0; // mark as visited + let area = 1; + for (let d = 0; d < 4; d++) { + const ni = i + directions[d]; + const nj = j + directions[d + 1]; + area += dfs(ni, nj); + } + return area; + } + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 1) { + maxArea = Math.max(maxArea, dfs(i, j)); + } + } + } + + return maxArea; +}; diff --git a/Max Area of Island - Leetcode 695.py b/Max Area of Island - Leetcode 695/Max Area of Island - Leetcode 695.py similarity index 100% rename from Max Area of Island - Leetcode 695.py rename to Max Area of Island - Leetcode 695/Max Area of Island - Leetcode 695.py diff --git a/Max Consecutive Ones III - Leetcode 1004/Max Consecutive Ones III - Leetcode 1004.cpp b/Max Consecutive Ones III - Leetcode 1004/Max Consecutive Ones III - Leetcode 1004.cpp new file mode 100644 index 0000000..1db0634 --- /dev/null +++ b/Max Consecutive Ones III - Leetcode 1004/Max Consecutive Ones III - Leetcode 1004.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + int longestOnes(vector& nums, int k) { + int max_w = 0; + int num_zeros = 0; + int l = 0; + + for (int r = 0; r < nums.size(); ++r) { + if (nums[r] == 0) { + num_zeros++; + } + + while (num_zeros > k) { + if (nums[l] == 0) { + num_zeros--; + } + l++; + } + + max_w = max(max_w, r - l + 1); + } + + return max_w; + } +}; diff --git a/Max Consecutive Ones III - Leetcode 1004/Max Consecutive Ones III - Leetcode 1004.java b/Max Consecutive Ones III - Leetcode 1004/Max Consecutive Ones III - Leetcode 1004.java new file mode 100644 index 0000000..fd0c8f7 --- /dev/null +++ b/Max Consecutive Ones III - Leetcode 1004/Max Consecutive Ones III - Leetcode 1004.java @@ -0,0 +1,24 @@ +class Solution { + public int longestOnes(int[] nums, int k) { + int maxLength = 0; + int zeroCount = 0; + int left = 0; + + for (int right = 0; right < nums.length; right++) { + if (nums[right] == 0) { + zeroCount++; + } + + while (zeroCount > k) { + if (nums[left] == 0) { + zeroCount--; + } + left++; + } + + maxLength = Math.max(maxLength, right - left + 1); + } + + return maxLength; + } +} diff --git a/Max Consecutive Ones III - Leetcode 1004/Max Consecutive Ones III - Leetcode 1004.js b/Max Consecutive Ones III - Leetcode 1004/Max Consecutive Ones III - Leetcode 1004.js new file mode 100644 index 0000000..35277c1 --- /dev/null +++ b/Max Consecutive Ones III - Leetcode 1004/Max Consecutive Ones III - Leetcode 1004.js @@ -0,0 +1,22 @@ +var longestOnes = function(nums, k) { + let maxLength = 0; + let zeroCount = 0; + let left = 0; + + for (let right = 0; right < nums.length; right++) { + if (nums[right] === 0) { + zeroCount++; + } + + while (zeroCount > k) { + if (nums[left] === 0) { + zeroCount--; + } + left++; + } + + maxLength = Math.max(maxLength, right - left + 1); + } + + return maxLength; +}; diff --git a/Max Consecutive Ones III - Leetcode 1004.py b/Max Consecutive Ones III - Leetcode 1004/Max Consecutive Ones III - Leetcode 1004.py similarity index 100% rename from Max Consecutive Ones III - Leetcode 1004.py rename to Max Consecutive Ones III - Leetcode 1004/Max Consecutive Ones III - Leetcode 1004.py diff --git a/Max Consecutive Ones III - Leetcode 1004/brute force.cpp b/Max Consecutive Ones III - Leetcode 1004/brute force.cpp new file mode 100644 index 0000000..3a8c72c --- /dev/null +++ b/Max Consecutive Ones III - Leetcode 1004/brute force.cpp @@ -0,0 +1,29 @@ +class Solution { +public: + int longestOnes(vector& nums, int k) { + int n = nums.size(); + int maxLen = 0; + + // Iterate over all starting points of subarrays + for (int i = 0; i < n; ++i) { + + // Check each subarray starting from `i` + for (int j = i; j < n; ++j) { + int zeroCount = 0; + for (int c = i; c <= j; ++c) { + if (nums[c] == 0) + zeroCount++; + } + + // If the number of zeroes exceeds k, + // update the maximum length + if (zeroCount <= k) { + maxLen = max(maxLen, j - i + 1); + } + + } + } + + return maxLen; + } +}; diff --git a/Max Consecutive Ones III - Leetcode 1004/brute force.java b/Max Consecutive Ones III - Leetcode 1004/brute force.java new file mode 100644 index 0000000..1df7076 --- /dev/null +++ b/Max Consecutive Ones III - Leetcode 1004/brute force.java @@ -0,0 +1,27 @@ +public class Solution { + public int longestOnes(int[] nums, int k) { + int maxLength = 0; + + // Iterate over all starting points + for (int i = 0; i < nums.length; i++) { + + // Iterate over all possible subarrays starting from i + for (int j = i; j < nums.length; j++) { + + int zeroCount = 0; + for (int c = i; c <= j; ++c) { + if (nums[c] == 0) + ++zeroCount; + } + + // Update maxLength if this subarray is valid + if (zeroCount <= k) { + maxLength = Math.max(maxLength, j - i + 1); + } + + } + } + + return maxLength; + } +} diff --git a/Max Consecutive Ones III - Leetcode 1004/brute force.js b/Max Consecutive Ones III - Leetcode 1004/brute force.js new file mode 100644 index 0000000..cd743b2 --- /dev/null +++ b/Max Consecutive Ones III - Leetcode 1004/brute force.js @@ -0,0 +1,30 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var longestOnes = function(nums, k) { + let maxLength = 0; + + // Iterate over all starting points + for (let i = 0; i < nums.length; i++) { + + // Iterate over all possible subarrays starting from i + for (let j = i; j < nums.length; j++) { + let zeroCount = 0; + for (let c = i; c <= j; ++c) { + if (nums[c] == 0) + ++zeroCount; + } + + // If the number of zeroes exceeds k, + // update the maximum length + if (zeroCount <= k) { + maxLength = Math.max(maxLength, j - i + 1); + } + + } + } + + return maxLength; +}; diff --git a/Max Consecutive Ones III - Leetcode 1004/brute force.py b/Max Consecutive Ones III - Leetcode 1004/brute force.py new file mode 100644 index 0000000..be6b73d --- /dev/null +++ b/Max Consecutive Ones III - Leetcode 1004/brute force.py @@ -0,0 +1,19 @@ +class Solution(object): + def longestOnes(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: int + """ + longest_ones = 0 + + # Iterate over all starting points + for i in range(len(nums)): + + # Iterate over all possible subarrays starting from i + for j in range(i + 1, len(nums) + 1): + window_len = j - i + num_zeros = nums[i:j].count(0) # O(k) operation + if num_zeros <= k: + longest_ones = max(longest_ones, window_len) + return longest_ones diff --git a/Maximum Average Subarray I - Leetcode 643/Maximum Average Subarray I - Leetcode 643.cpp b/Maximum Average Subarray I - Leetcode 643/Maximum Average Subarray I - Leetcode 643.cpp new file mode 100644 index 0000000..3dc7370 --- /dev/null +++ b/Maximum Average Subarray I - Leetcode 643/Maximum Average Subarray I - Leetcode 643.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + double findMaxAverage(vector& nums, int k) { + int n = nums.size(); + double cur_sum = 0; + + for (int i = 0; i < k; ++i) { + cur_sum += nums[i]; + } + + double max_avg = cur_sum / k; + + for (int i = k; i < n; ++i) { + cur_sum += nums[i]; + cur_sum -= nums[i - k]; + + double avg = cur_sum / k; + max_avg = max(max_avg, avg); + } + + return max_avg; + } +}; diff --git a/Maximum Average Subarray I - Leetcode 643/Maximum Average Subarray I - Leetcode 643.java b/Maximum Average Subarray I - Leetcode 643/Maximum Average Subarray I - Leetcode 643.java new file mode 100644 index 0000000..f0b087c --- /dev/null +++ b/Maximum Average Subarray I - Leetcode 643/Maximum Average Subarray I - Leetcode 643.java @@ -0,0 +1,22 @@ +class Solution { + public double findMaxAverage(int[] nums, int k) { + int n = nums.length; + double curSum = 0; + + for (int i = 0; i < k; i++) { + curSum += nums[i]; + } + + double maxAvg = curSum / k; + + for (int i = k; i < n; i++) { + curSum += nums[i]; + curSum -= nums[i - k]; + + double avg = curSum / k; + maxAvg = Math.max(maxAvg, avg); + } + + return maxAvg; + } +} diff --git a/Maximum Average Subarray I - Leetcode 643/Maximum Average Subarray I - Leetcode 643.js b/Maximum Average Subarray I - Leetcode 643/Maximum Average Subarray I - Leetcode 643.js new file mode 100644 index 0000000..6dfb069 --- /dev/null +++ b/Maximum Average Subarray I - Leetcode 643/Maximum Average Subarray I - Leetcode 643.js @@ -0,0 +1,19 @@ +var findMaxAverage = function(nums, k) { + let curSum = 0; + + for (let i = 0; i < k; i++) { + curSum += nums[i]; + } + + let maxAvg = curSum / k; + + for (let i = k; i < nums.length; i++) { + curSum += nums[i]; + curSum -= nums[i - k]; + + let avg = curSum / k; + maxAvg = Math.max(maxAvg, avg); + } + + return maxAvg; +}; diff --git a/Maximum Average Subarray I - Leetcode 643.py b/Maximum Average Subarray I - Leetcode 643/Maximum Average Subarray I - Leetcode 643.py similarity index 100% rename from Maximum Average Subarray I - Leetcode 643.py rename to Maximum Average Subarray I - Leetcode 643/Maximum Average Subarray I - Leetcode 643.py diff --git a/Maximum Average Subarray I - Leetcode 643/brute force.cpp b/Maximum Average Subarray I - Leetcode 643/brute force.cpp new file mode 100644 index 0000000..e399fe5 --- /dev/null +++ b/Maximum Average Subarray I - Leetcode 643/brute force.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + double findMaxAverage(const vector& nums, int k) { + double max_avg = 0; + + // setting max_avg to any constant numeric value + // here is incorrect!!! + // So initialize it with some values from the input + for (int i = 0; i < k; ++i) + max_avg += nums[i]; + max_avg /= k; + + for (int i = 0; i <= nums.size() - k; ++i) { + double avg = 0; + for (int j = i; j < i + k; ++j) + avg += nums[j]; + avg /= k; + max_avg = max(max_avg, avg); + } + return max_avg; + } +}; diff --git a/Maximum Average Subarray I - Leetcode 643/brute force.java b/Maximum Average Subarray I - Leetcode 643/brute force.java new file mode 100644 index 0000000..6dfd656 --- /dev/null +++ b/Maximum Average Subarray I - Leetcode 643/brute force.java @@ -0,0 +1,22 @@ +class Solution { + public double findMaxAverage(int[] nums, int k) { + double max_avg = 0; + + // setting max_avg to any constant numeric value + // here is incorrect!!! + // So initialize it with some values from the input + for (int i = 0; i < k; ++i) + max_avg += nums[i]; + max_avg /= k; + + for (int i = 0; i <= nums.length - k; ++i) { + double avg = 0; + for (int j = i; j < i + k; ++j) + avg += nums[j]; + avg /= k; + max_avg = Math.max(max_avg, avg); + } + return max_avg; + + } +} diff --git a/Maximum Average Subarray I - Leetcode 643/brute force.js b/Maximum Average Subarray I - Leetcode 643/brute force.js new file mode 100644 index 0000000..07469e7 --- /dev/null +++ b/Maximum Average Subarray I - Leetcode 643/brute force.js @@ -0,0 +1,22 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number} + */ +var findMaxAverage = function(nums, k) { + const avg = (vals, start, len) => { + let sum = 0; + for (let i = start; i < start + len; i++) { + sum += vals[i]; + } + return sum / len; + }; + + // Calculate initial maximum average + let maxAvg = avg(nums, 0, k); + for (let i = 0; i <= nums.length - k; i++) { + maxAvg = Math.max(maxAvg, avg(nums, i, k)); + } + + return maxAvg; +}; diff --git a/Maximum Average Subarray I - Leetcode 643/brute force.py b/Maximum Average Subarray I - Leetcode 643/brute force.py new file mode 100644 index 0000000..1de4fbf --- /dev/null +++ b/Maximum Average Subarray I - Leetcode 643/brute force.py @@ -0,0 +1,20 @@ +class Solution(object): + def findMaxAverage(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: float + """ + + def avg(vals): + return sum(vals) / float(len(vals)) + + # Note, setting max_avg to any constant numeric value + # here is incorrect!!! + # Say 0, if nums = [-1, -2, -3, -4], k = 2, + # the output would be incorrect + max_avg = avg(nums[:k]) + for i in range(len(nums) - k + 1): + max_avg = max(max_avg, avg(nums[i:i+k])) # avg is O(k) + return max_avg + diff --git a/Maximum Depth of Binary Tree - Leetcode 104.py b/Maximum Depth of Binary Tree - Leetcode 104.py deleted file mode 100644 index 061c10f..0000000 --- a/Maximum Depth of Binary Tree - Leetcode 104.py +++ /dev/null @@ -1,12 +0,0 @@ -class Solution: - def maxDepth(self, root: Optional[TreeNode]) -> int: - if not root: - return 0 - - left = self.maxDepth(root.left) - right = self.maxDepth(root.right) - - return 1 + max(left, right) - -# Time Complexity: O(n) -# Space Complexity: O(h) { here "h" is the height of the binary tree } diff --git a/Maximum Depth of Binary Tree - Leetcode 104/Maximum Depth of Binary Tree - Leetcode 104.cpp b/Maximum Depth of Binary Tree - Leetcode 104/Maximum Depth of Binary Tree - Leetcode 104.cpp new file mode 100644 index 0000000..f6f3698 --- /dev/null +++ b/Maximum Depth of Binary Tree - Leetcode 104/Maximum Depth of Binary Tree - Leetcode 104.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int maxDepth(TreeNode* root) { + if (!root) return 0; + + int left = maxDepth(root->left); + int right = maxDepth(root->right); + + return 1 + max(left, right); + } +}; diff --git a/Maximum Depth of Binary Tree - Leetcode 104/Maximum Depth of Binary Tree - Leetcode 104.java b/Maximum Depth of Binary Tree - Leetcode 104/Maximum Depth of Binary Tree - Leetcode 104.java new file mode 100644 index 0000000..5426c03 --- /dev/null +++ b/Maximum Depth of Binary Tree - Leetcode 104/Maximum Depth of Binary Tree - Leetcode 104.java @@ -0,0 +1,10 @@ +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) return 0; + + int left = maxDepth(root.left); + int right = maxDepth(root.right); + + return 1 + Math.max(left, right); + } +} diff --git a/Maximum Depth of Binary Tree - Leetcode 104/Maximum Depth of Binary Tree - Leetcode 104.js b/Maximum Depth of Binary Tree - Leetcode 104/Maximum Depth of Binary Tree - Leetcode 104.js new file mode 100644 index 0000000..979d07c --- /dev/null +++ b/Maximum Depth of Binary Tree - Leetcode 104/Maximum Depth of Binary Tree - Leetcode 104.js @@ -0,0 +1,8 @@ +var maxDepth = function(root) { + if (root === null) return 0; + + const left = maxDepth(root.left); + const right = maxDepth(root.right); + + return 1 + Math.max(left, right); +}; diff --git a/Maximum Depth of Binary Tree - Leetcode 104/Maximum Depth of Binary Tree - Leetcode 104.py b/Maximum Depth of Binary Tree - Leetcode 104/Maximum Depth of Binary Tree - Leetcode 104.py new file mode 100644 index 0000000..9cf4d38 --- /dev/null +++ b/Maximum Depth of Binary Tree - Leetcode 104/Maximum Depth of Binary Tree - Leetcode 104.py @@ -0,0 +1,38 @@ +# DFS +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + + left = self.maxDepth(root.left) + right = self.maxDepth(root.right) + + return 1 + max(left, right) + +# Time Complexity: O(n) +# Space Complexity: O(h) { here "h" is the height of the binary tree } + +# BFS +class Solution: + def maxDepth(self, root): + if not root: + return 0 # Height of an empty tree is 0 + + queue = deque([root]) + height = 0 + + while queue: + level_size = len(queue) # Number of nodes at the current level + + for _ in range(level_size): + node = queue.popleft() + if node.left: + queue.append(node.left) + if node.right: + queue.append(node.right) + + height += 1 # Increment height at each level + + return height + # Time Complexity: O(n) + # Space Complexity: O(n) diff --git a/Maximum Number of Balloons - Leetcode 1189/Maximum Number of Balloons - Leetcode 1189.cpp b/Maximum Number of Balloons - Leetcode 1189/Maximum Number of Balloons - Leetcode 1189.cpp new file mode 100644 index 0000000..35eac0e --- /dev/null +++ b/Maximum Number of Balloons - Leetcode 1189/Maximum Number of Balloons - Leetcode 1189.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int maxNumberOfBalloons(string text) { + unordered_map counter; + string balloon = "balloon"; + + for (char c : text) { + if (balloon.find(c) != string::npos) { + counter[c]++; + } + } + + if (counter.find('b') == counter.end() || + counter.find('a') == counter.end() || + counter.find('l') == counter.end() || + counter.find('o') == counter.end() || + counter.find('n') == counter.end()) { + return 0; + } else { + return min({counter['b'], counter['a'], counter['l'] / 2, counter['o'] / 2, counter['n']}); + } + } +}; diff --git a/Maximum Number of Balloons - Leetcode 1189/Maximum Number of Balloons - Leetcode 1189.java b/Maximum Number of Balloons - Leetcode 1189/Maximum Number of Balloons - Leetcode 1189.java new file mode 100644 index 0000000..4c48376 --- /dev/null +++ b/Maximum Number of Balloons - Leetcode 1189/Maximum Number of Balloons - Leetcode 1189.java @@ -0,0 +1,27 @@ +import java.util.HashMap; +import java.util.Map; + +class Solution { + public int maxNumberOfBalloons(String text) { + Map counter = new HashMap<>(); + String balloon = "balloon"; + + for (char c : text.toCharArray()) { + if (balloon.indexOf(c) != -1) { + counter.put(c, counter.getOrDefault(c, 0) + 1); + } + } + + if (!counter.containsKey('b') || + !counter.containsKey('a') || + !counter.containsKey('l') || + !counter.containsKey('o') || + !counter.containsKey('n')) { + return 0; + } else { + return Math.min(Math.min(counter.get('b'), counter.get('a')), + Math.min(counter.get('l') / 2, + Math.min(counter.get('o') / 2, counter.get('n')))); + } + } +} diff --git a/Maximum Number of Balloons - Leetcode 1189/Maximum Number of Balloons - Leetcode 1189.js b/Maximum Number of Balloons - Leetcode 1189/Maximum Number of Balloons - Leetcode 1189.js new file mode 100644 index 0000000..ce75eb7 --- /dev/null +++ b/Maximum Number of Balloons - Leetcode 1189/Maximum Number of Balloons - Leetcode 1189.js @@ -0,0 +1,20 @@ +var maxNumberOfBalloons = function(text) { + const counter = {}; + const balloon = "balloon"; + + for (const c of text) { + if (balloon.includes(c)) { + counter[c] = (counter[c] || 0) + 1; + } + } + + if (!('b' in counter) || + !('a' in counter) || + !('l' in counter) || + !('o' in counter) || + !('n' in counter)) { + return 0; + } else { + return Math.min(counter['b'], counter['a'], Math.floor(counter['l'] / 2), Math.floor(counter['o'] / 2), counter['n']); + } +}; diff --git a/Maximum Number of Balloons - Leetcode 1189.py b/Maximum Number of Balloons - Leetcode 1189/Maximum Number of Balloons - Leetcode 1189.py similarity index 100% rename from Maximum Number of Balloons - Leetcode 1189.py rename to Maximum Number of Balloons - Leetcode 1189/Maximum Number of Balloons - Leetcode 1189.py diff --git a/Maximum Subarray - Leetcode 53/Maximum Subarray - Leetcode 53.cpp b/Maximum Subarray - Leetcode 53/Maximum Subarray - Leetcode 53.cpp new file mode 100644 index 0000000..4a00d4b --- /dev/null +++ b/Maximum Subarray - Leetcode 53/Maximum Subarray - Leetcode 53.cpp @@ -0,0 +1,22 @@ +#include +#include +using namespace std; + +class Solution { +public: + int maxSubArray(vector& nums) { + int max_sum = INT_MIN; + int curr_sum = 0; + + for (int num : nums) { + curr_sum += num; + max_sum = max(max_sum, curr_sum); + + if (curr_sum < 0) { + curr_sum = 0; + } + } + + return max_sum; + } +}; diff --git a/Maximum Subarray - Leetcode 53/Maximum Subarray - Leetcode 53.java b/Maximum Subarray - Leetcode 53/Maximum Subarray - Leetcode 53.java new file mode 100644 index 0000000..a49e573 --- /dev/null +++ b/Maximum Subarray - Leetcode 53/Maximum Subarray - Leetcode 53.java @@ -0,0 +1,17 @@ +public class Solution { + public int maxSubArray(int[] nums) { + int maxSum = Integer.MIN_VALUE; + int currSum = 0; + + for (int num : nums) { + currSum += num; + maxSum = Math.max(maxSum, currSum); + + if (currSum < 0) { + currSum = 0; + } + } + + return maxSum; + } +} diff --git a/Maximum Subarray - Leetcode 53/Maximum Subarray - Leetcode 53.js b/Maximum Subarray - Leetcode 53/Maximum Subarray - Leetcode 53.js new file mode 100644 index 0000000..38c350b --- /dev/null +++ b/Maximum Subarray - Leetcode 53/Maximum Subarray - Leetcode 53.js @@ -0,0 +1,15 @@ +var maxSubArray = function(nums) { + let maxSum = -Infinity; + let currSum = 0; + + for (const num of nums) { + currSum += num; + maxSum = Math.max(maxSum, currSum); + + if (currSum < 0) { + currSum = 0; + } + } + + return maxSum; +}; diff --git a/Maximum Subarray - Leetcode 53/Maximum Subarray - Leetcode 53.py b/Maximum Subarray - Leetcode 53/Maximum Subarray - Leetcode 53.py new file mode 100644 index 0000000..0e1ab07 --- /dev/null +++ b/Maximum Subarray - Leetcode 53/Maximum Subarray - Leetcode 53.py @@ -0,0 +1,16 @@ +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + # Bottom Up DP (Constant Space) + # Time: O(n) + # Space: O(1) + max_sum = float('-inf') + curr_sum = 0 + + for i in range(len(nums)): + curr_sum += nums[i] + max_sum = max(max_sum, curr_sum) + + if curr_sum < 0: + curr_sum = 0 + + return max_sum diff --git a/Merge Intervals - Leetcode 56/Merge Intervals - Leetcode 56.cpp b/Merge Intervals - Leetcode 56/Merge Intervals - Leetcode 56.cpp new file mode 100644 index 0000000..89cf699 --- /dev/null +++ b/Merge Intervals - Leetcode 56/Merge Intervals - Leetcode 56.cpp @@ -0,0 +1,28 @@ +#include +#include +using namespace std; + +class Solution { +public: + vector> merge(vector>& intervals) { + if (intervals.empty()) return {}; + + // Sort intervals based on the starting time + sort(intervals.begin(), intervals.end(), [](const vector& a, const vector& b) { + return a[0] < b[0]; + }); + + vector> merged; + for (const auto& interval : intervals) { + // If the merged list is empty or there is no overlap + if (merged.empty() || merged.back()[1] < interval[0]) { + merged.push_back(interval); + } else { + // There is overlap, merge the intervals + merged.back()[1] = max(merged.back()[1], interval[1]); + } + } + + return merged; + } +}; diff --git a/Merge Intervals - Leetcode 56/Merge Intervals - Leetcode 56.java b/Merge Intervals - Leetcode 56/Merge Intervals - Leetcode 56.java new file mode 100644 index 0000000..9cf210c --- /dev/null +++ b/Merge Intervals - Leetcode 56/Merge Intervals - Leetcode 56.java @@ -0,0 +1,23 @@ +import java.util.*; + +public class Solution { + public int[][] merge(int[][] intervals) { + if (intervals.length == 0) return new int[0][0]; + + // Sort intervals based on the starting time + Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); + + List merged = new ArrayList<>(); + for (int[] interval : intervals) { + // If the merged list is empty or there is no overlap + if (merged.isEmpty() || merged.get(merged.size() - 1)[1] < interval[0]) { + merged.add(interval); + } else { + // There is overlap, merge the intervals + merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], interval[1]); + } + } + + return merged.toArray(new int[merged.size()][]); + } +} diff --git a/Merge Intervals - Leetcode 56/Merge Intervals - Leetcode 56.js b/Merge Intervals - Leetcode 56/Merge Intervals - Leetcode 56.js new file mode 100644 index 0000000..87c4a70 --- /dev/null +++ b/Merge Intervals - Leetcode 56/Merge Intervals - Leetcode 56.js @@ -0,0 +1,19 @@ +var merge = function(intervals) { + if (intervals.length === 0) return []; + + // Sort intervals based on the starting time + intervals.sort((a, b) => a[0] - b[0]); + + const merged = []; + for (const interval of intervals) { + // If the merged list is empty or there is no overlap + if (merged.length === 0 || merged[merged.length - 1][1] < interval[0]) { + merged.push(interval); + } else { + // There is overlap, merge the intervals + merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1]); + } + } + + return merged; +}; diff --git a/Merge Intervals - Leetcode 56/Merge Intervals - Leetcode 56.py b/Merge Intervals - Leetcode 56/Merge Intervals - Leetcode 56.py new file mode 100644 index 0000000..b94f8ac --- /dev/null +++ b/Merge Intervals - Leetcode 56/Merge Intervals - Leetcode 56.py @@ -0,0 +1,34 @@ +class Solution: + def merge(self, intervals: List[List[int]]) -> List[List[int]]: + intervals.sort(key=lambda interval: interval[0]) + merged = [] + + for interval in intervals: + if not merged or merged[-1][1] < interval[0]: + merged.append(interval) + else: + merged[-1] = [merged[-1][0], max(merged[-1][1], interval[1])] + + return merged + # Time: O(n log n) + # Space: O(n) + + +class Solution: + def merge(self, intervals: List[List[int]]) -> List[List[int]]: + intervals.sort(key=lambda x: x[0]) # Sort by start time + i = 0 # Index to track merged intervals + n = len(intervals) + + for j in range(1, n): + # Check if the current interval overlaps with the previous one + if intervals[i][1] >= intervals[j][0]: + intervals[i][1] = max(intervals[i][1], intervals[j][1]) # Merge + else: + i += 1 + intervals[i] = intervals[j] # Move next non-overlapping interval + + return intervals[:i+1] # Return the relevant merged portion + + # Time: O(n log n) + # Space: O(1) diff --git a/Merge Sorted Array - Leetcode 88/Merge Sorted Array - Leetcode 88.cpp b/Merge Sorted Array - Leetcode 88/Merge Sorted Array - Leetcode 88.cpp new file mode 100644 index 0000000..976c5ca --- /dev/null +++ b/Merge Sorted Array - Leetcode 88/Merge Sorted Array - Leetcode 88.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + int x = m - 1, y = n - 1; + + for (int z = m + n - 1; z >= 0; z--) { + if (x < 0) { + nums1[z] = nums2[y--]; + } else if (y < 0) { + break; + } else if (nums1[x] > nums2[y]) { + nums1[z] = nums1[x--]; + } else { + nums1[z] = nums2[y--]; + } + } + } +}; diff --git a/Merge Sorted Array - Leetcode 88/Merge Sorted Array - Leetcode 88.java b/Merge Sorted Array - Leetcode 88/Merge Sorted Array - Leetcode 88.java new file mode 100644 index 0000000..bdfe564 --- /dev/null +++ b/Merge Sorted Array - Leetcode 88/Merge Sorted Array - Leetcode 88.java @@ -0,0 +1,17 @@ +class Solution { + public void merge(int[] nums1, int m, int[] nums2, int n) { + int x = m - 1, y = n - 1; + + for (int z = m + n - 1; z >= 0; z--) { + if (x < 0) { + nums1[z] = nums2[y--]; + } else if (y < 0) { + break; + } else if (nums1[x] > nums2[y]) { + nums1[z] = nums1[x--]; + } else { + nums1[z] = nums2[y--]; + } + } + } +} diff --git a/Merge Sorted Array - Leetcode 88/Merge Sorted Array - Leetcode 88.js b/Merge Sorted Array - Leetcode 88/Merge Sorted Array - Leetcode 88.js new file mode 100644 index 0000000..63f6dc0 --- /dev/null +++ b/Merge Sorted Array - Leetcode 88/Merge Sorted Array - Leetcode 88.js @@ -0,0 +1,15 @@ +var merge = function(nums1, m, nums2, n) { + let x = m - 1, y = n - 1; + + for (let z = m + n - 1; z >= 0; z--) { + if (x < 0) { + nums1[z] = nums2[y--]; + } else if (y < 0) { + break; + } else if (nums1[x] > nums2[y]) { + nums1[z] = nums1[x--]; + } else { + nums1[z] = nums2[y--]; + } + } +}; diff --git a/Merge Sorted Array - Leetcode 88/Merge Sorted Array - Leetcode 88.py b/Merge Sorted Array - Leetcode 88/Merge Sorted Array - Leetcode 88.py new file mode 100644 index 0000000..a2859b6 --- /dev/null +++ b/Merge Sorted Array - Leetcode 88/Merge Sorted Array - Leetcode 88.py @@ -0,0 +1,22 @@ +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + """ + Do not return anything, modify nums1 in-place instead. + """ + x, y = m-1, n-1 + + for z in range(m + n - 1, -1, -1): + if x < 0: + nums1[z] = nums2[y] + y -= 1 + elif y < 0: + break + elif nums1[x] > nums2[y]: + nums1[z] = nums1[x] + x -= 1 + else: + nums1[z] = nums2[y] + y -= 1 + + # Time: O(n + m) + # Space: O(1) \ No newline at end of file diff --git a/Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.cpp b/Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.cpp new file mode 100644 index 0000000..ec41a3c --- /dev/null +++ b/Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.cpp @@ -0,0 +1,26 @@ +#include +using namespace std; + +class Solution { +public: + string mergeAlternately(string word1, string word2) { + int A = word1.size(), B = word2.size(); + int a = 0, b = 0; + string result; + + while (a < A && b < B) { + result += word1[a++]; + result += word2[b++]; + } + + while (a < A) { + result += word1[a++]; + } + + while (b < B) { + result += word2[b++]; + } + + return result; + } +}; diff --git a/Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.java b/Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.java new file mode 100644 index 0000000..c5ad300 --- /dev/null +++ b/Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.java @@ -0,0 +1,22 @@ +public class Solution { + public String mergeAlternately(String word1, String word2) { + int A = word1.length(), B = word2.length(); + int a = 0, b = 0; + StringBuilder result = new StringBuilder(); + + while (a < A && b < B) { + result.append(word1.charAt(a++)); + result.append(word2.charAt(b++)); + } + + while (a < A) { + result.append(word1.charAt(a++)); + } + + while (b < B) { + result.append(word2.charAt(b++)); + } + + return result.toString(); + } +} diff --git a/Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.js b/Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.js new file mode 100644 index 0000000..2d0562f --- /dev/null +++ b/Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.js @@ -0,0 +1,20 @@ +var mergeAlternately = function(word1, word2) { + let A = word1.length, B = word2.length; + let a = 0, b = 0; + let result = ''; + + while (a < A && b < B) { + result += word1[a++]; + result += word2[b++]; + } + + while (a < A) { + result += word1[a++]; + } + + while (b < B) { + result += word2[b++]; + } + + return result; +}; diff --git a/Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.py b/Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.py new file mode 100644 index 0000000..ac9a73d --- /dev/null +++ b/Merge Strings Alternately - Leetcode 1768/Merge Strings Alternately - Leetcode 1768.py @@ -0,0 +1,67 @@ +# Brute Force Solution +class Solution: + def mergeAlternately(self, word1: str, word2: str) -> str: + characters = "" + cur_word = 1 + a, b = 0, 0 + + while a < len(word1) and b < len(word2): + if cur_word == 1: + characters += word1[a] + a += 1 + cur_word = 2 + else: + characters += word2[b] + b += 1 + cur_word = 1 + + while a < len(word1): + characters += word1[a] + a += 1 + + while b < len(word2): + characters += word2[b] + b += 1 + + return characters + # Let A be the length of Word1 + # Let B be the length of Word2 + # Let T = A + B + + # Time: O(T^2) + # Space: O(T) + + +# Optimal Solution +class Solution: + def mergeAlternately(self, word1: str, word2: str) -> str: + A, B = len(word1), len(word2) + a, b = 0, 0 + s = [] + + word = 1 + while a < A and b < B: + if word == 1: + s.append(word1[a]) + a += 1 + word = 2 + else: + s.append(word2[b]) + b += 1 + word = 1 + + while a < A: + s.append(word1[a]) + a += 1 + + while b < B: + s.append(word2[b]) + b += 1 + + return ''.join(s) + # Let A be the length of Word1 + # Let B be the length of Word2 + # Let T = A + B + + # Time: O(T) + # Space: O(T) diff --git a/Merge Two Sorted Lists - Leetcode 21/Merge Two Sorted Lists - Leetcode 21.cpp b/Merge Two Sorted Lists - Leetcode 21/Merge Two Sorted Lists - Leetcode 21.cpp new file mode 100644 index 0000000..d1fc500 --- /dev/null +++ b/Merge Two Sorted Lists - Leetcode 21/Merge Two Sorted Lists - Leetcode 21.cpp @@ -0,0 +1,26 @@ +#include +using namespace std; + + +class Solution { +public: + ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { + ListNode dummy(0); + ListNode* cur = &dummy; + + while (list1 && list2) { + if (list1->val < list2->val) { + cur->next = list1; + list1 = list1->next; + } else { + cur->next = list2; + list2 = list2->next; + } + cur = cur->next; + } + + cur->next = list1 ? list1 : list2; + + return dummy.next; + } +}; diff --git a/Merge Two Sorted Lists - Leetcode 21/Merge Two Sorted Lists - Leetcode 21.java b/Merge Two Sorted Lists - Leetcode 21/Merge Two Sorted Lists - Leetcode 21.java new file mode 100644 index 0000000..8e6eeed --- /dev/null +++ b/Merge Two Sorted Lists - Leetcode 21/Merge Two Sorted Lists - Leetcode 21.java @@ -0,0 +1,21 @@ +public class Solution { + public ListNode mergeTwoLists(ListNode list1, ListNode list2) { + ListNode dummy = new ListNode(0); + ListNode cur = dummy; + + while (list1 != null && list2 != null) { + if (list1.val < list2.val) { + cur.next = list1; + list1 = list1.next; + } else { + cur.next = list2; + list2 = list2.next; + } + cur = cur.next; + } + + cur.next = list1 != null ? list1 : list2; + + return dummy.next; + } +} diff --git a/Merge Two Sorted Lists - Leetcode 21/Merge Two Sorted Lists - Leetcode 21.js b/Merge Two Sorted Lists - Leetcode 21/Merge Two Sorted Lists - Leetcode 21.js new file mode 100644 index 0000000..5cf94cf --- /dev/null +++ b/Merge Two Sorted Lists - Leetcode 21/Merge Two Sorted Lists - Leetcode 21.js @@ -0,0 +1,19 @@ +var mergeTwoLists = function(list1, list2) { + let dummy = new ListNode(0); + let cur = dummy; + + while (list1 !== null && list2 !== null) { + if (list1.val < list2.val) { + cur.next = list1; + list1 = list1.next; + } else { + cur.next = list2; + list2 = list2.next; + } + cur = cur.next; + } + + cur.next = list1 !== null ? list1 : list2; + + return dummy.next; +}; diff --git a/Merge Two Sorted Lists - Leetcode 21.py b/Merge Two Sorted Lists - Leetcode 21/Merge Two Sorted Lists - Leetcode 21.py similarity index 100% rename from Merge Two Sorted Lists - Leetcode 21.py rename to Merge Two Sorted Lists - Leetcode 21/Merge Two Sorted Lists - Leetcode 21.py diff --git a/Merge k Sorted (Linked) Lists - Leetcode 23/Merge k Sorted (Linked) Lists - Leetcode 23.cpp b/Merge k Sorted (Linked) Lists - Leetcode 23/Merge k Sorted (Linked) Lists - Leetcode 23.cpp new file mode 100644 index 0000000..9ebec07 --- /dev/null +++ b/Merge k Sorted (Linked) Lists - Leetcode 23/Merge k Sorted (Linked) Lists - Leetcode 23.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + + +class Solution { +public: + ListNode* mergeKLists(vector& lists) { + auto cmp = [](ListNode* a, ListNode* b) { + return a->val > b->val; + }; + priority_queue, decltype(cmp)> minHeap(cmp); + + // Add the initial nodes of each list to the heap + for (ListNode* node : lists) { + if (node) { + minHeap.push(node); + } + } + + ListNode dummy(0); + ListNode* cur = &dummy; + + while (!minHeap.empty()) { + ListNode* node = minHeap.top(); + minHeap.pop(); + cur->next = node; + cur = node; + if (node->next) { + minHeap.push(node->next); + } + } + + return dummy.next; + } +}; diff --git a/Merge k Sorted (Linked) Lists - Leetcode 23/Merge k Sorted (Linked) Lists - Leetcode 23.java b/Merge k Sorted (Linked) Lists - Leetcode 23/Merge k Sorted (Linked) Lists - Leetcode 23.java new file mode 100644 index 0000000..21bfd33 --- /dev/null +++ b/Merge k Sorted (Linked) Lists - Leetcode 23/Merge k Sorted (Linked) Lists - Leetcode 23.java @@ -0,0 +1,29 @@ +import java.util.PriorityQueue; + + +public class Solution { + public ListNode mergeKLists(ListNode[] lists) { + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val)); + + // Add the initial nodes of each list to the heap + for (ListNode node : lists) { + if (node != null) { + minHeap.offer(node); + } + } + + ListNode dummy = new ListNode(0); + ListNode cur = dummy; + + while (!minHeap.isEmpty()) { + ListNode node = minHeap.poll(); + cur.next = node; + cur = node; + if (node.next != null) { + minHeap.offer(node.next); + } + } + + return dummy.next; + } +} diff --git a/Merge k Sorted (Linked) Lists - Leetcode 23/Merge k Sorted (Linked) Lists - Leetcode 23.js b/Merge k Sorted (Linked) Lists - Leetcode 23/Merge k Sorted (Linked) Lists - Leetcode 23.js new file mode 100644 index 0000000..6b0b5f8 --- /dev/null +++ b/Merge k Sorted (Linked) Lists - Leetcode 23/Merge k Sorted (Linked) Lists - Leetcode 23.js @@ -0,0 +1,90 @@ +var mergeKLists = function(lists) { + const heap = new MinHeap((a, b) => a.val - b.val); + + // Add the initial nodes of each list to the heap + for (let node of lists) { + if (node) { + heap.push(node); + } + } + + let dummy = new ListNode(0); + let cur = dummy; + + while (heap.size() > 0) { + let node = heap.pop(); + cur.next = node; + cur = node; + if (node.next) { + heap.push(node.next); + } + } + + return dummy.next; +}; + +// MinHeap implementation +class MinHeap { + constructor(compare) { + this.heap = []; + this.compare = compare; + } + + push(item) { + this.heap.push(item); + this.bubbleUp(this.heap.length - 1); + } + + pop() { + const top = this.heap[0]; + const end = this.heap.pop(); + if (this.heap.length > 0) { + this.heap[0] = end; + this.bubbleDown(0); + } + return top; + } + + size() { + return this.heap.length; + } + + bubbleUp(index) { + const item = this.heap[index]; + while (index > 0) { + const parentIndex = Math.floor((index - 1) / 2); + const parent = this.heap[parentIndex]; + if (this.compare(item, parent) >= 0) break; + this.heap[index] = parent; + index = parentIndex; + } + this.heap[index] = item; + } + + bubbleDown(index) { + const length = this.heap.length; + const item = this.heap[index]; + while (true) { + const leftChildIndex = 2 * index + 1; + const rightChildIndex = 2 * index + 2; + let swap = null; + if (leftChildIndex < length) { + const leftChild = this.heap[leftChildIndex]; + if (this.compare(leftChild, item) < 0) { + swap = leftChildIndex; + } + } + if (rightChildIndex < length) { + const rightChild = this.heap[rightChildIndex]; + if ((swap === null && this.compare(rightChild, item) < 0) || + (swap !== null && this.compare(rightChild, this.heap[swap]) < 0)) { + swap = rightChildIndex; + } + } + if (swap === null) break; + this.heap[index] = this.heap[swap]; + index = swap; + } + this.heap[index] = item; + } +} diff --git a/Merge k Sorted (Linked) Lists - Leetcode 23/Merge k Sorted (Linked) Lists - Leetcode 23.py b/Merge k Sorted (Linked) Lists - Leetcode 23/Merge k Sorted (Linked) Lists - Leetcode 23.py new file mode 100644 index 0000000..b219b83 --- /dev/null +++ b/Merge k Sorted (Linked) Lists - Leetcode 23/Merge k Sorted (Linked) Lists - Leetcode 23.py @@ -0,0 +1,28 @@ +import heapq +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: + heap = [] + for i, node in enumerate(lists): + if node: + heapq.heappush(heap, (node.val, i, node)) + + D = ListNode() + cur = D + + # n log k + while heap: + val, i, node = heapq.heappop(heap) + cur.next = node + cur = node + node = node.next + if node: + heapq.heappush(heap, (node.val, i, node)) + + return D.next + # Time: O(N log K) + # Space: O(K) diff --git a/Middle of the Linked List - Leetcode 876/Middle of the Linked List - Leetcode 876.cpp b/Middle of the Linked List - Leetcode 876/Middle of the Linked List - Leetcode 876.cpp new file mode 100644 index 0000000..c479630 --- /dev/null +++ b/Middle of the Linked List - Leetcode 876/Middle of the Linked List - Leetcode 876.cpp @@ -0,0 +1,18 @@ +#include +using namespace std; + + +class Solution { +public: + ListNode* middleNode(ListNode* head) { + ListNode* slow = head; + ListNode* fast = head; + + while (fast && fast->next) { + fast = fast->next->next; + slow = slow->next; + } + + return slow; + } +}; diff --git a/Middle of the Linked List - Leetcode 876/Middle of the Linked List - Leetcode 876.java b/Middle of the Linked List - Leetcode 876/Middle of the Linked List - Leetcode 876.java new file mode 100644 index 0000000..5de430b --- /dev/null +++ b/Middle of the Linked List - Leetcode 876/Middle of the Linked List - Leetcode 876.java @@ -0,0 +1,13 @@ +public class Solution { + public ListNode middleNode(ListNode head) { + ListNode slow = head; + ListNode fast = head; + + while (fast != null && fast.next != null) { + fast = fast.next.next; + slow = slow.next; + } + + return slow; + } +} diff --git a/Middle of the Linked List - Leetcode 876/Middle of the Linked List - Leetcode 876.js b/Middle of the Linked List - Leetcode 876/Middle of the Linked List - Leetcode 876.js new file mode 100644 index 0000000..8e000f6 --- /dev/null +++ b/Middle of the Linked List - Leetcode 876/Middle of the Linked List - Leetcode 876.js @@ -0,0 +1,11 @@ +var middleNode = function(head) { + let slow = head; + let fast = head; + + while (fast !== null && fast.next !== null) { + fast = fast.next.next; + slow = slow.next; + } + + return slow; +}; diff --git a/Middle of the Linked List - Leetcode 876.py b/Middle of the Linked List - Leetcode 876/Middle of the Linked List - Leetcode 876.py similarity index 100% rename from Middle of the Linked List - Leetcode 876.py rename to Middle of the Linked List - Leetcode 876/Middle of the Linked List - Leetcode 876.py diff --git a/Min Cost Climbing Stairs - Leetcode 746/Min Cost Climbing Stairs - Leetcode 746.cpp b/Min Cost Climbing Stairs - Leetcode 746/Min Cost Climbing Stairs - Leetcode 746.cpp new file mode 100644 index 0000000..8ddaf60 --- /dev/null +++ b/Min Cost Climbing Stairs - Leetcode 746/Min Cost Climbing Stairs - Leetcode 746.cpp @@ -0,0 +1,19 @@ +#include +#include +using namespace std; + +class Solution { +public: + int minCostClimbingStairs(vector& cost) { + int n = cost.size(); + int prev = 0, curr = 0; + + for (int i = 2; i <= n; ++i) { + int next = min(cost[i - 2] + prev, cost[i - 1] + curr); + prev = curr; + curr = next; + } + + return curr; + } +}; diff --git a/Min Cost Climbing Stairs - Leetcode 746/Min Cost Climbing Stairs - Leetcode 746.java b/Min Cost Climbing Stairs - Leetcode 746/Min Cost Climbing Stairs - Leetcode 746.java new file mode 100644 index 0000000..575a84b --- /dev/null +++ b/Min Cost Climbing Stairs - Leetcode 746/Min Cost Climbing Stairs - Leetcode 746.java @@ -0,0 +1,14 @@ +public class Solution { + public int minCostClimbingStairs(int[] cost) { + int n = cost.length; + int prev = 0, curr = 0; + + for (int i = 2; i <= n; i++) { + int next = Math.min(cost[i - 2] + prev, cost[i - 1] + curr); + prev = curr; + curr = next; + } + + return curr; + } +} diff --git a/Min Cost Climbing Stairs - Leetcode 746/Min Cost Climbing Stairs - Leetcode 746.js b/Min Cost Climbing Stairs - Leetcode 746/Min Cost Climbing Stairs - Leetcode 746.js new file mode 100644 index 0000000..b29987a --- /dev/null +++ b/Min Cost Climbing Stairs - Leetcode 746/Min Cost Climbing Stairs - Leetcode 746.js @@ -0,0 +1,12 @@ +var minCostClimbingStairs = function(cost) { + let n = cost.length; + let prev = 0, curr = 0; + + for (let i = 2; i <= n; i++) { + let next = Math.min(cost[i - 2] + prev, cost[i - 1] + curr); + prev = curr; + curr = next; + } + + return curr; +}; diff --git a/Min Cost Climbing Stairs - Leetcode 746.py b/Min Cost Climbing Stairs - Leetcode 746/Min Cost Climbing Stairs - Leetcode 746.py similarity index 100% rename from Min Cost Climbing Stairs - Leetcode 746.py rename to Min Cost Climbing Stairs - Leetcode 746/Min Cost Climbing Stairs - Leetcode 746.py diff --git a/Min Cost to Connect All Points - Leetcode 1584/Min Cost to Connect All Points - Leetcode 1584.cpp b/Min Cost to Connect All Points - Leetcode 1584/Min Cost to Connect All Points - Leetcode 1584.cpp new file mode 100644 index 0000000..9a1dc7a --- /dev/null +++ b/Min Cost to Connect All Points - Leetcode 1584/Min Cost to Connect All Points - Leetcode 1584.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + int minCostConnectPoints(vector>& points) { + int n = points.size(); + int totalCost = 0; + vector visited(n, false); + priority_queue, vector>, greater>> minHeap; + minHeap.push({0, 0}); // cost, pointIndex + + while (!minHeap.empty()) { + auto edge = minHeap.top(); + minHeap.pop(); + int cost = edge[0]; + int point = edge[1]; + + if (visited[point]) continue; + + visited[point] = true; + totalCost += cost; + + for (int i = 0; i < n; i++) { + if (!visited[i]) { + int newCost = abs(points[point][0] - points[i][0]) + abs(points[point][1] - points[i][1]); + minHeap.push({newCost, i}); + } + } + } + + return totalCost; + } +}; diff --git a/Min Cost to Connect All Points - Leetcode 1584/Min Cost to Connect All Points - Leetcode 1584.java b/Min Cost to Connect All Points - Leetcode 1584/Min Cost to Connect All Points - Leetcode 1584.java new file mode 100644 index 0000000..122b494 --- /dev/null +++ b/Min Cost to Connect All Points - Leetcode 1584/Min Cost to Connect All Points - Leetcode 1584.java @@ -0,0 +1,31 @@ +import java.util.*; + +public class Solution { + public int minCostConnectPoints(int[][] points) { + int n = points.length; + int totalCost = 0; + boolean[] visited = new boolean[n]; + PriorityQueue minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); + minHeap.offer(new int[]{0, 0}); // cost, pointIndex + + while (!minHeap.isEmpty()) { + int[] edge = minHeap.poll(); + int cost = edge[0]; + int point = edge[1]; + + if (visited[point]) continue; + + visited[point] = true; + totalCost += cost; + + for (int i = 0; i < n; i++) { + if (!visited[i]) { + int newCost = Math.abs(points[point][0] - points[i][0]) + Math.abs(points[point][1] - points[i][1]); + minHeap.offer(new int[]{newCost, i}); + } + } + } + + return totalCost; + } +} diff --git a/Min Cost to Connect All Points - Leetcode 1584/Min Cost to Connect All Points - Leetcode 1584.js b/Min Cost to Connect All Points - Leetcode 1584/Min Cost to Connect All Points - Leetcode 1584.js new file mode 100644 index 0000000..13ac655 --- /dev/null +++ b/Min Cost to Connect All Points - Leetcode 1584/Min Cost to Connect All Points - Leetcode 1584.js @@ -0,0 +1,27 @@ +var minCostConnectPoints = function(points) { + const n = points.length; + let totalCost = 0; + const visited = new Array(n).fill(false); + const minHeap = []; + + minHeap.push([0, 0]); // cost, pointIndex + + while (minHeap.length > 0) { + const [cost, point] = minHeap.shift(); + + if (visited[point]) continue; + + visited[point] = true; + totalCost += cost; + + for (let i = 0; i < n; i++) { + if (!visited[i]) { + const newCost = Math.abs(points[point][0] - points[i][0]) + Math.abs(points[point][1] - points[i][1]); + minHeap.push([newCost, i]); + minHeap.sort((a, b) => a[0] - b[0]); // Maintain min-heap property + } + } + } + + return totalCost; +}; diff --git a/Min Cost to Connect All Points - Leetcode 1584.py b/Min Cost to Connect All Points - Leetcode 1584/Min Cost to Connect All Points - Leetcode 1584.py similarity index 100% rename from Min Cost to Connect All Points - Leetcode 1584.py rename to Min Cost to Connect All Points - Leetcode 1584/Min Cost to Connect All Points - Leetcode 1584.py diff --git a/Min Stack - Leetcode 155/Min Stack - Leetcode 155.cpp b/Min Stack - Leetcode 155/Min Stack - Leetcode 155.cpp new file mode 100644 index 0000000..9b47db8 --- /dev/null +++ b/Min Stack - Leetcode 155/Min Stack - Leetcode 155.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; + +class MinStack { +public: + MinStack() {} + + void push(int val) { + stk.push(val); + if (minStk.empty() || val <= minStk.top()) { + minStk.push(val); + } else { + minStk.push(minStk.top()); + } + } + + void pop() { + stk.pop(); + minStk.pop(); + } + + int top() { + return stk.top(); + } + + int getMin() { + return minStk.top(); + } + +private: + stack stk; + stack minStk; +}; diff --git a/Min Stack - Leetcode 155/Min Stack - Leetcode 155.java b/Min Stack - Leetcode 155/Min Stack - Leetcode 155.java new file mode 100644 index 0000000..b5bab75 --- /dev/null +++ b/Min Stack - Leetcode 155/Min Stack - Leetcode 155.java @@ -0,0 +1,33 @@ +import java.util.Stack; + +public class MinStack { + private Stack stack; + private Stack minStack; + + public MinStack() { + stack = new Stack<>(); + minStack = new Stack<>(); + } + + public void push(int val) { + stack.push(val); + if (minStack.isEmpty() || val <= minStack.peek()) { + minStack.push(val); + } else { + minStack.push(minStack.peek()); + } + } + + public void pop() { + stack.pop(); + minStack.pop(); + } + + public int top() { + return stack.peek(); + } + + public int getMin() { + return minStack.peek(); + } +} diff --git a/Min Stack - Leetcode 155/Min Stack - Leetcode 155.js b/Min Stack - Leetcode 155/Min Stack - Leetcode 155.js new file mode 100644 index 0000000..53d19fc --- /dev/null +++ b/Min Stack - Leetcode 155/Min Stack - Leetcode 155.js @@ -0,0 +1,28 @@ +class MinStack { + constructor() { + this.stk = []; + this.minStk = []; + } + + push(val) { + this.stk.push(val); + if (this.minStk.length === 0 || val <= this.minStk[this.minStk.length - 1]) { + this.minStk.push(val); + } else { + this.minStk.push(this.minStk[this.minStk.length - 1]); + } + } + + pop() { + this.stk.pop(); + this.minStk.pop(); + } + + top() { + return this.stk[this.stk.length - 1]; + } + + getMin() { + return this.minStk[this.minStk.length - 1]; + } +} diff --git a/Min Stack - Leetcode 155.py b/Min Stack - Leetcode 155/Min Stack - Leetcode 155.py similarity index 100% rename from Min Stack - Leetcode 155.py rename to Min Stack - Leetcode 155/Min Stack - Leetcode 155.py diff --git a/Minimum Absolute Difference in BST - Leetcode 530/Minimum Absolute Difference in BST - Leetcode 530.cpp b/Minimum Absolute Difference in BST - Leetcode 530/Minimum Absolute Difference in BST - Leetcode 530.cpp new file mode 100644 index 0000000..acef07c --- /dev/null +++ b/Minimum Absolute Difference in BST - Leetcode 530/Minimum Absolute Difference in BST - Leetcode 530.cpp @@ -0,0 +1,35 @@ +#include + +class Solution { +public: + int getMinimumDifference(TreeNode* root) { + prev = nullptr; + minDiff = INT_MAX; + inOrderTraversal(root); + return minDiff; + } + +private: + TreeNode* prev; + int minDiff; + + void inOrderTraversal(TreeNode* node) { + if (node == nullptr) { + return; + } + + // Traverse left subtree + inOrderTraversal(node->left); + + // Compute the minimum difference + if (prev != nullptr) { + minDiff = std::min(minDiff, node->val - prev->val); + } + + // Update previous node + prev = node; + + // Traverse right subtree + inOrderTraversal(node->right); + } +}; diff --git a/Minimum Absolute Difference in BST - Leetcode 530/Minimum Absolute Difference in BST - Leetcode 530.java b/Minimum Absolute Difference in BST - Leetcode 530/Minimum Absolute Difference in BST - Leetcode 530.java new file mode 100644 index 0000000..4920e5a --- /dev/null +++ b/Minimum Absolute Difference in BST - Leetcode 530/Minimum Absolute Difference in BST - Leetcode 530.java @@ -0,0 +1,29 @@ +class Solution { + private TreeNode prev = null; + private int minDiff = Integer.MAX_VALUE; + + public int getMinimumDifference(TreeNode root) { + inOrderTraversal(root); + return minDiff; + } + + private void inOrderTraversal(TreeNode node) { + if (node == null) { + return; + } + + // Traverse the left subtree + inOrderTraversal(node.left); + + // Process the current node + if (prev != null) { + minDiff = Math.min(minDiff, node.val - prev.val); + } + + // Update the previous node to the current node + prev = node; + + // Traverse the right subtree + inOrderTraversal(node.right); + } +} diff --git a/Minimum Absolute Difference in BST - Leetcode 530/Minimum Absolute Difference in BST - Leetcode 530.js b/Minimum Absolute Difference in BST - Leetcode 530/Minimum Absolute Difference in BST - Leetcode 530.js new file mode 100644 index 0000000..531d450 --- /dev/null +++ b/Minimum Absolute Difference in BST - Leetcode 530/Minimum Absolute Difference in BST - Leetcode 530.js @@ -0,0 +1,20 @@ +var getMinimumDifference = function(root) { + let minDifference = Infinity; + let prev = null; + + function dfs(node) { + if (node === null) return; + + dfs(node.left); + + if (prev !== null) { + minDifference = Math.min(minDifference, Math.abs(node.val - prev)); + } + prev = node.val; + + dfs(node.right); + } + + dfs(root); + return minDifference; +}; diff --git a/Minimum Absolute Difference in BST - Leetcode 530/Minimum Absolute Difference in BST - Leetcode 530.py b/Minimum Absolute Difference in BST - Leetcode 530/Minimum Absolute Difference in BST - Leetcode 530.py new file mode 100644 index 0000000..ba6a569 --- /dev/null +++ b/Minimum Absolute Difference in BST - Leetcode 530/Minimum Absolute Difference in BST - Leetcode 530.py @@ -0,0 +1,21 @@ +class Solution: + def getMinimumDifference(self, root: Optional[TreeNode]) -> int: + min_distance = [float('inf')] + prev = [None] + + def dfs(node): + if node is None: + return + + dfs(node.left) + + if prev[0] is not None: + min_distance[0] = min(min_distance[0], node.val - prev[0]) + + prev[0] = node.val + dfs(node.right) + + dfs(root) + return min_distance[0] + # Time: O(n) + # Space: O(n) diff --git a/Minimum Size Subarray Sum - Leetcode 209/Minimum Size Subarray Sum - Leetcode 209.cpp b/Minimum Size Subarray Sum - Leetcode 209/Minimum Size Subarray Sum - Leetcode 209.cpp new file mode 100644 index 0000000..2a78667 --- /dev/null +++ b/Minimum Size Subarray Sum - Leetcode 209/Minimum Size Subarray Sum - Leetcode 209.cpp @@ -0,0 +1,22 @@ +#include +#include +#include + +class Solution { +public: + int minSubArrayLen(int target, std::vector& nums) { + int minLength = INT_MAX; + int sum = 0; + int l = 0; + + for (int r = 0; r < nums.size(); ++r) { + sum += nums[r]; + while (sum >= target) { + minLength = std::min(minLength, r - l + 1); + sum -= nums[l++]; + } + } + + return minLength == INT_MAX ? 0 : minLength; + } +}; diff --git a/Minimum Size Subarray Sum - Leetcode 209/Minimum Size Subarray Sum - Leetcode 209.java b/Minimum Size Subarray Sum - Leetcode 209/Minimum Size Subarray Sum - Leetcode 209.java new file mode 100644 index 0000000..a816b05 --- /dev/null +++ b/Minimum Size Subarray Sum - Leetcode 209/Minimum Size Subarray Sum - Leetcode 209.java @@ -0,0 +1,20 @@ +import java.util.*; + +public class Solution { + public int minSubArrayLen(int target, int[] nums) { + int minLength = Integer.MAX_VALUE; + int sum = 0; + int l = 0; + + for (int r = 0; r < nums.length; r++) { + sum += nums[r]; + while (sum >= target) { + minLength = Math.min(minLength, r - l + 1); + sum -= nums[l]; + l++; + } + } + + return minLength == Integer.MAX_VALUE ? 0 : minLength; + } +} diff --git a/Minimum Size Subarray Sum - Leetcode 209/Minimum Size Subarray Sum - Leetcode 209.js b/Minimum Size Subarray Sum - Leetcode 209/Minimum Size Subarray Sum - Leetcode 209.js new file mode 100644 index 0000000..dfa3928 --- /dev/null +++ b/Minimum Size Subarray Sum - Leetcode 209/Minimum Size Subarray Sum - Leetcode 209.js @@ -0,0 +1,15 @@ +var minSubArrayLen = function(target, nums) { + let minLength = Infinity; + let sum = 0; + let l = 0; + + for (let r = 0; r < nums.length; r++) { + sum += nums[r]; + while (sum >= target) { + minLength = Math.min(minLength, r - l + 1); + sum -= nums[l++]; + } + } + + return minLength === Infinity ? 0 : minLength; +}; diff --git a/Minimum Size Subarray Sum - Leetcode 209/Minimum Size Subarray Sum - Leetcode 209.py b/Minimum Size Subarray Sum - Leetcode 209/Minimum Size Subarray Sum - Leetcode 209.py new file mode 100644 index 0000000..ed736fa --- /dev/null +++ b/Minimum Size Subarray Sum - Leetcode 209/Minimum Size Subarray Sum - Leetcode 209.py @@ -0,0 +1,16 @@ +class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + min_length = float('inf') + summ = 0 + l = 0 + + for r in range(len(nums)): + summ += nums[r] + while summ >= target: + min_length = min(min_length, r-l+1) + summ -= nums[l] + l += 1 + + return min_length if min_length < float('inf') else 0 + # Time: O(n) + # Space: O(1) diff --git a/N-ary Tree Level Order Traversal - Leetcode 429/N-ary Tree Level Order Traversal - Leetcode 429.cpp b/N-ary Tree Level Order Traversal - Leetcode 429/N-ary Tree Level Order Traversal - Leetcode 429.cpp new file mode 100644 index 0000000..accc47c --- /dev/null +++ b/N-ary Tree Level Order Traversal - Leetcode 429/N-ary Tree Level Order Traversal - Leetcode 429.cpp @@ -0,0 +1,30 @@ +#include +#include + +using namespace std; + +class Solution { +public: + vector> levelOrder(Node* root) { + vector> output; + if (!root) return output; + + queue q; + q.push(root); + + while (!q.empty()) { + int n = q.size(); + vector level; + for (int i = 0; i < n; i++) { + Node* node = q.front(); + q.pop(); + level.push_back(node->val); + for (Node* child : node->children) { + q.push(child); + } + } + output.push_back(level); + } + return output; + } +}; diff --git a/N-ary Tree Level Order Traversal - Leetcode 429/N-ary Tree Level Order Traversal - Leetcode 429.java b/N-ary Tree Level Order Traversal - Leetcode 429/N-ary Tree Level Order Traversal - Leetcode 429.java new file mode 100644 index 0000000..2759a8f --- /dev/null +++ b/N-ary Tree Level Order Traversal - Leetcode 429/N-ary Tree Level Order Traversal - Leetcode 429.java @@ -0,0 +1,26 @@ +import java.util.*; + + +class Solution { + public List> levelOrder(Node root) { + List> output = new ArrayList<>(); + if (root == null) return output; + + Queue q = new LinkedList<>(); + q.add(root); + + while (!q.isEmpty()) { + int n = q.size(); + List level = new ArrayList<>(); + for (int i = 0; i < n; i++) { + Node node = q.poll(); + level.add(node.val); + if (node.children != null) { + q.addAll(node.children); + } + } + output.add(level); + } + return output; + } +} diff --git a/N-ary Tree Level Order Traversal - Leetcode 429/N-ary Tree Level Order Traversal - Leetcode 429.js b/N-ary Tree Level Order Traversal - Leetcode 429/N-ary Tree Level Order Traversal - Leetcode 429.js new file mode 100644 index 0000000..5b8adf9 --- /dev/null +++ b/N-ary Tree Level Order Traversal - Leetcode 429/N-ary Tree Level Order Traversal - Leetcode 429.js @@ -0,0 +1,20 @@ +var levelOrder = function(root) { + if (!root) return []; + + let output = []; + let q = [root]; + + while (q.length > 0) { + let n = q.length; + let level = []; + for (let i = 0; i < n; i++) { + let node = q.shift(); + level.push(node.val); + if (node.children) { + q.push(...node.children); + } + } + output.push(level); + } + return output; +}; diff --git a/N-ary Tree Level Order Traversal - Leetcode 429/N-ary Tree Level Order Traversal - Leetcode 429.py b/N-ary Tree Level Order Traversal - Leetcode 429/N-ary Tree Level Order Traversal - Leetcode 429.py new file mode 100644 index 0000000..34fa64d --- /dev/null +++ b/N-ary Tree Level Order Traversal - Leetcode 429/N-ary Tree Level Order Traversal - Leetcode 429.py @@ -0,0 +1,31 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None): + self.val = val + self.children = children +""" + +class Solution: + def levelOrder(self, root: 'Node') -> List[List[int]]: + if not root: + return [] + output = [] + q = deque() + q.append(root) + + while q: + n = len(q) + level = [] + for _ in range(n): + node = q.popleft() + level.append(node.val) + for child in node.children: + q.append(child) + output.append(level) + + return output + + # Time: O(n) + # Space: O(n) + # n is number of nodes in the tree \ No newline at end of file diff --git a/N-ary Tree Preorder Traversal - Leetcode 589/N-ary Tree Preorder Traversal - Leetcode 429.cpp b/N-ary Tree Preorder Traversal - Leetcode 589/N-ary Tree Preorder Traversal - Leetcode 429.cpp new file mode 100644 index 0000000..accc47c --- /dev/null +++ b/N-ary Tree Preorder Traversal - Leetcode 589/N-ary Tree Preorder Traversal - Leetcode 429.cpp @@ -0,0 +1,30 @@ +#include +#include + +using namespace std; + +class Solution { +public: + vector> levelOrder(Node* root) { + vector> output; + if (!root) return output; + + queue q; + q.push(root); + + while (!q.empty()) { + int n = q.size(); + vector level; + for (int i = 0; i < n; i++) { + Node* node = q.front(); + q.pop(); + level.push_back(node->val); + for (Node* child : node->children) { + q.push(child); + } + } + output.push_back(level); + } + return output; + } +}; diff --git a/N-ary Tree Preorder Traversal - Leetcode 589/N-ary Tree Preorder Traversal - Leetcode 429.java b/N-ary Tree Preorder Traversal - Leetcode 589/N-ary Tree Preorder Traversal - Leetcode 429.java new file mode 100644 index 0000000..ac21f6d --- /dev/null +++ b/N-ary Tree Preorder Traversal - Leetcode 589/N-ary Tree Preorder Traversal - Leetcode 429.java @@ -0,0 +1,18 @@ +import java.util.*; + + +class Solution { + public List preorder(Node root) { + List output = new ArrayList<>(); + if (root == null) return output; + dfs(root, output); + return output; + } + + private void dfs(Node node, List output) { + output.add(node.val); + for (Node child : node.children) { + dfs(child, output); + } + } +} diff --git a/N-ary Tree Preorder Traversal - Leetcode 589/N-ary Tree Preorder Traversal - Leetcode 429.js b/N-ary Tree Preorder Traversal - Leetcode 589/N-ary Tree Preorder Traversal - Leetcode 429.js new file mode 100644 index 0000000..b3ae283 --- /dev/null +++ b/N-ary Tree Preorder Traversal - Leetcode 589/N-ary Tree Preorder Traversal - Leetcode 429.js @@ -0,0 +1,15 @@ +var preorder = function(root) { + if (!root) return []; + + let output = []; + + function dfs(node) { + output.push(node.val); + for (let child of node.children) { + dfs(child); + } + } + + dfs(root); + return output; +}; diff --git a/N-ary Tree Preorder Traversal - Leetcode 589/N-ary Tree Preorder Traversal - Leetcode 429.py b/N-ary Tree Preorder Traversal - Leetcode 589/N-ary Tree Preorder Traversal - Leetcode 429.py new file mode 100644 index 0000000..896cfa2 --- /dev/null +++ b/N-ary Tree Preorder Traversal - Leetcode 589/N-ary Tree Preorder Traversal - Leetcode 429.py @@ -0,0 +1,25 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None): + self.val = val + self.children = children +""" + +class Solution: + def preorder(self, root: 'Node') -> List[int]: + if not root: + return [] + + output = [] + def dfs(node): + output.append(node.val) + for child in node.children: + dfs(child) + + dfs(root) + return output + + # Time: O(n) + # Space: O(n) + # n is number of nodes in the tree \ No newline at end of file diff --git a/Network Delay Time - Leetcode 743/Network Delay Time - Leetcode 743.cpp b/Network Delay Time - Leetcode 743/Network Delay Time - Leetcode 743.cpp new file mode 100644 index 0000000..423c388 --- /dev/null +++ b/Network Delay Time - Leetcode 743/Network Delay Time - Leetcode 743.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + int networkDelayTime(vector>& times, int n, int k) { + unordered_map>> graph; + for (const auto& time : times) { + int u = time[0], v = time[1], t = time[2]; + graph[u].emplace_back(v, t); + } + + priority_queue, vector>, greater<>> minHeap; + minHeap.emplace(0, k); + unordered_map minTimes; + + while (!minHeap.empty()) { + auto [currentTime, node] = minHeap.top(); + minHeap.pop(); + + if (minTimes.count(node)) continue; + minTimes[node] = currentTime; + + for (const auto& [neighbor, time] : graph[node]) { + if (!minTimes.count(neighbor)) { + minHeap.emplace(currentTime + time, neighbor); + } + } + } + + if (minTimes.size() == n) { + return max_element(minTimes.begin(), minTimes.end(), + [](const pair& a, const pair& b) { + return a.second < b.second; + })->second; + } else { + return -1; + } + } +}; diff --git a/Network Delay Time - Leetcode 743/Network Delay Time - Leetcode 743.java b/Network Delay Time - Leetcode 743/Network Delay Time - Leetcode 743.java new file mode 100644 index 0000000..f2108d0 --- /dev/null +++ b/Network Delay Time - Leetcode 743/Network Delay Time - Leetcode 743.java @@ -0,0 +1,40 @@ +import java.util.*; + +public class Solution { + public int networkDelayTime(int[][] times, int n, int k) { + Map> graph = new HashMap<>(); + for (int[] time : times) { + int u = time[0], v = time[1], t = time[2]; + graph.computeIfAbsent(u, x -> new ArrayList<>()).add(new int[]{v, t}); + } + + PriorityQueue minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[1])); + minHeap.add(new int[]{k, 0}); + Map minTimes = new HashMap<>(); + + while (!minHeap.isEmpty()) { + int[] current = minHeap.poll(); + int node = current[0]; + int time = current[1]; + + if (minTimes.containsKey(node)) continue; + + minTimes.put(node, time); + if (graph.containsKey(node)) { + for (int[] neighbor : graph.get(node)) { + int nei = neighbor[0]; + int neiTime = neighbor[1]; + if (!minTimes.containsKey(nei)) { + minHeap.add(new int[]{nei, time + neiTime}); + } + } + } + } + + if (minTimes.size() == n) { + return Collections.max(minTimes.values()); + } else { + return -1; + } + } +} diff --git a/Network Delay Time - Leetcode 743/Network Delay Time - Leetcode 743.js b/Network Delay Time - Leetcode 743/Network Delay Time - Leetcode 743.js new file mode 100644 index 0000000..4c76aa6 --- /dev/null +++ b/Network Delay Time - Leetcode 743/Network Delay Time - Leetcode 743.js @@ -0,0 +1,28 @@ +function networkDelayTime(times, n, k) { + const graph = new Map(); + for (const [u, v, time] of times) { + if (!graph.has(u)) graph.set(u, []); + graph.get(u).push([v, time]); + } + + const minHeap = new MinPriorityQueue(); + minHeap.enqueue([k, 0], 0); + const minTimes = new Map(); + + while (!minHeap.isEmpty()) { + const [node, currentTime] = minHeap.dequeue().element; + + if (minTimes.has(node)) continue; + minTimes.set(node, currentTime); + + if (graph.has(node)) { + for (const [neighbor, time] of graph.get(node)) { + if (!minTimes.has(neighbor)) { + minHeap.enqueue([neighbor, currentTime + time], currentTime + time); + } + } + } + } + + return minTimes.size === n ? Math.max(...minTimes.values()) : -1; +} diff --git a/Network Delay Time - Leetcode 743.py b/Network Delay Time - Leetcode 743/Network Delay Time - Leetcode 743.py similarity index 100% rename from Network Delay Time - Leetcode 743.py rename to Network Delay Time - Leetcode 743/Network Delay Time - Leetcode 743.py diff --git a/Number of 1 Bits - Leetcode 191/Number of 1 Bits - Leetcode 191.cpp b/Number of 1 Bits - Leetcode 191/Number of 1 Bits - Leetcode 191.cpp new file mode 100644 index 0000000..27e6f07 --- /dev/null +++ b/Number of 1 Bits - Leetcode 191/Number of 1 Bits - Leetcode 191.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int hammingWeight(uint32_t n) { + int ans = 0; + + while (n != 0) { + ans++; + n &= (n - 1); + } + + return ans; + } +}; diff --git a/Number of 1 Bits - Leetcode 191/Number of 1 Bits - Leetcode 191.java b/Number of 1 Bits - Leetcode 191/Number of 1 Bits - Leetcode 191.java new file mode 100644 index 0000000..3549a55 --- /dev/null +++ b/Number of 1 Bits - Leetcode 191/Number of 1 Bits - Leetcode 191.java @@ -0,0 +1,12 @@ +public class Solution { + public int hammingWeight(int n) { + int ans = 0; + + while (n != 0) { + ans++; + n &= (n - 1); + } + + return ans; + } +} diff --git a/Number of 1 Bits - Leetcode 191/Number of 1 Bits - Leetcode 191.js b/Number of 1 Bits - Leetcode 191/Number of 1 Bits - Leetcode 191.js new file mode 100644 index 0000000..a9a0c61 --- /dev/null +++ b/Number of 1 Bits - Leetcode 191/Number of 1 Bits - Leetcode 191.js @@ -0,0 +1,10 @@ +var hammingWeight = function(n) { + var ans = 0; + + while (n !== 0) { + ans++; + n &= (n - 1); + } + + return ans; +}; diff --git a/Number of 1 Bits - Leetcode 191/Number of 1 Bits - Leetcode 191.py b/Number of 1 Bits - Leetcode 191/Number of 1 Bits - Leetcode 191.py new file mode 100644 index 0000000..ef8d745 --- /dev/null +++ b/Number of 1 Bits - Leetcode 191/Number of 1 Bits - Leetcode 191.py @@ -0,0 +1,10 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + ans = 0 + + while n != 0: + ans += 1 + n = n & (n-1) + + return ans + # Time: O(Bits), Space: O(1) \ No newline at end of file diff --git a/Number of Islands - Leetcode 200/Number of Islands - Leetcode 200.cpp b/Number of Islands - Leetcode 200/Number of Islands - Leetcode 200.cpp new file mode 100644 index 0000000..934bf80 --- /dev/null +++ b/Number of Islands - Leetcode 200/Number of Islands - Leetcode 200.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; + +class Solution { +public: + int numIslands(vector>& grid) { + if (grid.empty() || grid[0].empty()) return 0; + + int m = grid.size(); + int n = grid[0].size(); + int numIslands = 0; + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (grid[i][j] == '1') { + numIslands++; + dfs(grid, i, j); + } + } + } + + return numIslands; + } + +private: + void dfs(vector>& grid, int i, int j) { + int m = grid.size(); + int n = grid[0].size(); + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != '1') return; + grid[i][j] = '0'; + dfs(grid, i, j + 1); + dfs(grid, i + 1, j); + dfs(grid, i, j - 1); + dfs(grid, i - 1, j); + } +}; diff --git a/Number of Islands - Leetcode 200/Number of Islands - Leetcode 200.java b/Number of Islands - Leetcode 200/Number of Islands - Leetcode 200.java new file mode 100644 index 0000000..9133b16 --- /dev/null +++ b/Number of Islands - Leetcode 200/Number of Islands - Leetcode 200.java @@ -0,0 +1,31 @@ +public class Solution { + public int numIslands(char[][] grid) { + if (grid == null || grid.length == 0) return 0; + + int m = grid.length; + int n = grid[0].length; + int numIslands = 0; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == '1') { + numIslands++; + dfs(grid, i, j); + } + } + } + + return numIslands; + } + + private void dfs(char[][] grid, int i, int j) { + int m = grid.length; + int n = grid[0].length; + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != '1') return; + grid[i][j] = '0'; + dfs(grid, i, j + 1); + dfs(grid, i + 1, j); + dfs(grid, i, j - 1); + dfs(grid, i - 1, j); + } +} diff --git a/Number of Islands - Leetcode 200/Number of Islands - Leetcode 200.js b/Number of Islands - Leetcode 200/Number of Islands - Leetcode 200.js new file mode 100644 index 0000000..faccc66 --- /dev/null +++ b/Number of Islands - Leetcode 200/Number of Islands - Leetcode 200.js @@ -0,0 +1,27 @@ +function numIslands(grid) { + if (!grid || grid.length === 0) return 0; + + const m = grid.length; + const n = grid[0].length; + let numIslands = 0; + + function dfs(i, j) { + if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] !== '1') return; + grid[i][j] = '0'; + dfs(i, j + 1); + dfs(i + 1, j); + dfs(i, j - 1); + dfs(i - 1, j); + } + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === '1') { + numIslands++; + dfs(i, j); + } + } + } + + return numIslands; +} diff --git a/Number of Islands - Leetcode 200.py b/Number of Islands - Leetcode 200/Number of Islands - Leetcode 200.py similarity index 100% rename from Number of Islands - Leetcode 200.py rename to Number of Islands - Leetcode 200/Number of Islands - Leetcode 200.py diff --git a/Pacific Atlantic Water Flow - Leetcode 417/Pacific Atlantic Water Flow - Leetcode 417.cpp b/Pacific Atlantic Water Flow - Leetcode 417/Pacific Atlantic Water Flow - Leetcode 417.cpp new file mode 100644 index 0000000..68797fe --- /dev/null +++ b/Pacific Atlantic Water Flow - Leetcode 417/Pacific Atlantic Water Flow - Leetcode 417.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + vector> pacificAtlantic(vector>& heights) { + vector> result; + if (heights.empty() || heights[0].empty()) return result; + + int m = heights.size(); + int n = heights[0].size(); + + vector> pacific(m, vector(n, false)); + vector> atlantic(m, vector(n, false)); + + queue> pacQueue; + queue> atlQueue; + + for (int i = 0; i < m; ++i) { + pacQueue.push({i, 0}); + pacific[i][0] = true; + atlQueue.push({i, n - 1}); + atlantic[i][n - 1] = true; + } + + for (int j = 0; j < n; ++j) { + pacQueue.push({0, j}); + pacific[0][j] = true; + atlQueue.push({m - 1, j}); + atlantic[m - 1][j] = true; + } + + bfs(pacQueue, pacific, heights); + bfs(atlQueue, atlantic, heights); + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (pacific[i][j] && atlantic[i][j]) { + result.push_back({i, j}); + } + } + } + + return result; + } + +private: + void bfs(queue>& q, vector>& ocean, vector>& heights) { + int m = heights.size(); + int n = heights[0].size(); + vector> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + while (!q.empty()) { + auto [r, c] = q.front(); + q.pop(); + + for (auto& dir : directions) { + int newRow = r + dir.first; + int newCol = c + dir.second; + if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n + && !ocean[newRow][newCol] && heights[newRow][newCol] >= heights[r][c]) { + ocean[newRow][newCol] = true; + q.push({newRow, newCol}); + } + } + } + } +}; diff --git a/Pacific Atlantic Water Flow - Leetcode 417/Pacific Atlantic Water Flow - Leetcode 417.java b/Pacific Atlantic Water Flow - Leetcode 417/Pacific Atlantic Water Flow - Leetcode 417.java new file mode 100644 index 0000000..2868961 --- /dev/null +++ b/Pacific Atlantic Water Flow - Leetcode 417/Pacific Atlantic Water Flow - Leetcode 417.java @@ -0,0 +1,72 @@ +import java.util.*; + +public class Solution { + public List> pacificAtlantic(int[][] heights) { + List> result = new ArrayList<>(); + if (heights == null || heights.length == 0 || heights[0].length == 0) return result; + + int m = heights.length; + int n = heights[0].length; + + boolean[][] pacific = new boolean[m][n]; + boolean[][] atlantic = new boolean[m][n]; + + Queue pacQueue = new LinkedList<>(); + Queue atlQueue = new LinkedList<>(); + + // Add pacific border cells + for (int i = 0; i < m; i++) { + pacQueue.add(new int[]{i, 0}); + pacific[i][0] = true; + } + for (int j = 0; j < n; j++) { + pacQueue.add(new int[]{0, j}); + pacific[0][j] = true; + } + + // Add atlantic border cells + for (int i = 0; i < m; i++) { + atlQueue.add(new int[]{i, n - 1}); + atlantic[i][n - 1] = true; + } + for (int j = 0; j < n; j++) { + atlQueue.add(new int[]{m - 1, j}); + atlantic[m - 1][j] = true; + } + + bfs(pacQueue, pacific, heights); + bfs(atlQueue, atlantic, heights); + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (pacific[i][j] && atlantic[i][j]) { + result.add(Arrays.asList(i, j)); + } + } + } + + return result; + } + + private void bfs(Queue queue, boolean[][] ocean, int[][] heights) { + int m = heights.length; + int n = heights[0].length; + int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; + + while (!queue.isEmpty()) { + int[] cell = queue.poll(); + int r = cell[0]; + int c = cell[1]; + + for (int[] dir : directions) { + int newRow = r + dir[0]; + int newCol = c + dir[1]; + if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n + && !ocean[newRow][newCol] && heights[newRow][newCol] >= heights[r][c]) { + ocean[newRow][newCol] = true; + queue.add(new int[]{newRow, newCol}); + } + } + } + } +} diff --git a/Pacific Atlantic Water Flow - Leetcode 417/Pacific Atlantic Water Flow - Leetcode 417.js b/Pacific Atlantic Water Flow - Leetcode 417/Pacific Atlantic Water Flow - Leetcode 417.js new file mode 100644 index 0000000..7df8b6b --- /dev/null +++ b/Pacific Atlantic Water Flow - Leetcode 417/Pacific Atlantic Water Flow - Leetcode 417.js @@ -0,0 +1,60 @@ +function pacificAtlantic(heights) { + const result = []; + if (!heights || heights.length === 0 || heights[0].length === 0) return result; + + const m = heights.length; + const n = heights[0].length; + + const pacific = Array.from({ length: m }, () => Array(n).fill(false)); + const atlantic = Array.from({ length: m }, () => Array(n).fill(false)); + + const pacQueue = []; + const atlQueue = []; + + for (let i = 0; i < m; i++) { + pacQueue.push([i, 0]); + pacific[i][0] = true; + atlQueue.push([i, n - 1]); + atlantic[i][n - 1] = true; + } + + for (let j = 0; j < n; j++) { + pacQueue.push([0, j]); + pacific[0][j] = true; + atlQueue.push([m - 1, j]); + atlantic[m - 1][j] = true; + } + + bfs(pacQueue, pacific, heights); + bfs(atlQueue, atlantic, heights); + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (pacific[i][j] && atlantic[i][j]) { + result.push([i, j]); + } + } + } + + return result; +} + +function bfs(queue, ocean, heights) { + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; + const m = heights.length; + const n = heights[0].length; + + while (queue.length > 0) { + const [r, c] = queue.shift(); + + for (const [dr, dc] of directions) { + const newRow = r + dr; + const newCol = c + dc; + if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n + && !ocean[newRow][newCol] && heights[newRow][newCol] >= heights[r][c]) { + ocean[newRow][newCol] = true; + queue.push([newRow, newCol]); + } + } + } +} diff --git a/Pacific Atlantic Water Flow - Leetcode 417.py b/Pacific Atlantic Water Flow - Leetcode 417/Pacific Atlantic Water Flow - Leetcode 417.py similarity index 100% rename from Pacific Atlantic Water Flow - Leetcode 417.py rename to Pacific Atlantic Water Flow - Leetcode 417/Pacific Atlantic Water Flow - Leetcode 417.py diff --git a/Path Sum - Leetcode 112/Path Sum - Leetcode 112.cpp b/Path Sum - Leetcode 112/Path Sum - Leetcode 112.cpp new file mode 100644 index 0000000..bb77cd6 --- /dev/null +++ b/Path Sum - Leetcode 112/Path Sum - Leetcode 112.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; + +class Solution { +public: + bool hasPathSum(TreeNode* root, int targetSum) { + return hasSum(root, 0, targetSum); + } + +private: + bool hasSum(TreeNode* node, int currentSum, int targetSum) { + if (node == nullptr) return false; + + currentSum += node->val; + + if (node->left == nullptr && node->right == nullptr) { + return currentSum == targetSum; + } + + return hasSum(node->left, currentSum, targetSum) || hasSum(node->right, currentSum, targetSum); + } +}; diff --git a/Path Sum - Leetcode 112/Path Sum - Leetcode 112.java b/Path Sum - Leetcode 112/Path Sum - Leetcode 112.java new file mode 100644 index 0000000..d48dcb0 --- /dev/null +++ b/Path Sum - Leetcode 112/Path Sum - Leetcode 112.java @@ -0,0 +1,17 @@ +public class Solution { + public boolean hasPathSum(TreeNode root, int targetSum) { + return hasSum(root, 0, targetSum); + } + + private boolean hasSum(TreeNode node, int currentSum, int targetSum) { + if (node == null) return false; + + currentSum += node.val; + + if (node.left == null && node.right == null) { + return currentSum == targetSum; + } + + return hasSum(node.left, currentSum, targetSum) || hasSum(node.right, currentSum, targetSum); + } +} diff --git a/Path Sum - Leetcode 112/Path Sum - Leetcode 112.js b/Path Sum - Leetcode 112/Path Sum - Leetcode 112.js new file mode 100644 index 0000000..7632970 --- /dev/null +++ b/Path Sum - Leetcode 112/Path Sum - Leetcode 112.js @@ -0,0 +1,15 @@ +function hasPathSum(root, targetSum) { + return hasSum(root, 0, targetSum); +} + +function hasSum(node, currentSum, targetSum) { + if (node === null) return false; + + currentSum += node.val; + + if (node.left === null && node.right === null) { + return currentSum === targetSum; + } + + return hasSum(node.left, currentSum, targetSum) || hasSum(node.right, currentSum, targetSum); +} diff --git a/Path Sum - Leetcode 112/Path Sum - Leetcode 112.py b/Path Sum - Leetcode 112/Path Sum - Leetcode 112.py new file mode 100644 index 0000000..f765314 --- /dev/null +++ b/Path Sum - Leetcode 112/Path Sum - Leetcode 112.py @@ -0,0 +1,24 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: + + def has_sum(root, cur_sum): + if not root: + return False + + cur_sum += root.val + + if not root.left and not root.right: + return cur_sum == targetSum + + return has_sum(root.left, cur_sum) or \ + has_sum(root.right, cur_sum) + + return has_sum(root, 0) + # Time: O(n) + # Space: O(h) or O(n) diff --git a/Permutation in String - Leetcode 567/Permutation in String - Leetcode 567.cpp b/Permutation in String - Leetcode 567/Permutation in String - Leetcode 567.cpp new file mode 100644 index 0000000..12c4a16 --- /dev/null +++ b/Permutation in String - Leetcode 567/Permutation in String - Leetcode 567.cpp @@ -0,0 +1,31 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool checkInclusion(string s1, string s2) { + int n1 = s1.length(); + int n2 = s2.length(); + + if (n1 > n2) return false; + + vector s1Counts(26, 0); + vector s2Counts(26, 0); + + for (int i = 0; i < n1; i++) { + s1Counts[s1[i] - 'a']++; + s2Counts[s2[i] - 'a']++; + } + + if (s1Counts == s2Counts) return true; + + for (int i = n1; i < n2; i++) { + s2Counts[s2[i] - 'a']++; + s2Counts[s2[i - n1] - 'a']--; + if (s1Counts == s2Counts) return true; + } + + return false; + } +}; diff --git a/Permutation in String - Leetcode 567/Permutation in String - Leetcode 567.java b/Permutation in String - Leetcode 567/Permutation in String - Leetcode 567.java new file mode 100644 index 0000000..7351ffc --- /dev/null +++ b/Permutation in String - Leetcode 567/Permutation in String - Leetcode 567.java @@ -0,0 +1,28 @@ +import java.util.Arrays; + +public class Solution { + public boolean checkInclusion(String s1, String s2) { + int n1 = s1.length(); + int n2 = s2.length(); + + if (n1 > n2) return false; + + int[] s1Counts = new int[26]; + int[] s2Counts = new int[26]; + + for (int i = 0; i < n1; i++) { + s1Counts[s1.charAt(i) - 'a']++; + s2Counts[s2.charAt(i) - 'a']++; + } + + if (Arrays.equals(s1Counts, s2Counts)) return true; + + for (int i = n1; i < n2; i++) { + s2Counts[s2.charAt(i) - 'a']++; + s2Counts[s2.charAt(i - n1) - 'a']--; + if (Arrays.equals(s1Counts, s2Counts)) return true; + } + + return false; + } +} diff --git a/Permutation in String - Leetcode 567/Permutation in String - Leetcode 567.js b/Permutation in String - Leetcode 567/Permutation in String - Leetcode 567.js new file mode 100644 index 0000000..e67377f --- /dev/null +++ b/Permutation in String - Leetcode 567/Permutation in String - Leetcode 567.js @@ -0,0 +1,24 @@ +function checkInclusion(s1, s2) { + const n1 = s1.length; + const n2 = s2.length; + + if (n1 > n2) return false; + + const s1Counts = Array(26).fill(0); + const s2Counts = Array(26).fill(0); + + for (let i = 0; i < n1; i++) { + s1Counts[s1.charCodeAt(i) - 97]++; + s2Counts[s2.charCodeAt(i) - 97]++; + } + + if (s1Counts.every((val, index) => val === s2Counts[index])) return true; + + for (let i = n1; i < n2; i++) { + s2Counts[s2.charCodeAt(i) - 97]++; + s2Counts[s2.charCodeAt(i - n1) - 97]--; + if (s1Counts.every((val, index) => val === s2Counts[index])) return true; + } + + return false; +} diff --git a/Permutation in String - Leetcode 567.py b/Permutation in String - Leetcode 567/Permutation in String - Leetcode 567.py similarity index 100% rename from Permutation in String - Leetcode 567.py rename to Permutation in String - Leetcode 567/Permutation in String - Leetcode 567.py diff --git a/Permutations - Leetcode 46/Permutations - Leetcode 46.cpp b/Permutations - Leetcode 46/Permutations - Leetcode 46.cpp new file mode 100644 index 0000000..93a82ca --- /dev/null +++ b/Permutations - Leetcode 46/Permutations - Leetcode 46.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; + +class Solution { +public: + vector> permute(vector& nums) { + vector> ans; + vector sol; + vector used(nums.size(), false); + + backtrack(nums, ans, sol, used); + return ans; + } + + void backtrack(vector& nums, vector>& ans, vector& sol, vector& used) { + if (sol.size() == nums.size()) { + ans.push_back(sol); + return; + } + + for (int i = 0; i < nums.size(); i++) { + if (used[i]) continue; + + sol.push_back(nums[i]); + used[i] = true; + backtrack(nums, ans, sol, used); + sol.pop_back(); + used[i] = false; + } + } +}; diff --git a/Permutations - Leetcode 46/Permutations - Leetcode 46.java b/Permutations - Leetcode 46/Permutations - Leetcode 46.java new file mode 100644 index 0000000..52a15e1 --- /dev/null +++ b/Permutations - Leetcode 46/Permutations - Leetcode 46.java @@ -0,0 +1,30 @@ +import java.util.ArrayList; +import java.util.List; + +public class Solution { + public List> permute(int[] nums) { + List> ans = new ArrayList<>(); + List sol = new ArrayList<>(); + boolean[] used = new boolean[nums.length]; + + backtrack(nums, ans, sol, used); + return ans; + } + + private void backtrack(int[] nums, List> ans, List sol, boolean[] used) { + if (sol.size() == nums.length) { + ans.add(new ArrayList<>(sol)); + return; + } + + for (int i = 0; i < nums.length; i++) { + if (used[i]) continue; + + sol.add(nums[i]); + used[i] = true; + backtrack(nums, ans, sol, used); + sol.remove(sol.size() - 1); + used[i] = false; + } + } +} diff --git a/Permutations - Leetcode 46/Permutations - Leetcode 46.js b/Permutations - Leetcode 46/Permutations - Leetcode 46.js new file mode 100644 index 0000000..375828a --- /dev/null +++ b/Permutations - Leetcode 46/Permutations - Leetcode 46.js @@ -0,0 +1,25 @@ +function permute(nums) { + const ans = []; + const sol = []; + const used = Array(nums.length).fill(false); + + function backtrack() { + if (sol.length === nums.length) { + ans.push([...sol]); + return; + } + + for (let i = 0; i < nums.length; i++) { + if (used[i]) continue; + + sol.push(nums[i]); + used[i] = true; + backtrack(); + sol.pop(); + used[i] = false; + } + } + + backtrack(); + return ans; +} diff --git a/Permutations - Leetcode 46.py b/Permutations - Leetcode 46/Permutations - Leetcode 46.py similarity index 100% rename from Permutations - Leetcode 46.py rename to Permutations - Leetcode 46/Permutations - Leetcode 46.py diff --git a/Product of Array Except Self - Leetcode 238.py b/Product of Array Except Self - Leetcode 238.py deleted file mode 100644 index a0232d4..0000000 --- a/Product of Array Except Self - Leetcode 238.py +++ /dev/null @@ -1,19 +0,0 @@ -class Solution: - def productExceptSelf(self, nums: List[int]) -> List[int]: - l_mult = 1 - r_mult = 1 - n = len(nums) - l_arr = [0] * n - r_arr = [0] * n - - for i in range(n): - j = -i -1 - l_arr[i] = l_mult - r_arr[j] = r_mult - l_mult *= nums[i] - r_mult *= nums[j] - - return [l*r for l, r in zip(l_arr, r_arr)] - -# Time Complexity: O(n) -# Space Complexity: O(n) diff --git a/Product of Array Except Self - Leetcode 238/Product of Array Except Self - Leetcode 238.cpp b/Product of Array Except Self - Leetcode 238/Product of Array Except Self - Leetcode 238.cpp new file mode 100644 index 0000000..80b2e5a --- /dev/null +++ b/Product of Array Except Self - Leetcode 238/Product of Array Except Self - Leetcode 238.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; + +class Solution { +public: + vector productExceptSelf(vector& nums) { + int n = nums.size(); + vector result(n); + + int leftProduct = 1; + int rightProduct = 1; + + // Calculate left products + for (int i = 0; i < n; i++) { + result[i] = leftProduct; + leftProduct *= nums[i]; + } + + // Calculate right products and final result + for (int i = n - 1; i >= 0; i--) { + result[i] *= rightProduct; + rightProduct *= nums[i]; + } + + return result; + } +}; diff --git a/Product of Array Except Self - Leetcode 238/Product of Array Except Self - Leetcode 238.java b/Product of Array Except Self - Leetcode 238/Product of Array Except Self - Leetcode 238.java new file mode 100644 index 0000000..37cdc91 --- /dev/null +++ b/Product of Array Except Self - Leetcode 238/Product of Array Except Self - Leetcode 238.java @@ -0,0 +1,23 @@ +public class Solution { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + int[] result = new int[n]; + + int leftProduct = 1; + int rightProduct = 1; + + // Calculate left products + for (int i = 0; i < n; i++) { + result[i] = leftProduct; + leftProduct *= nums[i]; + } + + // Calculate right products and final result + for (int i = n - 1; i >= 0; i--) { + result[i] *= rightProduct; + rightProduct *= nums[i]; + } + + return result; + } +} diff --git a/Product of Array Except Self - Leetcode 238/Product of Array Except Self - Leetcode 238.js b/Product of Array Except Self - Leetcode 238/Product of Array Except Self - Leetcode 238.js new file mode 100644 index 0000000..a83b1ed --- /dev/null +++ b/Product of Array Except Self - Leetcode 238/Product of Array Except Self - Leetcode 238.js @@ -0,0 +1,21 @@ +function productExceptSelf(nums) { + const n = nums.length; + const result = new Array(n); + + let leftProduct = 1; + let rightProduct = 1; + + // Calculate left products + for (let i = 0; i < n; i++) { + result[i] = leftProduct; + leftProduct *= nums[i]; + } + + // Calculate right products and final result + for (let i = n - 1; i >= 0; i--) { + result[i] *= rightProduct; + rightProduct *= nums[i]; + } + + return result; +} diff --git a/Product of Array Except Self - Leetcode 238/Product of Array Except Self - Leetcode 238.py b/Product of Array Except Self - Leetcode 238/Product of Array Except Self - Leetcode 238.py new file mode 100644 index 0000000..63c25b1 --- /dev/null +++ b/Product of Array Except Self - Leetcode 238/Product of Array Except Self - Leetcode 238.py @@ -0,0 +1,68 @@ +# Brute Force Solution +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + ans = [0] * n + + for i in range(n): + prod = 1 + for j in range(n): + if i != j: + prod *= nums[j] + ans[i] = prod + + return ans + # Time: O(n^2) + # Space: O(n) + + +# Optimal Solution +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + l_mult = 1 + r_mult = 1 + n = len(nums) + l_arr = [0] * n + r_arr = [0] * n + + for i in range(n): + j = -i -1 + l_arr[i] = l_mult + r_arr[j] = r_mult + l_mult *= nums[i] + r_mult *= nums[j] + + return [l*r for l, r in zip(l_arr, r_arr)] + +# Time Complexity: O(n) +# Space Complexity: O(n) + + +# Optimal Solution for Bootcamp +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + answer = [0] * n + + L = 1 + left_product = [0] * n + + for i in range(n): + left_product[i] = L + L *= nums[i] + + + R = 1 + right_product = [0] * n + + for i in range(n-1, -1, -1): + right_product[i] = R + R *= nums[i] + + + for i in range(n): + answer[i] = left_product[i] * right_product[i] + + return answer +# Time Complexity: O(n) +# Space Complexity: O(n) diff --git a/Ransom Note - Leetcode 383.py b/Ransom Note - Leetcode 383.py deleted file mode 100644 index 9aeeff0..0000000 --- a/Ransom Note - Leetcode 383.py +++ /dev/null @@ -1,22 +0,0 @@ -class Solution: - def canConstruct(self, ransomNote: str, magazine: str) -> bool: - counter = {} - - for c in magazine: - if c in counter: - counter[c] += 1 - else: - counter[c] = 1 - - for c in ransomNote: - if c not in counter: - return False - elif counter[c] == 1: - del counter[c] - else: - counter[c] -= 1 - - return True - -# Time Complexity: O(m + n) -# Space Complexity: O(1) diff --git a/Ransom Note - Leetcode 383/Ransom Note - Leetcode 383.cpp b/Ransom Note - Leetcode 383/Ransom Note - Leetcode 383.cpp new file mode 100644 index 0000000..0e5ed8b --- /dev/null +++ b/Ransom Note - Leetcode 383/Ransom Note - Leetcode 383.cpp @@ -0,0 +1,27 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool canConstruct(string ransomNote, string magazine) { + unordered_map hashmap; + + for (char ch : magazine) { + hashmap[ch]++; + } + + for (char ch : ransomNote) { + if (hashmap[ch] > 0) { + hashmap[ch]--; + } else { + return false; + } + } + + return true; + } +}; + +// Time Complexity: O(m + n) -> m = length of ransomNote, n = length of magazine +// Space Complexity: O(n) -> we're using an unordered_map diff --git a/Ransom Note - Leetcode 383/Ransom Note - Leetcode 383.java b/Ransom Note - Leetcode 383/Ransom Note - Leetcode 383.java new file mode 100644 index 0000000..4bfe6b9 --- /dev/null +++ b/Ransom Note - Leetcode 383/Ransom Note - Leetcode 383.java @@ -0,0 +1,24 @@ +import java.util.HashMap; + +class Solution { + public boolean canConstruct(String ransomNote, String magazine) { + HashMap hashmap = new HashMap<>(); + + for (char ch : magazine.toCharArray()) { + hashmap.put(ch, hashmap.getOrDefault(ch, 0) + 1); + } + + for (char ch : ransomNote.toCharArray()) { + if (hashmap.getOrDefault(ch, 0) > 0) { + hashmap.put(ch, hashmap.get(ch) - 1); + } else { + return false; + } + } + + return true; + } +} + +// Time Complexity: O(m + n) -> m = len(ransomNote), n = len(magazine) +// Space Complexity: O(n) -> we're using a hashmap diff --git a/Ransom Note - Leetcode 383/Ransom Note - Leetcode 383.js b/Ransom Note - Leetcode 383/Ransom Note - Leetcode 383.js new file mode 100644 index 0000000..2410ffd --- /dev/null +++ b/Ransom Note - Leetcode 383/Ransom Note - Leetcode 383.js @@ -0,0 +1,20 @@ +var canConstruct = function(ransomNote, magazine) { + let hashmap = {}; + + for (let ch of magazine) { + hashmap[ch] = (hashmap[ch] || 0) + 1; + } + + for (let ch of ransomNote) { + if (hashmap[ch] > 0) { + hashmap[ch]--; + } else { + return false; + } + } + + return true; +}; + +// Time Complexity: O(m + n) -> m = length of ransomNote, n = length of magazine +// Space Complexity: O(n) -> we're using a hashmap diff --git a/Ransom Note - Leetcode 383/Ransom Note - Leetcode 383.py b/Ransom Note - Leetcode 383/Ransom Note - Leetcode 383.py new file mode 100644 index 0000000..3f5de88 --- /dev/null +++ b/Ransom Note - Leetcode 383/Ransom Note - Leetcode 383.py @@ -0,0 +1,28 @@ +# Brute Force Solution +class Solution: + def canConstruct(self, ransomNote: str, magazine: str) -> bool: + for letter in ransomNote: + if letter in magazine: + position = magazine.index(letter) + magazine = magazine[:position] + magazine[position+1:] + else: + return False + + return True +# Time: O(R * M) +# Space: O(1) + +# Optimal Solution +class Solution: + def canConstruct(self, ransomNote: str, magazine: str) -> bool: + hashmap = Counter(magazine) # TC for Counter is O(n) + + for ch in ransomNote: + if hashmap[ch] > 0: + hashmap[ch]-=1 + else: + return False + return True + +# Time Complexity: O(R + M) -> R = len(ransomNote), M = len(magazine) +# Space Complexity: O(M) -> we're using a hashmap diff --git a/Remove Duplicates from Sorted Array - Leetcode 26/Remove Duplicates from Sorted Array - Leetcode 26.cpp b/Remove Duplicates from Sorted Array - Leetcode 26/Remove Duplicates from Sorted Array - Leetcode 26.cpp new file mode 100644 index 0000000..440120a --- /dev/null +++ b/Remove Duplicates from Sorted Array - Leetcode 26/Remove Duplicates from Sorted Array - Leetcode 26.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int removeDuplicates(vector& nums) { + if (nums.empty()) return 0; + int j = 1; + for (int i = 1; i < nums.size(); i++) { + if (nums[i] != nums[i - 1]) { + nums[j] = nums[i]; + j++; + } + } + return j; + } +}; diff --git a/Remove Duplicates from Sorted Array - Leetcode 26/Remove Duplicates from Sorted Array - Leetcode 26.java b/Remove Duplicates from Sorted Array - Leetcode 26/Remove Duplicates from Sorted Array - Leetcode 26.java new file mode 100644 index 0000000..8b0a932 --- /dev/null +++ b/Remove Duplicates from Sorted Array - Leetcode 26/Remove Duplicates from Sorted Array - Leetcode 26.java @@ -0,0 +1,13 @@ +class Solution { + public int removeDuplicates(int[] nums) { + if (nums.length == 0) return 0; + int j = 1; + for (int i = 1; i < nums.length; i++) { + if (nums[i] != nums[i - 1]) { + nums[j] = nums[i]; + j++; + } + } + return j; + } +} diff --git a/Remove Duplicates from Sorted Array - Leetcode 26/Remove Duplicates from Sorted Array - Leetcode 26.js b/Remove Duplicates from Sorted Array - Leetcode 26/Remove Duplicates from Sorted Array - Leetcode 26.js new file mode 100644 index 0000000..d659bba --- /dev/null +++ b/Remove Duplicates from Sorted Array - Leetcode 26/Remove Duplicates from Sorted Array - Leetcode 26.js @@ -0,0 +1,11 @@ +var removeDuplicates = function(nums) { + if (nums.length === 0) return 0; + let j = 1; + for (let i = 1; i < nums.length; i++) { + if (nums[i] !== nums[i - 1]) { + nums[j] = nums[i]; + j++; + } + } + return j; +}; diff --git a/Remove Duplicates from Sorted Array - Leetcode 26/Remove Duplicates from Sorted Array - Leetcode 26.py b/Remove Duplicates from Sorted Array - Leetcode 26/Remove Duplicates from Sorted Array - Leetcode 26.py new file mode 100644 index 0000000..05c4fb9 --- /dev/null +++ b/Remove Duplicates from Sorted Array - Leetcode 26/Remove Duplicates from Sorted Array - Leetcode 26.py @@ -0,0 +1,13 @@ +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + n = len(nums) + j = 1 + for i in range(1, n): + if nums[i] != nums[i-1]: + nums[j] = nums[i] + j += 1 + + return j + + # Time: O(n) + # Space: O(1) \ No newline at end of file diff --git a/Remove Duplicates from Sorted Array II - Leetcode 80/Remove Duplicates from Sorted Array II - Leetcode 80.cpp b/Remove Duplicates from Sorted Array II - Leetcode 80/Remove Duplicates from Sorted Array II - Leetcode 80.cpp new file mode 100644 index 0000000..e242730 --- /dev/null +++ b/Remove Duplicates from Sorted Array II - Leetcode 80/Remove Duplicates from Sorted Array II - Leetcode 80.cpp @@ -0,0 +1,25 @@ +#include + +class Solution { +public: + int removeDuplicates(std::vector& nums) { + int j = 1; + int count = 1; + int n = nums.size(); + + for (int i = 1; i < n; i++) { + if (nums[i] == nums[i - 1]) { + count++; + } else { + count = 1; + } + + if (count <= 2) { + nums[j] = nums[i]; + j++; + } + } + + return j; + } +}; diff --git a/Remove Duplicates from Sorted Array II - Leetcode 80/Remove Duplicates from Sorted Array II - Leetcode 80.java b/Remove Duplicates from Sorted Array II - Leetcode 80/Remove Duplicates from Sorted Array II - Leetcode 80.java new file mode 100644 index 0000000..3e22d32 --- /dev/null +++ b/Remove Duplicates from Sorted Array II - Leetcode 80/Remove Duplicates from Sorted Array II - Leetcode 80.java @@ -0,0 +1,22 @@ +class Solution { + public int removeDuplicates(int[] nums) { + int j = 1; + int count = 1; + int n = nums.length; + + for (int i = 1; i < n; i++) { + if (nums[i] == nums[i - 1]) { + count++; + } else { + count = 1; + } + + if (count <= 2) { + nums[j] = nums[i]; + j++; + } + } + + return j; + } +} diff --git a/Remove Duplicates from Sorted Array II - Leetcode 80/Remove Duplicates from Sorted Array II - Leetcode 80.js b/Remove Duplicates from Sorted Array II - Leetcode 80/Remove Duplicates from Sorted Array II - Leetcode 80.js new file mode 100644 index 0000000..695e45c --- /dev/null +++ b/Remove Duplicates from Sorted Array II - Leetcode 80/Remove Duplicates from Sorted Array II - Leetcode 80.js @@ -0,0 +1,20 @@ +var removeDuplicates = function(nums) { + var j = 1; + var count = 1; + var n = nums.length; + + for (var i = 1; i < n; i++) { + if (nums[i] === nums[i - 1]) { + count++; + } else { + count = 1; + } + + if (count <= 2) { + nums[j] = nums[i]; + j++; + } + } + + return j; +}; diff --git a/Remove Duplicates from Sorted Array II - Leetcode 80/Remove Duplicates from Sorted Array II - Leetcode 80.py b/Remove Duplicates from Sorted Array II - Leetcode 80/Remove Duplicates from Sorted Array II - Leetcode 80.py new file mode 100644 index 0000000..fb417be --- /dev/null +++ b/Remove Duplicates from Sorted Array II - Leetcode 80/Remove Duplicates from Sorted Array II - Leetcode 80.py @@ -0,0 +1,19 @@ +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + j = 1 + count = 1 + n = len(nums) + + for i in range(1, n): + if nums[i] == nums[i-1]: + count += 1 + else: + count = 1 + + if count <= 2: + nums[j] = nums[i] + j += 1 + + return j + # Time: O(n) + # Space: O(1) diff --git a/Remove Duplicates from Sorted List - Leetcode 83/Remove Duplicates from Sorted List - Leetcode 83.cpp b/Remove Duplicates from Sorted List - Leetcode 83/Remove Duplicates from Sorted List - Leetcode 83.cpp new file mode 100644 index 0000000..39fd191 --- /dev/null +++ b/Remove Duplicates from Sorted List - Leetcode 83/Remove Duplicates from Sorted List - Leetcode 83.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* cur = head; + + while (cur != nullptr && cur->next != nullptr) { + if (cur->val == cur->next->val) { + cur->next = cur->next->next; + } else { + cur = cur->next; + } + } + + return head; + } +}; diff --git a/Remove Duplicates from Sorted List - Leetcode 83/Remove Duplicates from Sorted List - Leetcode 83.java b/Remove Duplicates from Sorted List - Leetcode 83/Remove Duplicates from Sorted List - Leetcode 83.java new file mode 100644 index 0000000..6cced42 --- /dev/null +++ b/Remove Duplicates from Sorted List - Leetcode 83/Remove Duplicates from Sorted List - Leetcode 83.java @@ -0,0 +1,15 @@ +public class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode cur = head; + + while (cur != null && cur.next != null) { + if (cur.val == cur.next.val) { + cur.next = cur.next.next; + } else { + cur = cur.next; + } + } + + return head; + } +} diff --git a/Remove Duplicates from Sorted List - Leetcode 83/Remove Duplicates from Sorted List - Leetcode 83.js b/Remove Duplicates from Sorted List - Leetcode 83/Remove Duplicates from Sorted List - Leetcode 83.js new file mode 100644 index 0000000..fafebc7 --- /dev/null +++ b/Remove Duplicates from Sorted List - Leetcode 83/Remove Duplicates from Sorted List - Leetcode 83.js @@ -0,0 +1,13 @@ +function deleteDuplicates(head) { + let cur = head; + + while (cur && cur.next) { + if (cur.val === cur.next.val) { + cur.next = cur.next.next; + } else { + cur = cur.next; + } + } + + return head; +} diff --git a/Remove Duplicates from Sorted List - Leetcode 83.py b/Remove Duplicates from Sorted List - Leetcode 83/Remove Duplicates from Sorted List - Leetcode 83.py similarity index 100% rename from Remove Duplicates from Sorted List - Leetcode 83.py rename to Remove Duplicates from Sorted List - Leetcode 83/Remove Duplicates from Sorted List - Leetcode 83.py diff --git a/Remove Element - Leetcode 27/Remove Element - Leetcode 27.cpp b/Remove Element - Leetcode 27/Remove Element - Leetcode 27.cpp new file mode 100644 index 0000000..aa2ae46 --- /dev/null +++ b/Remove Element - Leetcode 27/Remove Element - Leetcode 27.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int removeElement(vector& nums, int val) { + int i = 0, n = nums.size(); + + while (i < n) { + if (nums[i] == val) { + nums[i] = nums[n - 1]; + n--; + } else { + i++; + } + } + return n; + } +}; diff --git a/Remove Element - Leetcode 27/Remove Element - Leetcode 27.java b/Remove Element - Leetcode 27/Remove Element - Leetcode 27.java new file mode 100644 index 0000000..53ccd63 --- /dev/null +++ b/Remove Element - Leetcode 27/Remove Element - Leetcode 27.java @@ -0,0 +1,15 @@ +class Solution { + public int removeElement(int[] nums, int val) { + int i = 0, n = nums.length; + + while (i < n) { + if (nums[i] == val) { + nums[i] = nums[n - 1]; + n--; + } else { + i++; + } + } + return n; + } +} diff --git a/Remove Element - Leetcode 27/Remove Element - Leetcode 27.js b/Remove Element - Leetcode 27/Remove Element - Leetcode 27.js new file mode 100644 index 0000000..78a45dd --- /dev/null +++ b/Remove Element - Leetcode 27/Remove Element - Leetcode 27.js @@ -0,0 +1,14 @@ +var removeElement = function(nums, val) { + let i = 0; + let n = nums.length; + + while (i < n) { + if (nums[i] === val) { + nums[i] = nums[n - 1]; + n--; + } else { + i++; + } + } + return n; +}; diff --git a/Remove Element - Leetcode 27/Remove Element - Leetcode 27.py b/Remove Element - Leetcode 27/Remove Element - Leetcode 27.py new file mode 100644 index 0000000..6c8da38 --- /dev/null +++ b/Remove Element - Leetcode 27/Remove Element - Leetcode 27.py @@ -0,0 +1,15 @@ +class Solution: + def removeElement(self, nums: List[int], val: int) -> int: + i = 0 + n = len(nums) + + while i < n: + if nums[i] == val: + nums[i] = nums[n - 1] + n -= 1 + else: + i += 1 + return n + + # Time: O(n) + # Space: O(1) \ No newline at end of file diff --git a/Remove Nth Node from End of List - Leetcode 19/Remove Nth Node from End of List - Leetcode 19.cpp b/Remove Nth Node from End of List - Leetcode 19/Remove Nth Node from End of List - Leetcode 19.cpp new file mode 100644 index 0000000..7716ac6 --- /dev/null +++ b/Remove Nth Node from End of List - Leetcode 19/Remove Nth Node from End of List - Leetcode 19.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + ListNode dummy(0); + dummy.next = head; + ListNode *behind = &dummy, *ahead = &dummy; + + for (int i = 0; i <= n; ++i) { + ahead = ahead->next; + } + + while (ahead != nullptr) { + behind = behind->next; + ahead = ahead->next; + } + + behind->next = behind->next->next; + + return dummy.next; + } +}; diff --git a/Remove Nth Node from End of List - Leetcode 19/Remove Nth Node from End of List - Leetcode 19.java b/Remove Nth Node from End of List - Leetcode 19/Remove Nth Node from End of List - Leetcode 19.java new file mode 100644 index 0000000..f47d869 --- /dev/null +++ b/Remove Nth Node from End of List - Leetcode 19/Remove Nth Node from End of List - Leetcode 19.java @@ -0,0 +1,20 @@ +public class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + ListNode dummy = new ListNode(0); + dummy.next = head; + ListNode behind = dummy, ahead = dummy; + + for (int i = 0; i <= n; i++) { + ahead = ahead.next; + } + + while (ahead != null) { + behind = behind.next; + ahead = ahead.next; + } + + behind.next = behind.next.next; + + return dummy.next; + } +} diff --git a/Remove Nth Node from End of List - Leetcode 19/Remove Nth Node from End of List - Leetcode 19.js b/Remove Nth Node from End of List - Leetcode 19/Remove Nth Node from End of List - Leetcode 19.js new file mode 100644 index 0000000..ad14a5b --- /dev/null +++ b/Remove Nth Node from End of List - Leetcode 19/Remove Nth Node from End of List - Leetcode 19.js @@ -0,0 +1,18 @@ +function removeNthFromEnd(head, n) { + let dummy = new ListNode(0); + dummy.next = head; + let behind = dummy, ahead = dummy; + + for (let i = 0; i <= n; i++) { + ahead = ahead.next; + } + + while (ahead) { + behind = behind.next; + ahead = ahead.next; + } + + behind.next = behind.next.next; + + return dummy.next; +} diff --git a/Remove Nth Node from End of List - Leetcode 19.py b/Remove Nth Node from End of List - Leetcode 19/Remove Nth Node from End of List - Leetcode 19.py similarity index 100% rename from Remove Nth Node from End of List - Leetcode 19.py rename to Remove Nth Node from End of List - Leetcode 19/Remove Nth Node from End of List - Leetcode 19.py diff --git a/Reverse Linked List - Leetcode 206/Reverse Linked List - Leetcode 206.cpp b/Reverse Linked List - Leetcode 206/Reverse Linked List - Leetcode 206.cpp new file mode 100644 index 0000000..7d5d8fb --- /dev/null +++ b/Reverse Linked List - Leetcode 206/Reverse Linked List - Leetcode 206.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + ListNode* prev = nullptr; + ListNode* cur = head; + + while (cur != nullptr) { + ListNode* temp = cur->next; + cur->next = prev; + prev = cur; + cur = temp; + } + + return prev; + } +}; diff --git a/Reverse Linked List - Leetcode 206/Reverse Linked List - Leetcode 206.java b/Reverse Linked List - Leetcode 206/Reverse Linked List - Leetcode 206.java new file mode 100644 index 0000000..2d1bf7a --- /dev/null +++ b/Reverse Linked List - Leetcode 206/Reverse Linked List - Leetcode 206.java @@ -0,0 +1,15 @@ +public class Solution { + public ListNode reverseList(ListNode head) { + ListNode prev = null; + ListNode cur = head; + + while (cur != null) { + ListNode temp = cur.next; + cur.next = prev; + prev = cur; + cur = temp; + } + + return prev; + } +} diff --git a/Reverse Linked List - Leetcode 206/Reverse Linked List - Leetcode 206.js b/Reverse Linked List - Leetcode 206/Reverse Linked List - Leetcode 206.js new file mode 100644 index 0000000..ea1e628 --- /dev/null +++ b/Reverse Linked List - Leetcode 206/Reverse Linked List - Leetcode 206.js @@ -0,0 +1,13 @@ +function reverseList(head) { + let prev = null; + let cur = head; + + while (cur !== null) { + let temp = cur.next; + cur.next = prev; + prev = cur; + cur = temp; + } + + return prev; +} diff --git a/Reverse Linked List - Leetcode 206.py b/Reverse Linked List - Leetcode 206/Reverse Linked List - Leetcode 206.py similarity index 100% rename from Reverse Linked List - Leetcode 206.py rename to Reverse Linked List - Leetcode 206/Reverse Linked List - Leetcode 206.py diff --git a/Reverse String - Leetcode 344.py b/Reverse String - Leetcode 344.py deleted file mode 100644 index 48cd942..0000000 --- a/Reverse String - Leetcode 344.py +++ /dev/null @@ -1,16 +0,0 @@ -class Solution: - def reverseString(self, s: List[str]) -> None: - """ - Do not return anything, modify s in-place instead. - """ - n = len(s) - l = 0 - r = n - 1 - - while l < r: - s[l], s[r] = s[r], s[l] - l += 1 - r -= 1 - -# Time Complexity: O(n) -# Space Complexity: O(1) diff --git a/Reverse String - Leetcode 344/Reverse String - Leetcode 344.cpp b/Reverse String - Leetcode 344/Reverse String - Leetcode 344.cpp new file mode 100644 index 0000000..6b64c63 --- /dev/null +++ b/Reverse String - Leetcode 344/Reverse String - Leetcode 344.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + void reverseString(vector& s) { + int l = 0; + int r = s.size() - 1; + + while (l < r) { + swap(s[l], s[r]); + l++; + r--; + } + } +}; diff --git a/Reverse String - Leetcode 344/Reverse String - Leetcode 344.java b/Reverse String - Leetcode 344/Reverse String - Leetcode 344.java new file mode 100644 index 0000000..0db2135 --- /dev/null +++ b/Reverse String - Leetcode 344/Reverse String - Leetcode 344.java @@ -0,0 +1,14 @@ +public class Solution { + public void reverseString(char[] s) { + int l = 0; + int r = s.length - 1; + + while (l < r) { + char temp = s[l]; + s[l] = s[r]; + s[r] = temp; + l++; + r--; + } + } +} diff --git a/Reverse String - Leetcode 344/Reverse String - Leetcode 344.js b/Reverse String - Leetcode 344/Reverse String - Leetcode 344.js new file mode 100644 index 0000000..cf5ad81 --- /dev/null +++ b/Reverse String - Leetcode 344/Reverse String - Leetcode 344.js @@ -0,0 +1,10 @@ +function reverseString(s) { + let l = 0; + let r = s.length - 1; + + while (l < r) { + [s[l], s[r]] = [s[r], s[l]]; + l++; + r--; + } +} diff --git a/Reverse String - Leetcode 344/Reverse String - Leetcode 344.py b/Reverse String - Leetcode 344/Reverse String - Leetcode 344.py new file mode 100644 index 0000000..0f947f0 --- /dev/null +++ b/Reverse String - Leetcode 344/Reverse String - Leetcode 344.py @@ -0,0 +1,34 @@ +# Brute Force Solution +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + n = len(s) + T = [] + for i in range(n-1, -1, -1): + T.append(s[i]) + + for i in range(n): + s[i] = T[i] + + # Time: O(n) + # Space: O(n) + +# Two Pointers (Optimal) Solution +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + n = len(s) + l = 0 + r = n - 1 + + while l < r: + s[l], s[r] = s[r], s[l] + l += 1 + r -= 1 + +# Time Complexity: O(n) +# Space Complexity: O(1) diff --git a/Roman to Integer - Leetcode 13/Roman to Integer - Leetcode 13.cpp b/Roman to Integer - Leetcode 13/Roman to Integer - Leetcode 13.cpp new file mode 100644 index 0000000..328ecdf --- /dev/null +++ b/Roman to Integer - Leetcode 13/Roman to Integer - Leetcode 13.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int romanToInt(string s) { + unordered_map d = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}}; + int summ = 0; + int n = s.size(); + int i = 0; + + while (i < n) { + if (i < n - 1 && d[s[i]] < d[s[i + 1]]) { + summ += d[s[i + 1]] - d[s[i]]; + i += 2; + } else { + summ += d[s[i]]; + i++; + } + } + + return summ; + } +}; diff --git a/Roman to Integer - Leetcode 13/Roman to Integer - Leetcode 13.java b/Roman to Integer - Leetcode 13/Roman to Integer - Leetcode 13.java new file mode 100644 index 0000000..6d7f9b1 --- /dev/null +++ b/Roman to Integer - Leetcode 13/Roman to Integer - Leetcode 13.java @@ -0,0 +1,31 @@ +import java.util.HashMap; +import java.util.Map; + +public class Solution { + public int romanToInt(String s) { + Map d = new HashMap<>(); + d.put('I', 1); + d.put('V', 5); + d.put('X', 10); + d.put('L', 50); + d.put('C', 100); + d.put('D', 500); + d.put('M', 1000); + + int summ = 0; + int n = s.length(); + int i = 0; + + while (i < n) { + if (i < n - 1 && d.get(s.charAt(i)) < d.get(s.charAt(i + 1))) { + summ += d.get(s.charAt(i + 1)) - d.get(s.charAt(i)); + i += 2; + } else { + summ += d.get(s.charAt(i)); + i++; + } + } + + return summ; + } +} diff --git a/Roman to Integer - Leetcode 13/Roman to Integer - Leetcode 13.js b/Roman to Integer - Leetcode 13/Roman to Integer - Leetcode 13.js new file mode 100644 index 0000000..f1f97e2 --- /dev/null +++ b/Roman to Integer - Leetcode 13/Roman to Integer - Leetcode 13.js @@ -0,0 +1,18 @@ +function romanToInt(s) { + const d = {I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000}; + let summ = 0; + const n = s.length; + let i = 0; + + while (i < n) { + if (i < n - 1 && d[s[i]] < d[s[i + 1]]) { + summ += d[s[i + 1]] - d[s[i]]; + i += 2; + } else { + summ += d[s[i]]; + i++; + } + } + + return summ; +} diff --git a/Roman to Integer - Leetcode 13/Roman to Integer - Leetcode 13.py b/Roman to Integer - Leetcode 13/Roman to Integer - Leetcode 13.py new file mode 100644 index 0000000..b4e0f48 --- /dev/null +++ b/Roman to Integer - Leetcode 13/Roman to Integer - Leetcode 13.py @@ -0,0 +1,18 @@ +class Solution: + def romanToInt(self, s: str) -> int: + d = {'I': 1, 'V':5, 'X':10, 'L':50, 'C':100, 'D': 500, 'M':1000} + summ = 0 + n = len(s) + i = 0 + + while i < n: + if i < n - 1 and d[s[i]] < d[s[i+1]]: + summ += d[s[i+1]] - d[s[i]] + i += 2 + else: + summ += d[s[i]] + i += 1 + + return summ + # Time: O(n) + # Space: O(1) diff --git a/Rotate Image - Leetcode 48/Rotate Image - Leetcode 48.cpp b/Rotate Image - Leetcode 48/Rotate Image - Leetcode 48.cpp new file mode 100644 index 0000000..588cdab --- /dev/null +++ b/Rotate Image - Leetcode 48/Rotate Image - Leetcode 48.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + void rotate(vector>& matrix) { + int n = matrix.size(); + + // Transpose + for (int i = 0; i < n; ++i) { + for (int j = i + 1; j < n; ++j) { + swap(matrix[i][j], matrix[j][i]); + } + } + + // Reflection + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n / 2; ++j) { + swap(matrix[i][j], matrix[i][n - j - 1]); + } + } + } +}; diff --git a/Rotate Image - Leetcode 48/Rotate Image - Leetcode 48.java b/Rotate Image - Leetcode 48/Rotate Image - Leetcode 48.java new file mode 100644 index 0000000..38a6690 --- /dev/null +++ b/Rotate Image - Leetcode 48/Rotate Image - Leetcode 48.java @@ -0,0 +1,23 @@ +public class Solution { + public void rotate(int[][] matrix) { + int n = matrix.length; + + // Transpose + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + int temp = matrix[i][j]; + matrix[i][j] = matrix[j][i]; + matrix[j][i] = temp; + } + } + + // Reflection + for (int i = 0; i < n; i++) { + for (int j = 0; j < n / 2; j++) { + int temp = matrix[i][j]; + matrix[i][j] = matrix[i][n - j - 1]; + matrix[i][n - j - 1] = temp; + } + } + } +} diff --git a/Rotate Image - Leetcode 48/Rotate Image - Leetcode 48.js b/Rotate Image - Leetcode 48/Rotate Image - Leetcode 48.js new file mode 100644 index 0000000..e3f4cad --- /dev/null +++ b/Rotate Image - Leetcode 48/Rotate Image - Leetcode 48.js @@ -0,0 +1,17 @@ +function rotate(matrix) { + const n = matrix.length; + + // Transpose + for (let i = 0; i < n; i++) { + for (let j = i + 1; j < n; j++) { + [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]; + } + } + + // Reflection + for (let i = 0; i < n; i++) { + for (let j = 0; j < n / 2; j++) { + [matrix[i][j], matrix[i][n - j - 1]] = [matrix[i][n - j - 1], matrix[i][j]]; + } + } +} diff --git a/Rotate Image - Leetcode 48/Rotate Image - Leetcode 48.py b/Rotate Image - Leetcode 48/Rotate Image - Leetcode 48.py new file mode 100644 index 0000000..2d6a660 --- /dev/null +++ b/Rotate Image - Leetcode 48/Rotate Image - Leetcode 48.py @@ -0,0 +1,19 @@ +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + """ + Do not return anything, modify matrix in-place instead. + """ + n = len(matrix) + + # Tranpose + for i in range(n): + for j in range(i+1, n): + matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] + + # Reflection + for i in range(n): + for j in range(n // 2): + matrix[i][j], matrix[i][n-j-1] = matrix[i][n-j-1], matrix[i][j] + + # Time: O(n^2) + # Space: O(1) diff --git a/Rotting Oranges - Leetcode 994.py b/Rotting Oranges - Leetcode 994.py deleted file mode 100644 index 32f3ce0..0000000 --- a/Rotting Oranges - Leetcode 994.py +++ /dev/null @@ -1,38 +0,0 @@ -from collections import deque -class Solution: - def orangesRotting(self, grid: List[List[int]]) -> int: - EMPTY, FRESH, ROTTEN = 0, 1, 2 - m, n = len(grid), len(grid[0]) - num_fresh = 0 - q = deque() - - for i in range(m): - for j in range(n): - if grid[i][j] == ROTTEN: - q.append((i, j)) - elif grid[i][j] == FRESH: - num_fresh += 1 - - if num_fresh == 0: - return 0 - - num_minutes = -1 - while q: - q_size = len(q) - num_minutes += 1 - - for _ in range(q_size): - i, j = q.popleft() - for r, c in [(i, j + 1), (i + 1, j), (i, j - 1), (i - 1, j)]: - if 0 <= r < m and 0 <= c < n and grid[r][c] == FRESH: - grid[r][c] = ROTTEN - num_fresh -= 1 - q.append((r, c)) - - if num_fresh == 0: - return num_minutes - else: - return -1 - -# Time Complexity: O(m*n) -# Space Complexity: O(m*n) diff --git a/Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.cpp b/Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.cpp new file mode 100644 index 0000000..caf26bc --- /dev/null +++ b/Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.cpp @@ -0,0 +1,48 @@ +#include +#include + +using namespace std; + +class Solution { +public: + int orangesRotting(vector>& grid) { + const int EMPTY = 0, FRESH = 1, ROTTEN = 2; + int m = grid.size(), n = grid[0].size(); + int numFresh = 0; + queue> q; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == ROTTEN) { + q.push({i, j}); + } else if (grid[i][j] == FRESH) { + numFresh++; + } + } + } + + if (numFresh == 0) return 0; + + int numMinutes = -1; + while (!q.empty()) { + int qSize = q.size(); + numMinutes++; + + for (int k = 0; k < qSize; k++) { + auto pos = q.front(); + q.pop(); + int i = pos.first, j = pos.second; + for (auto dir : vector>{{0,1},{1,0},{0,-1},{-1,0}}) { + int r = i + dir[0], c = j + dir[1]; + if (r >= 0 && r < m && c >= 0 && c < n && grid[r][c] == FRESH) { + grid[r][c] = ROTTEN; + numFresh--; + q.push({r, c}); + } + } + } + } + + return numFresh == 0 ? numMinutes : -1; + } +}; diff --git a/Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.java b/Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.java new file mode 100644 index 0000000..947159f --- /dev/null +++ b/Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.java @@ -0,0 +1,43 @@ +import java.util.*; + +public class Solution { + public int orangesRotting(int[][] grid) { + final int EMPTY = 0, FRESH = 1, ROTTEN = 2; + int m = grid.length, n = grid[0].length; + int numFresh = 0; + Queue q = new LinkedList<>(); + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == ROTTEN) { + q.offer(new int[]{i, j}); + } else if (grid[i][j] == FRESH) { + numFresh++; + } + } + } + + if (numFresh == 0) return 0; + + int numMinutes = -1; + while (!q.isEmpty()) { + int qSize = q.size(); + numMinutes++; + + for (int k = 0; k < qSize; k++) { + int[] pos = q.poll(); + int i = pos[0], j = pos[1]; + for (int[] dir : new int[][]{{0,1},{1,0},{0,-1},{-1,0}}) { + int r = i + dir[0], c = j + dir[1]; + if (r >= 0 && r < m && c >= 0 && c < n && grid[r][c] == FRESH) { + grid[r][c] = ROTTEN; + numFresh--; + q.offer(new int[]{r, c}); + } + } + } + } + + return numFresh == 0 ? numMinutes : -1; + } +} diff --git a/Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.js b/Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.js new file mode 100644 index 0000000..8b46631 --- /dev/null +++ b/Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.js @@ -0,0 +1,39 @@ +function orangesRotting(grid) { + const EMPTY = 0, FRESH = 1, ROTTEN = 2; + const m = grid.length, n = grid[0].length; + let numFresh = 0; + const q = []; + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === ROTTEN) { + q.push([i, j]); + } else if (grid[i][j] === FRESH) { + numFresh++; + } + } + } + + if (numFresh === 0) return 0; + + let numMinutes = -1; + while (q.length > 0) { + const qSize = q.length; + numMinutes++; + + for (let k = 0; k < qSize; k++) { + const [i, j] = q.shift(); + const dirs = [[0,1], [1,0], [0,-1], [-1,0]]; + for (const [di, dj] of dirs) { + const r = i + di, c = j + dj; + if (r >= 0 && r < m && c >= 0 && c < n && grid[r][c] === FRESH) { + grid[r][c] = ROTTEN; + numFresh--; + q.push([r, c]); + } + } + } + } + + return numFresh === 0 ? numMinutes : -1; +} diff --git a/Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.py b/Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.py new file mode 100644 index 0000000..c14eb3f --- /dev/null +++ b/Rotting Oranges - Leetcode 994/Rotting Oranges - Leetcode 994.py @@ -0,0 +1,75 @@ +# Code for Bootcamp +class Solution: + from collections import deque + + def orangesRotting(self, grid): + # Initialize variables + Minute = 0 + Q = deque() + FreshCount = 0 + M, N = len(grid), len(grid[0]) + + # Populate queue with initial rotten oranges and count fresh oranges + for i in range(M): + for j in range(N): + if grid[i][j] == 2: + Q.append((i, j)) + elif grid[i][j] == 1: + FreshCount += 1 + + # Perform BFS + while Q and FreshCount > 0: + NumRotting = len(Q) + for _ in range(NumRotting): + i, j = Q.popleft() + for r, c in [(i, j + 1), (i + 1, j), (i, j - 1), (i - 1, j)]: + if 0 <= r < M and 0 <= c < N and grid[r][c] == 1: + grid[r][c] = 2 + FreshCount -= 1 + Q.append((r, c)) + Minute += 1 # Increment minute after processing all rotten oranges in this round + + # Return the time taken or -1 if fresh oranges remain + return Minute if FreshCount == 0 else -1 + + + +# Code for YouTube Video +from collections import deque +class Solution: + def orangesRotting(self, grid: List[List[int]]) -> int: + EMPTY, FRESH, ROTTEN = 0, 1, 2 + m, n = len(grid), len(grid[0]) + num_fresh = 0 + q = deque() + + for i in range(m): + for j in range(n): + if grid[i][j] == ROTTEN: + q.append((i, j)) + elif grid[i][j] == FRESH: + num_fresh += 1 + + if num_fresh == 0: + return 0 + + num_minutes = -1 + while q: + q_size = len(q) + num_minutes += 1 + + for _ in range(q_size): + i, j = q.popleft() + for r, c in [(i, j + 1), (i + 1, j), (i, j - 1), (i - 1, j)]: + if 0 <= r < m and 0 <= c < n and grid[r][c] == FRESH: + grid[r][c] = ROTTEN + num_fresh -= 1 + q.append((r, c)) + + if num_fresh == 0: + return num_minutes + else: + return -1 + +# Time Complexity: O(m*n) +# Space Complexity: O(m*n) diff --git a/Running Sum of 1d Array - Leetcode 1480/Running Sum of 1d Array - Leetcode 1480.cpp b/Running Sum of 1d Array - Leetcode 1480/Running Sum of 1d Array - Leetcode 1480.cpp new file mode 100644 index 0000000..94ddeae --- /dev/null +++ b/Running Sum of 1d Array - Leetcode 1480/Running Sum of 1d Array - Leetcode 1480.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector runningSum(vector& nums) { + int s = 0; + int n = nums.size(); + vector prefix_sum(n); + + for (int i = 0; i < n; i++) { + s += nums[i]; + prefix_sum[i] = s; + } + + return prefix_sum; + } + // Time: O(n) + // Space: O(n) +}; diff --git a/Running Sum of 1d Array - Leetcode 1480/Running Sum of 1d Array - Leetcode 1480.java b/Running Sum of 1d Array - Leetcode 1480/Running Sum of 1d Array - Leetcode 1480.java new file mode 100644 index 0000000..4949524 --- /dev/null +++ b/Running Sum of 1d Array - Leetcode 1480/Running Sum of 1d Array - Leetcode 1480.java @@ -0,0 +1,16 @@ +class Solution { + public int[] runningSum(int[] nums) { + int s = 0; + int n = nums.length; + int[] prefix_sum = new int[n]; + + for (int i = 0; i < n; i++) { + s += nums[i]; + prefix_sum[i] = s; + } + + return prefix_sum; + } + // Time: O(n) + // Space: O(n) +} diff --git a/Running Sum of 1d Array - Leetcode 1480/Running Sum of 1d Array - Leetcode 1480.js b/Running Sum of 1d Array - Leetcode 1480/Running Sum of 1d Array - Leetcode 1480.js new file mode 100644 index 0000000..518f15a --- /dev/null +++ b/Running Sum of 1d Array - Leetcode 1480/Running Sum of 1d Array - Leetcode 1480.js @@ -0,0 +1,14 @@ +var runningSum = function(nums) { + var s = 0; + var n = nums.length; + var prefix_sum = new Array(n).fill(0); + + for (var i = 0; i < n; i++) { + s += nums[i]; + prefix_sum[i] = s; + } + + return prefix_sum; + // Time: O(n) + // Space: O(n) +}; diff --git a/Running Sum of 1d Array - Leetcode 1480/Running Sum of 1d Array - Leetcode 1480.py b/Running Sum of 1d Array - Leetcode 1480/Running Sum of 1d Array - Leetcode 1480.py new file mode 100644 index 0000000..912cfd7 --- /dev/null +++ b/Running Sum of 1d Array - Leetcode 1480/Running Sum of 1d Array - Leetcode 1480.py @@ -0,0 +1,13 @@ +class Solution: + def runningSum(self, nums): + s = 0 + n = len(nums) + prefix_sum = [0] * n + + for i in range(n): + s += nums[i] + prefix_sum[i] = s + + return prefix_sum + # Time: O(n) + # Space: O(n) \ No newline at end of file diff --git a/Same Binary Tree - Leetcode 100.py b/Same Binary Tree - Leetcode 100.py deleted file mode 100644 index 920eff1..0000000 --- a/Same Binary Tree - Leetcode 100.py +++ /dev/null @@ -1,19 +0,0 @@ -class Solution: - def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: - - def balanced(p, q): - if not p and not q: - return True - - if (p and not q) or (q and not p): - return False - - if p.val != q.val: - return False - - return balanced(p.left, q.left) and balanced(p.right, q.right) - - return balanced(p, q) - -# Time Complexity: O(n) -# Space Complexity: O(h) { here "h" is the height of the tree } diff --git a/Same Binary Tree - Leetcode 100/Same Binary Tree - Leetcode 100.cpp b/Same Binary Tree - Leetcode 100/Same Binary Tree - Leetcode 100.cpp new file mode 100644 index 0000000..eb325dd --- /dev/null +++ b/Same Binary Tree - Leetcode 100/Same Binary Tree - Leetcode 100.cpp @@ -0,0 +1,17 @@ +#include + +class Solution { +public: + bool isSameTree(TreeNode* p, TreeNode* q) { + return isSame(p, q); + } + +private: + bool isSame(TreeNode* p, TreeNode* q) { + if (!p && !q) return true; + if (!p || !q) return false; + if (p->val != q->val) return false; + + return isSame(p->left, q->left) && isSame(p->right, q->right); + } +}; diff --git a/Same Binary Tree - Leetcode 100/Same Binary Tree - Leetcode 100.java b/Same Binary Tree - Leetcode 100/Same Binary Tree - Leetcode 100.java new file mode 100644 index 0000000..431e030 --- /dev/null +++ b/Same Binary Tree - Leetcode 100/Same Binary Tree - Leetcode 100.java @@ -0,0 +1,13 @@ +public class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + return isSame(p, q); + } + + private boolean isSame(TreeNode p, TreeNode q) { + if (p == null && q == null) return true; + if (p == null || q == null) return false; + if (p.val != q.val) return false; + + return isSame(p.left, q.left) && isSame(p.right, q.right); + } +} diff --git a/Same Binary Tree - Leetcode 100/Same Binary Tree - Leetcode 100.js b/Same Binary Tree - Leetcode 100/Same Binary Tree - Leetcode 100.js new file mode 100644 index 0000000..2d6d9bc --- /dev/null +++ b/Same Binary Tree - Leetcode 100/Same Binary Tree - Leetcode 100.js @@ -0,0 +1,11 @@ +var isSameTree = function(p, q) { + return isSame(p, q); +}; + +function isSame(p, q) { + if (!p && !q) return true; + if (!p || !q) return false; + if (p.val !== q.val) return false; + + return isSame(p.left, q.left) && isSame(p.right, q.right); +} diff --git a/Same Binary Tree - Leetcode 100/Same Binary Tree - Leetcode 100.py b/Same Binary Tree - Leetcode 100/Same Binary Tree - Leetcode 100.py new file mode 100644 index 0000000..da4e7fc --- /dev/null +++ b/Same Binary Tree - Leetcode 100/Same Binary Tree - Leetcode 100.py @@ -0,0 +1,26 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: + # 1: Both Null + if not p and not q: + return True + + # 2: One is Null + if (p and not q) or (q and not p): + return False + + # 3. Values Mismatch + if p.val != q.val: + return False + + return self.isSameTree(p.left, q.left) and \ + self.isSameTree(p.right, q.right) + +# Time Complexity: O(n + m) +# Space Complexity: O(n + m) +# m is number of nodes in p, n is number of nodes in Q. diff --git a/Search Insert Position - Leetcode 35/Search Insert Position - Leetcode 35.cpp b/Search Insert Position - Leetcode 35/Search Insert Position - Leetcode 35.cpp new file mode 100644 index 0000000..4f1e2e8 --- /dev/null +++ b/Search Insert Position - Leetcode 35/Search Insert Position - Leetcode 35.cpp @@ -0,0 +1,25 @@ +#include + +using namespace std; + +class Solution { +public: + int searchInsert(vector& nums, int target) { + int l = 0; + int r = nums.size() - 1; + + while (l <= r) { + int m = (l + r) / 2; + + if (nums[m] < target) { + l = m + 1; + } else if (nums[m] > target) { + r = m - 1; + } else { + return m; + } + } + + return l; + } +}; diff --git a/Search Insert Position - Leetcode 35/Search Insert Position - Leetcode 35.java b/Search Insert Position - Leetcode 35/Search Insert Position - Leetcode 35.java new file mode 100644 index 0000000..20385f9 --- /dev/null +++ b/Search Insert Position - Leetcode 35/Search Insert Position - Leetcode 35.java @@ -0,0 +1,20 @@ +public class Solution { + public int searchInsert(int[] nums, int target) { + int l = 0; + int r = nums.length - 1; + + while (l <= r) { + int m = (l + r) / 2; + + if (nums[m] < target) { + l = m + 1; + } else if (nums[m] > target) { + r = m - 1; + } else { + return m; + } + } + + return l; + } +} diff --git a/Search Insert Position - Leetcode 35/Search Insert Position - Leetcode 35.js b/Search Insert Position - Leetcode 35/Search Insert Position - Leetcode 35.js new file mode 100644 index 0000000..553643e --- /dev/null +++ b/Search Insert Position - Leetcode 35/Search Insert Position - Leetcode 35.js @@ -0,0 +1,18 @@ +var searchInsert = function(nums, target) { + let l = 0; + let r = nums.length - 1; + + while (l <= r) { + let m = Math.floor((l + r) / 2); + + if (nums[m] < target) { + l = m + 1; + } else if (nums[m] > target) { + r = m - 1; + } else { + return m; + } + } + + return l; +}; diff --git a/Search Insert Position - Leetcode 35.py b/Search Insert Position - Leetcode 35/Search Insert Position - Leetcode 35.py similarity index 100% rename from Search Insert Position - Leetcode 35.py rename to Search Insert Position - Leetcode 35/Search Insert Position - Leetcode 35.py diff --git a/Search a 2D Matrix - Leetcode 74.py b/Search a 2D Matrix - Leetcode 74.py deleted file mode 100644 index c45100a..0000000 --- a/Search a 2D Matrix - Leetcode 74.py +++ /dev/null @@ -1,25 +0,0 @@ -class Solution: - def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: - m = len(matrix) - n = len(matrix[0]) - t = m * n - l = 0 - r = t - 1 - - while l <= r: - m = (l + r) // 2 - i = m // n - j = m % n - mid_num = matrix[i][j] - - if target == mid_num: - return True - elif target < mid_num: - r = m - 1 - else: - l = m + 1 - - return False - -# Time Complexity: O(log(m * n)) -# Space Complexity: O(1) diff --git a/Search a 2D Matrix - Leetcode 74/Search a 2D Matrix - Leetcode 74.cpp b/Search a 2D Matrix - Leetcode 74/Search a 2D Matrix - Leetcode 74.cpp new file mode 100644 index 0000000..5c3477d --- /dev/null +++ b/Search a 2D Matrix - Leetcode 74/Search a 2D Matrix - Leetcode 74.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + bool searchMatrix(vector>& matrix, int target) { + int m = matrix.size(); + int n = matrix[0].size(); + int l = 0; + int r = m * n - 1; + + while (l <= r) { + int mid = (l + r) / 2; + int i = mid / n; + int j = mid % n; + int midNum = matrix[i][j]; + + if (target == midNum) { + return true; + } else if (target < midNum) { + r = mid - 1; + } else { + l = mid + 1; + } + } + + return false; + } +}; diff --git a/Search a 2D Matrix - Leetcode 74/Search a 2D Matrix - Leetcode 74.java b/Search a 2D Matrix - Leetcode 74/Search a 2D Matrix - Leetcode 74.java new file mode 100644 index 0000000..6541b9f --- /dev/null +++ b/Search a 2D Matrix - Leetcode 74/Search a 2D Matrix - Leetcode 74.java @@ -0,0 +1,25 @@ +public class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int m = matrix.length; + int n = matrix[0].length; + int l = 0; + int r = m * n - 1; + + while (l <= r) { + int mid = (l + r) / 2; + int i = mid / n; + int j = mid % n; + int midNum = matrix[i][j]; + + if (target == midNum) { + return true; + } else if (target < midNum) { + r = mid - 1; + } else { + l = mid + 1; + } + } + + return false; + } +} diff --git a/Search a 2D Matrix - Leetcode 74/Search a 2D Matrix - Leetcode 74.js b/Search a 2D Matrix - Leetcode 74/Search a 2D Matrix - Leetcode 74.js new file mode 100644 index 0000000..1feead2 --- /dev/null +++ b/Search a 2D Matrix - Leetcode 74/Search a 2D Matrix - Leetcode 74.js @@ -0,0 +1,23 @@ +var searchMatrix = function(matrix, target) { + let m = matrix.length; + let n = matrix[0].length; + let l = 0; + let r = m * n - 1; + + while (l <= r) { + let mid = Math.floor((l + r) / 2); + let i = Math.floor(mid / n); + let j = mid % n; + let midNum = matrix[i][j]; + + if (target === midNum) { + return true; + } else if (target < midNum) { + r = mid - 1; + } else { + l = mid + 1; + } + } + + return false; +}; diff --git a/Search a 2D Matrix - Leetcode 74/Search a 2D Matrix - Leetcode 74.py b/Search a 2D Matrix - Leetcode 74/Search a 2D Matrix - Leetcode 74.py new file mode 100644 index 0000000..18a6f3d --- /dev/null +++ b/Search a 2D Matrix - Leetcode 74/Search a 2D Matrix - Leetcode 74.py @@ -0,0 +1,50 @@ +# Brute Force Solution +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + for row in matrix: + if target in row: + return True + + return False +# Time: O(m * n) +# Space: O(1) + +# Brute Force Solution With (i, j) indices +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m, n = len(matrix), len(matrix[0]) + for i in range(m): + for j in range(n): + if target == matrix[i][j]: + return True + + return False +# Time: O(m * n) +# Space: O(1) + +# Optimal Solution +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + m = len(matrix) + n = len(matrix[0]) + t = m * n + l = 0 + r = t - 1 + + while l <= r: + mid = (l + r) // 2 + mid_i = mid // n + mid_j = mid % n + mid_num = matrix[mid_i][mid_j] + + if target == mid_num: + return True + elif target < mid_num: + r = mid - 1 + else: + l = mid + 1 + + return False + +# Time Complexity: O(log(m * n)) +# Space Complexity: O(1) diff --git a/Search in Rotated Sorted Array - Leetcode 33/Search in Rotated Sorted Array - Leetcode 33.cpp b/Search in Rotated Sorted Array - Leetcode 33/Search in Rotated Sorted Array - Leetcode 33.cpp new file mode 100644 index 0000000..77eae3f --- /dev/null +++ b/Search in Rotated Sorted Array - Leetcode 33/Search in Rotated Sorted Array - Leetcode 33.cpp @@ -0,0 +1,44 @@ +class Solution { +public: + int search(vector& nums, int target) { + int n = nums.size(); + int l = 0; + int r = n - 1; + + while (l < r) { + int m = (l + r) / 2; + + if (nums[m] > nums[r]) { + l = m + 1; + } else { + r = m; + } + } + + int minIndex = l; + + if (minIndex == 0) { + l = 0; + r = n - 1; + } else if (target >= nums[0] && target <= nums[minIndex - 1]) { + l = 0; + r = minIndex - 1; + } else { + l = minIndex; + r = n - 1; + } + + while (l <= r) { + int m = (l + r) / 2; + if (nums[m] == target) { + return m; + } else if (nums[m] < target) { + l = m + 1; + } else { + r = m - 1; + } + } + + return -1; + } +}; diff --git a/Search in Rotated Sorted Array - Leetcode 33/Search in Rotated Sorted Array - Leetcode 33.java b/Search in Rotated Sorted Array - Leetcode 33/Search in Rotated Sorted Array - Leetcode 33.java new file mode 100644 index 0000000..fe4dd30 --- /dev/null +++ b/Search in Rotated Sorted Array - Leetcode 33/Search in Rotated Sorted Array - Leetcode 33.java @@ -0,0 +1,43 @@ +public class Solution { + public int search(int[] nums, int target) { + int n = nums.length; + int l = 0; + int r = n - 1; + + while (l < r) { + int m = (l + r) / 2; + + if (nums[m] > nums[r]) { + l = m + 1; + } else { + r = m; + } + } + + int minIndex = l; + + if (minIndex == 0) { + l = 0; + r = n - 1; + } else if (target >= nums[0] && target <= nums[minIndex - 1]) { + l = 0; + r = minIndex - 1; + } else { + l = minIndex; + r = n - 1; + } + + while (l <= r) { + int m = (l + r) / 2; + if (nums[m] == target) { + return m; + } else if (nums[m] < target) { + l = m + 1; + } else { + r = m - 1; + } + } + + return -1; + } +} diff --git a/Search in Rotated Sorted Array - Leetcode 33/Search in Rotated Sorted Array - Leetcode 33.js b/Search in Rotated Sorted Array - Leetcode 33/Search in Rotated Sorted Array - Leetcode 33.js new file mode 100644 index 0000000..7e3dc80 --- /dev/null +++ b/Search in Rotated Sorted Array - Leetcode 33/Search in Rotated Sorted Array - Leetcode 33.js @@ -0,0 +1,41 @@ +var search = function(nums, target) { + let n = nums.length; + let l = 0; + let r = n - 1; + + while (l < r) { + let m = Math.floor((l + r) / 2); + + if (nums[m] > nums[r]) { + l = m + 1; + } else { + r = m; + } + } + + let minIndex = l; + + if (minIndex === 0) { + l = 0; + r = n - 1; + } else if (target >= nums[0] && target <= nums[minIndex - 1]) { + l = 0; + r = minIndex - 1; + } else { + l = minIndex; + r = n - 1; + } + + while (l <= r) { + let m = Math.floor((l + r) / 2); + if (nums[m] === target) { + return m; + } else if (nums[m] < target) { + l = m + 1; + } else { + r = m - 1; + } + } + + return -1; +}; diff --git a/Search in Rotated Sorted Array - Leetcode 33.py b/Search in Rotated Sorted Array - Leetcode 33/Search in Rotated Sorted Array - Leetcode 33.py similarity index 100% rename from Search in Rotated Sorted Array - Leetcode 33.py rename to Search in Rotated Sorted Array - Leetcode 33/Search in Rotated Sorted Array - Leetcode 33.py diff --git a/Single Number - Leetcode 136/Single Number - Leetcode 136.cpp b/Single Number - Leetcode 136/Single Number - Leetcode 136.cpp new file mode 100644 index 0000000..d758cfb --- /dev/null +++ b/Single Number - Leetcode 136/Single Number - Leetcode 136.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int singleNumber(vector& nums) { + int a = 0; + for (int x : nums) { + a ^= x; + } + return a; + } +}; diff --git a/Single Number - Leetcode 136/Single Number - Leetcode 136.java b/Single Number - Leetcode 136/Single Number - Leetcode 136.java new file mode 100644 index 0000000..5143e50 --- /dev/null +++ b/Single Number - Leetcode 136/Single Number - Leetcode 136.java @@ -0,0 +1,9 @@ +public class Solution { + public int singleNumber(int[] nums) { + int a = 0; + for (int x : nums) { + a ^= x; + } + return a; + } +} diff --git a/Single Number - Leetcode 136/Single Number - Leetcode 136.js b/Single Number - Leetcode 136/Single Number - Leetcode 136.js new file mode 100644 index 0000000..7cc42c2 --- /dev/null +++ b/Single Number - Leetcode 136/Single Number - Leetcode 136.js @@ -0,0 +1,7 @@ +var singleNumber = function(nums) { + let a = 0; + for (let x of nums) { + a ^= x; + } + return a; +}; diff --git a/Single Number - Leetcode 136/Single Number - Leetcode 136.py b/Single Number - Leetcode 136/Single Number - Leetcode 136.py new file mode 100644 index 0000000..df1c075 --- /dev/null +++ b/Single Number - Leetcode 136/Single Number - Leetcode 136.py @@ -0,0 +1,10 @@ +class Solution(object): + def singleNumber(self, nums: List[int]) -> int: + a = 0 + + for x in nums: + a ^= x + + return a + # Time: O(n) + # Space: O(1) \ No newline at end of file diff --git a/Sort Colors - Leetcode 75/Sort Colors - Leetcode 75.cpp b/Sort Colors - Leetcode 75/Sort Colors - Leetcode 75.cpp new file mode 100644 index 0000000..7128438 --- /dev/null +++ b/Sort Colors - Leetcode 75/Sort Colors - Leetcode 75.cpp @@ -0,0 +1,24 @@ +#include + +class Solution { +public: + void sortColors(std::vector& nums) { + int counts[3] = {0, 0, 0}; + + for (int color : nums) { + counts[color]++; + } + + int R = counts[0], W = counts[1], B = counts[2]; + + for (int i = 0; i < R; i++) { + nums[i] = 0; + } + for (int i = R; i < R + W; i++) { + nums[i] = 1; + } + for (int i = R + W; i < nums.size(); i++) { + nums[i] = 2; + } + } +}; diff --git a/Sort Colors - Leetcode 75/Sort Colors - Leetcode 75.java b/Sort Colors - Leetcode 75/Sort Colors - Leetcode 75.java new file mode 100644 index 0000000..b6483ce --- /dev/null +++ b/Sort Colors - Leetcode 75/Sort Colors - Leetcode 75.java @@ -0,0 +1,21 @@ +public class Solution { + public void sortColors(int[] nums) { + int[] counts = new int[3]; + + for (int color : nums) { + counts[color]++; + } + + int R = counts[0], W = counts[1], B = counts[2]; + + for (int i = 0; i < R; i++) { + nums[i] = 0; + } + for (int i = R; i < R + W; i++) { + nums[i] = 1; + } + for (int i = R + W; i < nums.length; i++) { + nums[i] = 2; + } + } +} diff --git a/Sort Colors - Leetcode 75/Sort Colors - Leetcode 75.js b/Sort Colors - Leetcode 75/Sort Colors - Leetcode 75.js new file mode 100644 index 0000000..88824c6 --- /dev/null +++ b/Sort Colors - Leetcode 75/Sort Colors - Leetcode 75.js @@ -0,0 +1,13 @@ +var sortColors = function(nums) { + let counts = [0, 0, 0]; + + for (let color of nums) { + counts[color]++; + } + + let R = counts[0], W = counts[1], B = counts[2]; + + nums.fill(0, 0, R); + nums.fill(1, R, R + W); + nums.fill(2, R + W, R + W + B); +}; diff --git a/Sort Colors - Leetcode 75/Sort Colors - Leetcode 75.py b/Sort Colors - Leetcode 75/Sort Colors - Leetcode 75.py new file mode 100644 index 0000000..ec2854e --- /dev/null +++ b/Sort Colors - Leetcode 75/Sort Colors - Leetcode 75.py @@ -0,0 +1,15 @@ +class Solution: + def sortColors(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + counts = [0, 0, 0] + + for color in nums: + counts[color] += 1 + + R, W, B = counts + + nums[:R] = [0] * R + nums[R:R+W] = [1] * W + nums[R+W:] = [2] * B \ No newline at end of file diff --git a/Spiral Matrix - Leetcode 54/Spiral Matrix - Leetcode 54.cpp b/Spiral Matrix - Leetcode 54/Spiral Matrix - Leetcode 54.cpp new file mode 100644 index 0000000..9e1770d --- /dev/null +++ b/Spiral Matrix - Leetcode 54/Spiral Matrix - Leetcode 54.cpp @@ -0,0 +1,65 @@ +#include + +using namespace std; + +class Solution { +public: + vector spiralOrder(vector>& matrix) { + vector ans; + if (matrix.empty()) return ans; + + int m = matrix.size(); + int n = matrix[0].size(); + int UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3; + int direction = RIGHT; + + int UP_WALL = 0; + int RIGHT_WALL = n; + int DOWN_WALL = m; + int LEFT_WALL = -1; + + int i = 0, j = 0; + + while (ans.size() != m * n) { + if (direction == RIGHT) { + while (j < RIGHT_WALL) { + ans.push_back(matrix[i][j]); + j++; + } + i++; + j--; + RIGHT_WALL--; + direction = DOWN; + } else if (direction == DOWN) { + while (i < DOWN_WALL) { + ans.push_back(matrix[i][j]); + i++; + } + i--; + j--; + DOWN_WALL--; + direction = LEFT; + } else if (direction == LEFT) { + while (j > LEFT_WALL) { + ans.push_back(matrix[i][j]); + j--; + } + i--; + j++; + LEFT_WALL++; + direction = UP; + } else { + while (i > UP_WALL) { + ans.push_back(matrix[i][j]); + i--; + } + i++; + j++; + UP_WALL++; + direction = RIGHT; + } + } + + return ans; + } +}; diff --git a/Spiral Matrix - Leetcode 54/Spiral Matrix - Leetcode 54.java b/Spiral Matrix - Leetcode 54/Spiral Matrix - Leetcode 54.java new file mode 100644 index 0000000..1b08d80 --- /dev/null +++ b/Spiral Matrix - Leetcode 54/Spiral Matrix - Leetcode 54.java @@ -0,0 +1,63 @@ +import java.util.ArrayList; +import java.util.List; + +public class Solution { + public List spiralOrder(int[][] matrix) { + List ans = new ArrayList<>(); + if (matrix.length == 0) return ans; + + int m = matrix.length; + int n = matrix[0].length; + int UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3; + int direction = RIGHT; + + int UP_WALL = 0; + int RIGHT_WALL = n; + int DOWN_WALL = m; + int LEFT_WALL = -1; + + int i = 0, j = 0; + + while (ans.size() != m * n) { + if (direction == RIGHT) { + while (j < RIGHT_WALL) { + ans.add(matrix[i][j]); + j++; + } + i++; + j--; + RIGHT_WALL--; + direction = DOWN; + } else if (direction == DOWN) { + while (i < DOWN_WALL) { + ans.add(matrix[i][j]); + i++; + } + i--; + j--; + DOWN_WALL--; + direction = LEFT; + } else if (direction == LEFT) { + while (j > LEFT_WALL) { + ans.add(matrix[i][j]); + j--; + } + i--; + j++; + LEFT_WALL++; + direction = UP; + } else { + while (i > UP_WALL) { + ans.add(matrix[i][j]); + i--; + } + i++; + j++; + UP_WALL++; + direction = RIGHT; + } + } + + return ans; + } +} diff --git a/Spiral Matrix - Leetcode 54/Spiral Matrix - Leetcode 54.js b/Spiral Matrix - Leetcode 54/Spiral Matrix - Leetcode 54.js new file mode 100644 index 0000000..0385ab2 --- /dev/null +++ b/Spiral Matrix - Leetcode 54/Spiral Matrix - Leetcode 54.js @@ -0,0 +1,58 @@ +var spiralOrder = function(matrix) { + let ans = []; + if (matrix.length === 0) return ans; + + let m = matrix.length; + let n = matrix[0].length; + const UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3; + let direction = RIGHT; + + let UP_WALL = 0; + let RIGHT_WALL = n; + let DOWN_WALL = m; + let LEFT_WALL = -1; + + let i = 0, j = 0; + + while (ans.length !== m * n) { + if (direction === RIGHT) { + while (j < RIGHT_WALL) { + ans.push(matrix[i][j]); + j++; + } + i++; + j--; + RIGHT_WALL--; + direction = DOWN; + } else if (direction === DOWN) { + while (i < DOWN_WALL) { + ans.push(matrix[i][j]); + i++; + } + i--; + j--; + DOWN_WALL--; + direction = LEFT; + } else if (direction === LEFT) { + while (j > LEFT_WALL) { + ans.push(matrix[i][j]); + j--; + } + i--; + j++; + LEFT_WALL++; + direction = UP; + } else { + while (i > UP_WALL) { + ans.push(matrix[i][j]); + i--; + } + i++; + j++; + UP_WALL++; + direction = RIGHT; + } + } + + return ans; +}; diff --git a/Spiral Matrix - Leetcode 54/Spiral Matrix - Leetcode 54.py b/Spiral Matrix - Leetcode 54/Spiral Matrix - Leetcode 54.py new file mode 100644 index 0000000..9f52cca --- /dev/null +++ b/Spiral Matrix - Leetcode 54/Spiral Matrix - Leetcode 54.py @@ -0,0 +1,46 @@ +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + m, n = len(matrix), len(matrix[0]) + ans = [] + i, j = 0, 0 + UP, RIGHT, DOWN, LEFT = 0, 1, 2, 3 + direction = RIGHT + + UP_WALL = 0 + RIGHT_WALL = n + DOWN_WALL = m + LEFT_WALL = -1 + + while len(ans) != m*n: + if direction == RIGHT: + while j < RIGHT_WALL: + ans.append(matrix[i][j]) + j += 1 + i, j = i+1, j-1 + RIGHT_WALL -= 1 + direction = DOWN + elif direction == DOWN: + while i < DOWN_WALL: + ans.append(matrix[i][j]) + i += 1 + i, j = i-1, j-1 + DOWN_WALL -= 1 + direction = LEFT + elif direction == LEFT: + while j > LEFT_WALL: + ans.append(matrix[i][j]) + j -= 1 + i, j = i-1, j+1 + LEFT_WALL += 1 + direction = UP + else: + while i > UP_WALL: + ans.append(matrix[i][j]) + i -= 1 + i, j = i+1, j+1 + UP_WALL += 1 + direction = RIGHT + + return ans + # Time: O(m*n) + # Space: O(1) diff --git a/Squares of a Sorted Array - Leetcode 977.py b/Squares of a Sorted Array - Leetcode 977.py deleted file mode 100644 index 1174376..0000000 --- a/Squares of a Sorted Array - Leetcode 977.py +++ /dev/null @@ -1,20 +0,0 @@ -class Solution: - def sortedSquares(self, nums: List[int]) -> List[int]: - left = 0 - right = len(nums) - 1 - result = [] - - while left <= right: - if abs(nums[left]) > abs(nums[right]): - result.append(nums[left] ** 2) - left += 1 - else: - result.append(nums[right] ** 2) - right -= 1 - - result.reverse() - - return result - -# Time Complexity: O(n) -# Space Complexity: O(1) diff --git a/Squares of a Sorted Array - Leetcode 977/Squares of a Sorted Array - Leetcode 977.cpp b/Squares of a Sorted Array - Leetcode 977/Squares of a Sorted Array - Leetcode 977.cpp new file mode 100644 index 0000000..e66ba65 --- /dev/null +++ b/Squares of a Sorted Array - Leetcode 977/Squares of a Sorted Array - Leetcode 977.cpp @@ -0,0 +1,25 @@ +#include +#include + +using namespace std; + +class Solution { +public: + vector sortedSquares(vector& nums) { + int left = 0, right = nums.size() - 1; + vector result(nums.size()); + int index = nums.size() - 1; + + while (left <= right) { + if (abs(nums[left]) > abs(nums[right])) { + result[index--] = nums[left] * nums[left]; + left++; + } else { + result[index--] = nums[right] * nums[right]; + right--; + } + } + + return result; + } +}; diff --git a/Squares of a Sorted Array - Leetcode 977/Squares of a Sorted Array - Leetcode 977.java b/Squares of a Sorted Array - Leetcode 977/Squares of a Sorted Array - Leetcode 977.java new file mode 100644 index 0000000..2fb887a --- /dev/null +++ b/Squares of a Sorted Array - Leetcode 977/Squares of a Sorted Array - Leetcode 977.java @@ -0,0 +1,21 @@ +import java.util.Arrays; + +public class Solution { + public int[] sortedSquares(int[] nums) { + int left = 0, right = nums.length - 1; + int[] result = new int[nums.length]; + int index = nums.length - 1; + + while (left <= right) { + if (Math.abs(nums[left]) > Math.abs(nums[right])) { + result[index--] = nums[left] * nums[left]; + left++; + } else { + result[index--] = nums[right] * nums[right]; + right--; + } + } + + return result; + } +} diff --git a/Squares of a Sorted Array - Leetcode 977/Squares of a Sorted Array - Leetcode 977.js b/Squares of a Sorted Array - Leetcode 977/Squares of a Sorted Array - Leetcode 977.js new file mode 100644 index 0000000..ffd32cc --- /dev/null +++ b/Squares of a Sorted Array - Leetcode 977/Squares of a Sorted Array - Leetcode 977.js @@ -0,0 +1,17 @@ +var sortedSquares = function(nums) { + let left = 0, right = nums.length - 1; + let result = new Array(nums.length); + let index = nums.length - 1; + + while (left <= right) { + if (Math.abs(nums[left]) > Math.abs(nums[right])) { + result[index--] = nums[left] * nums[left]; + left++; + } else { + result[index--] = nums[right] * nums[right]; + right--; + } + } + + return result; +}; diff --git a/Squares of a Sorted Array - Leetcode 977/Squares of a Sorted Array - Leetcode 977.py b/Squares of a Sorted Array - Leetcode 977/Squares of a Sorted Array - Leetcode 977.py new file mode 100644 index 0000000..2ed626c --- /dev/null +++ b/Squares of a Sorted Array - Leetcode 977/Squares of a Sorted Array - Leetcode 977.py @@ -0,0 +1,61 @@ +# Brute Force Solution +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + n = len(nums) + for i in range(n): + nums[i] = nums[i] ** 2 + + nums.sort() + + return nums + +# Time: O(n log n) +# Space: O(1) + +# Optimal Solution for Bootcamp +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + n = len(nums) + L, R = 0, n-1 + result = [0] * n + + for i in range(n): + nums[i] = nums[i] ** 2 + + j = n-1 + while L <= R: + if nums[L] > nums[R]: + result[j] = nums[L] + L += 1 + else: + result[j] = nums[R] + R -= 1 + + j -= 1 + + return result +# Time: O(n) +# Space: O(n) + + +# Optimal Solution in YT Video +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + left = 0 + right = len(nums) - 1 + result = [] + + while left <= right: + if abs(nums[left]) > abs(nums[right]): + result.append(nums[left] ** 2) + left += 1 + else: + result.append(nums[right] ** 2) + right -= 1 + + result.reverse() + + return result + +# Time Complexity: O(n) +# Space Complexity: O(n) diff --git a/Subsets - Leetcode 78/Subsets - Leetcode 78.cpp b/Subsets - Leetcode 78/Subsets - Leetcode 78.cpp new file mode 100644 index 0000000..16cf683 --- /dev/null +++ b/Subsets - Leetcode 78/Subsets - Leetcode 78.cpp @@ -0,0 +1,23 @@ +#include + +using namespace std; + +class Solution { +public: + vector> subsets(vector& nums) { + vector> res; + vector sol; + backtrack(nums, 0, sol, res); + return res; + } + +private: + void backtrack(vector& nums, int start, vector& sol, vector>& res) { + res.push_back(sol); + for (int i = start; i < nums.size(); i++) { + sol.push_back(nums[i]); + backtrack(nums, i + 1, sol, res); + sol.pop_back(); + } + } +}; diff --git a/Subsets - Leetcode 78/Subsets - Leetcode 78.java b/Subsets - Leetcode 78/Subsets - Leetcode 78.java new file mode 100644 index 0000000..f6df3a6 --- /dev/null +++ b/Subsets - Leetcode 78/Subsets - Leetcode 78.java @@ -0,0 +1,20 @@ +import java.util.ArrayList; +import java.util.List; + +public class Solution { + public List> subsets(int[] nums) { + List> res = new ArrayList<>(); + List sol = new ArrayList<>(); + backtrack(nums, 0, sol, res); + return res; + } + + private void backtrack(int[] nums, int start, List sol, List> res) { + res.add(new ArrayList<>(sol)); + for (int i = start; i < nums.length; i++) { + sol.add(nums[i]); + backtrack(nums, i + 1, sol, res); + sol.remove(sol.size() - 1); + } + } +} diff --git a/Subsets - Leetcode 78/Subsets - Leetcode 78.js b/Subsets - Leetcode 78/Subsets - Leetcode 78.js new file mode 100644 index 0000000..489d312 --- /dev/null +++ b/Subsets - Leetcode 78/Subsets - Leetcode 78.js @@ -0,0 +1,16 @@ +var subsets = function(nums) { + const res = []; + const sol = []; + + function backtrack(start) { + res.push([...sol]); + for (let i = start; i < nums.length; i++) { + sol.push(nums[i]); + backtrack(i + 1); + sol.pop(); + } + } + + backtrack(0); + return res; +}; diff --git a/Subsets - Leetcode 78.py b/Subsets - Leetcode 78/Subsets - Leetcode 78.py similarity index 83% rename from Subsets - Leetcode 78.py rename to Subsets - Leetcode 78/Subsets - Leetcode 78.py index 0739377..0c77de4 100644 --- a/Subsets - Leetcode 78.py +++ b/Subsets - Leetcode 78/Subsets - Leetcode 78.py @@ -1,11 +1,11 @@ class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: n = len(nums) - res, sol = [], [] + ans, sol = [], [] def backtrack(i): if i == n: - res.append(sol[:]) + ans.append(sol[:]) return # Don't pick nums[i] @@ -17,7 +17,7 @@ def backtrack(i): sol.pop() backtrack(0) - return res + return ans # Time Complexity: O(2^n) # Space Complexity: O(n) diff --git a/Subtree of Another Tree - Leetcode 572/Subtree of Another Tree - Leetcode 572.cpp b/Subtree of Another Tree - Leetcode 572/Subtree of Another Tree - Leetcode 572.cpp new file mode 100644 index 0000000..457a406 --- /dev/null +++ b/Subtree of Another Tree - Leetcode 572/Subtree of Another Tree - Leetcode 572.cpp @@ -0,0 +1,40 @@ +#include + +using namespace std; + + +class Solution { +public: + bool isSubtree(TreeNode* root, TreeNode* subRoot) { + return hasSubtree(root, subRoot); + } + +private: + bool hasSubtree(TreeNode* root, TreeNode* subRoot) { + if (!root) { + return false; + } + + if (isSameTree(root, subRoot)) { + return true; + } + + return hasSubtree(root->left, subRoot) || hasSubtree(root->right, subRoot); + } + + bool isSameTree(TreeNode* p, TreeNode* q) { + if (!p && !q) { + return true; + } + + if (!p || !q) { + return false; + } + + if (p->val != q->val) { + return false; + } + + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } +}; diff --git a/Subtree of Another Tree - Leetcode 572/Subtree of Another Tree - Leetcode 572.java b/Subtree of Another Tree - Leetcode 572/Subtree of Another Tree - Leetcode 572.java new file mode 100644 index 0000000..88af419 --- /dev/null +++ b/Subtree of Another Tree - Leetcode 572/Subtree of Another Tree - Leetcode 572.java @@ -0,0 +1,33 @@ +public class Solution { + public boolean isSubtree(TreeNode root, TreeNode subRoot) { + return hasSubtree(root, subRoot); + } + + private boolean hasSubtree(TreeNode root, TreeNode subRoot) { + if (root == null) { + return false; + } + + if (isSameTree(root, subRoot)) { + return true; + } + + return hasSubtree(root.left, subRoot) || hasSubtree(root.right, subRoot); + } + + private boolean isSameTree(TreeNode p, TreeNode q) { + if (p == null && q == null) { + return true; + } + + if (p == null || q == null) { + return false; + } + + if (p.val != q.val) { + return false; + } + + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } +} diff --git a/Subtree of Another Tree - Leetcode 572/Subtree of Another Tree - Leetcode 572.js b/Subtree of Another Tree - Leetcode 572/Subtree of Another Tree - Leetcode 572.js new file mode 100644 index 0000000..36e5382 --- /dev/null +++ b/Subtree of Another Tree - Leetcode 572/Subtree of Another Tree - Leetcode 572.js @@ -0,0 +1,16 @@ +var isSubtree = function(root, subRoot) { + function isSameTree(p, q) { + if (!p && !q) return true; + if (!p || !q) return false; + if (p.val !== q.val) return false; + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } + + function hasSubtree(root, subRoot) { + if (!root) return false; + if (isSameTree(root, subRoot)) return true; + return hasSubtree(root.left, subRoot) || hasSubtree(root.right, subRoot); + } + + return hasSubtree(root, subRoot); +}; diff --git a/Subtree of Another Tree - Leetcode 572.py b/Subtree of Another Tree - Leetcode 572/Subtree of Another Tree - Leetcode 572.py similarity index 100% rename from Subtree of Another Tree - Leetcode 572.py rename to Subtree of Another Tree - Leetcode 572/Subtree of Another Tree - Leetcode 572.py diff --git a/Summary Ranges - Leetcode 228/Summary Ranges - Leetcode 228.cpp b/Summary Ranges - Leetcode 228/Summary Ranges - Leetcode 228.cpp new file mode 100644 index 0000000..3cc109b --- /dev/null +++ b/Summary Ranges - Leetcode 228/Summary Ranges - Leetcode 228.cpp @@ -0,0 +1,27 @@ +#include +#include +using namespace std; + +class Solution { +public: + vector summaryRanges(vector& nums) { + vector ans; + int n = nums.size(); + int i = 0; + + while (i < n) { + int start = nums[i]; + while (i < n - 1 && nums[i] + 1 == nums[i + 1]) { + i++; + } + if (start != nums[i]) { + ans.push_back(to_string(start) + "->" + to_string(nums[i])); + } else { + ans.push_back(to_string(nums[i])); + } + i++; + } + + return ans; + } +}; diff --git a/Summary Ranges - Leetcode 228/Summary Ranges - Leetcode 228.java b/Summary Ranges - Leetcode 228/Summary Ranges - Leetcode 228.java new file mode 100644 index 0000000..ad65976 --- /dev/null +++ b/Summary Ranges - Leetcode 228/Summary Ranges - Leetcode 228.java @@ -0,0 +1,25 @@ +import java.util.ArrayList; +import java.util.List; + +public class Solution { + public List summaryRanges(int[] nums) { + List ans = new ArrayList<>(); + int n = nums.length; + int i = 0; + + while (i < n) { + int start = nums[i]; + while (i < n - 1 && nums[i] + 1 == nums[i + 1]) { + i++; + } + if (start != nums[i]) { + ans.add(start + "->" + nums[i]); + } else { + ans.add(String.valueOf(nums[i])); + } + i++; + } + + return ans; + } +} diff --git a/Summary Ranges - Leetcode 228/Summary Ranges - Leetcode 228.js b/Summary Ranges - Leetcode 228/Summary Ranges - Leetcode 228.js new file mode 100644 index 0000000..5ca0c9b --- /dev/null +++ b/Summary Ranges - Leetcode 228/Summary Ranges - Leetcode 228.js @@ -0,0 +1,19 @@ +var summaryRanges = function(nums) { + let ans = []; + let i = 0; + + while (i < nums.length) { + let start = nums[i]; + while (i < nums.length - 1 && nums[i] + 1 === nums[i + 1]) { + i++; + } + if (start !== nums[i]) { + ans.push(start + "->" + nums[i]); + } else { + ans.push(start.toString()); + } + i++; + } + + return ans; +}; diff --git a/Summary Ranges - Leetcode 228/Summary Ranges - Leetcode 228.py b/Summary Ranges - Leetcode 228/Summary Ranges - Leetcode 228.py new file mode 100644 index 0000000..25cb1e1 --- /dev/null +++ b/Summary Ranges - Leetcode 228/Summary Ranges - Leetcode 228.py @@ -0,0 +1,20 @@ +class Solution: + def summaryRanges(self, nums: List[int]) -> List[str]: + ans = [] + i = 0 + + while i < len(nums): + start = nums[i] + while i < len(nums)-1 and nums[i] + 1 == nums[i + 1]: + i += 1 + + if start != nums[i]: + ans.append(str(start) + "->" + str(nums[i])) + else: + ans.append(str(nums[i])) + + i += 1 + + return ans + # Time: O(n) + # Space: O(n) diff --git a/Symmetric Tree - Leetcode 101/Symmetric Tree - Leetcode 101.cpp b/Symmetric Tree - Leetcode 101/Symmetric Tree - Leetcode 101.cpp new file mode 100644 index 0000000..2e8313c --- /dev/null +++ b/Symmetric Tree - Leetcode 101/Symmetric Tree - Leetcode 101.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + bool isSymmetric(TreeNode* root) { + return isMirror(root, root); + } + +private: + bool isMirror(TreeNode* t1, TreeNode* t2) { + if (!t1 && !t2) return true; + if (!t1 || !t2) return false; + if (t1->val != t2->val) return false; + + return isMirror(t1->left, t2->right) && isMirror(t1->right, t2->left); + } +}; diff --git a/Symmetric Tree - Leetcode 101/Symmetric Tree - Leetcode 101.java b/Symmetric Tree - Leetcode 101/Symmetric Tree - Leetcode 101.java new file mode 100644 index 0000000..9505535 --- /dev/null +++ b/Symmetric Tree - Leetcode 101/Symmetric Tree - Leetcode 101.java @@ -0,0 +1,13 @@ +public class Solution { + public boolean isSymmetric(TreeNode root) { + return isMirror(root, root); + } + + private boolean isMirror(TreeNode t1, TreeNode t2) { + if (t1 == null && t2 == null) return true; + if (t1 == null || t2 == null) return false; + if (t1.val != t2.val) return false; + + return isMirror(t1.left, t2.right) && isMirror(t1.right, t2.left); + } +} diff --git a/Symmetric Tree - Leetcode 101/Symmetric Tree - Leetcode 101.js b/Symmetric Tree - Leetcode 101/Symmetric Tree - Leetcode 101.js new file mode 100644 index 0000000..254cd65 --- /dev/null +++ b/Symmetric Tree - Leetcode 101/Symmetric Tree - Leetcode 101.js @@ -0,0 +1,11 @@ +var isSymmetric = function(root) { + function isMirror(t1, t2) { + if (t1 === null && t2 === null) return true; + if (t1 === null || t2 === null) return false; + if (t1.val !== t2.val) return false; + + return isMirror(t1.left, t2.right) && isMirror(t1.right, t2.left); + } + + return isMirror(root, root); +}; diff --git a/Symmetric Tree - Leetcode 101/Symmetric Tree - Leetcode 101.py b/Symmetric Tree - Leetcode 101/Symmetric Tree - Leetcode 101.py new file mode 100644 index 0000000..8693257 --- /dev/null +++ b/Symmetric Tree - Leetcode 101/Symmetric Tree - Leetcode 101.py @@ -0,0 +1,24 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isSymmetric(self, root: Optional[TreeNode]) -> bool: + def same(root1, root2): + if not root1 and not root2: + return True + + if not root1 or not root2: + return False + + if root1.val != root2.val: + return False + + return same(root1.left, root2.right) and \ + same(root1.right, root2.left) + + return same(root, root) + # Time: O(n) + # Space: O(height) or O(n) diff --git a/Top K Frequent Elements - Leetcode 347.py b/Top K Frequent Elements - Leetcode 347.py deleted file mode 100644 index 1aea9e1..0000000 --- a/Top K Frequent Elements - Leetcode 347.py +++ /dev/null @@ -1,24 +0,0 @@ -from collections import Counter -class Solution: - def topKFrequent(self, nums: List[int], k: int) -> List[int]: - n = len(nums) - counter = Counter(nums) - buckets = [0] * (n + 1) - - for num, freq in counter.items(): - if buckets[freq] == 0: - buckets[freq] = [num] - else: - buckets[freq].append(num) - - ret = [] - for i in range(n, -1, -1): - if buckets[i] != 0: - ret.extend(buckets[i]) - if len(ret) == k: - break - - return ret - -# Time Complexity: O(n) -# Space Complexity: O(n) diff --git a/Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.cpp b/Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.cpp new file mode 100644 index 0000000..e419556 --- /dev/null +++ b/Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.cpp @@ -0,0 +1,86 @@ + +#include +#include +#include +#include +using namespace std; + +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map countMap; + for (int num : nums) { + countMap[num]++; + } + + auto cmp = [](const pair& a, const pair& b) { + return a.second > b.second; + }; + + priority_queue, vector>, decltype(cmp)> minHeap(cmp); + + for (auto& entry : countMap) { + if (minHeap.size() < k) { + minHeap.push(entry); + } else { + minHeap.push(entry); + minHeap.pop(); + } + } + + vector topK; + while (!minHeap.empty()) { + topK.push_back(minHeap.top().first); + minHeap.pop(); + } + + reverse(topK.begin(), topK.end()); + return topK; + } +}; + + + + + + + + + + + + + +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map count; + for (int num : nums) { + count[num]++; + } + + vector> buckets(nums.size() + 1); + for (auto& entry : count) { + buckets[entry.second].push_back(entry.first); + } + + vector result; + for (int i = buckets.size() - 1; i >= 0; --i) { + if (!buckets[i].empty()) { + result.insert(result.end(), buckets[i].begin(), buckets[i].end()); + if (result.size() >= k) { + result.resize(k); + break; + } + } + } + + return result; + } +}; diff --git a/Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.java b/Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.java new file mode 100644 index 0000000..39d16f3 --- /dev/null +++ b/Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.java @@ -0,0 +1,82 @@ +import java.util.*; + +public class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map countMap = new HashMap<>(); + for (int num : nums) { + countMap.put(num, countMap.getOrDefault(num, 0) + 1); + } + + PriorityQueue> heap = new PriorityQueue<>( + (a, b) -> Integer.compare(a.getValue(), b.getValue()) + ); + + for (Map.Entry entry : countMap.entrySet()) { + if (heap.size() < k) { + heap.offer(entry); + } else { + heap.offer(entry); + heap.poll(); + } + } + + int[] topK = new int[k]; + for (int i = k - 1; i >= 0; i--) { + topK[i] = heap.poll().getKey(); + } + + return topK; + } +} + + + + + + + + + + + + + + +import java.util.*; + +public class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map count = new HashMap<>(); + for (int num : nums) { + count.put(num, count.getOrDefault(num, 0) + 1); + } + + List[] buckets = new ArrayList[nums.length + 1]; + for (int i = 0; i < buckets.length; i++) { + buckets[i] = new ArrayList<>(); + } + + for (Map.Entry entry : count.entrySet()) { + int num = entry.getKey(); + int freq = entry.getValue(); + buckets[freq].add(num); + } + + List result = new ArrayList<>(); + for (int i = buckets.length - 1; i >= 0; --i) { + if (!buckets[i].isEmpty()) { + result.addAll(buckets[i]); + if (result.size() >= k) { + break; + } + } + } + + // Convert result to int[] + int[] resultArray = new int[k]; + for (int i = 0; i < k; i++) { + resultArray[i] = result.get(i); + } + return resultArray; + } +} diff --git a/Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.js b/Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.js new file mode 100644 index 0000000..e8ffa21 --- /dev/null +++ b/Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.js @@ -0,0 +1,124 @@ +var topKFrequent = function(nums, k) { + const countMap = new Map(); + for (const num of nums) { + countMap.set(num, (countMap.get(num) || 0) + 1); + } + + const heap = new MinHeap(); + + for (const [num, freq] of countMap) { + if (heap.size() < k) { + heap.add([freq, num]); + } else { + heap.add([freq, num]); + heap.poll(); + } + } + + return heap.toArray().map(pair => pair[1]); +}; + +// Helper class for MinHeap +class MinHeap { + constructor() { + this.heap = []; + } + + size() { + return this.heap.length; + } + + add(pair) { + this.heap.push(pair); + this.bubbleUp(); + } + + poll() { + const min = this.heap[0]; + const end = this.heap.pop(); + if (this.size() > 0) { + this.heap[0] = end; + this.bubbleDown(); + } + return min; + } + + bubbleUp() { + let idx = this.size() - 1; + const element = this.heap[idx]; + while (idx > 0) { + let parentIdx = Math.floor((idx - 1) / 2); + let parent = this.heap[parentIdx]; + if (element[0] >= parent[0]) break; + this.heap[idx] = parent; + idx = parentIdx; + } + this.heap[idx] = element; + } + + bubbleDown() { + let idx = 0; + const length = this.size(); + const element = this.heap[0]; + while (true) { + let leftChildIdx = 2 * idx + 1; + let rightChildIdx = 2 * idx + 2; + let swap = null; + + if (leftChildIdx < length) { + let leftChild = this.heap[leftChildIdx]; + if (leftChild[0] < element[0]) { + swap = leftChildIdx; + } + } + + if (rightChildIdx < length) { + let rightChild = this.heap[rightChildIdx]; + if ((swap === null && rightChild[0] < element[0]) || + (swap !== null && rightChild[0] < this.heap[swap][0])) { + swap = rightChildIdx; + } + } + + if (swap === null) break; + this.heap[idx] = this.heap[swap]; + idx = swap; + } + this.heap[idx] = element; + } + + toArray() { + return this.heap; + } +} + + + + + + + + + + +var topKFrequent = function(nums, k) { + const count = new Map(); + for (const num of nums) { + count.set(num, (count.get(num) || 0) + 1); + } + + const buckets = Array.from({ length: nums.length + 1 }, () => []); + for (const [num, freq] of count.entries()) { + buckets[freq].push(num); + } + + const result = []; + for (let i = buckets.length - 1; i >= 0; i--) { + if (buckets[i].length > 0) { + result.push(...buckets[i]); + if (result.length >= k) { + return result.slice(0, k); + } + } + } +}; diff --git a/Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.py b/Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.py new file mode 100644 index 0000000..a89a7e6 --- /dev/null +++ b/Top K Frequent Elements - Leetcode 347/Top K Frequent Elements - Leetcode 347.py @@ -0,0 +1,59 @@ +# Heap Solution: +from collections import Counter +import heapq +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + counter = Counter(nums) + heap = [] + + for key, val in counter.items(): + if len(heap) < k: + heapq.heappush(heap, (val, key)) + else: + heapq.heappushpop(heap, (val, key)) + + return [h[1] for h in heap] + # Time: O(n log k), Space: O(k) + + +import heapq +from collections import Counter + +def top_k_frequent(nums, k): + # Step 1: Count frequency + freq_map = Counter(nums) + + # Step 2: Use max heap (invert frequency to simulate max heap) + max_heap = [(-freq, num) for num, freq in freq_map.items()] + heapq.heapify(max_heap) # Convert list into a heap in O(n) + + # Step 3: Extract k most frequent elements + result = [heapq.heappop(max_heap)[1] for _ in range(k)] + return result + # Max Heap + +# Buckets +from collections import Counter +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + n = len(nums) + counter = Counter(nums) + buckets = [0] * (n + 1) + + for num, freq in counter.items(): + if buckets[freq] == 0: + buckets[freq] = [num] + else: + buckets[freq].append(num) + + ret = [] + for i in range(n, -1, -1): + if buckets[i] != 0: + ret.extend(buckets[i]) + if len(ret) == k: + break + + return ret + +# Time Complexity: O(n) +# Space Complexity: O(n) diff --git a/Trapping Rain Water - Leetcode 42/Trapping Rain Water - Leetcode 42.cpp b/Trapping Rain Water - Leetcode 42/Trapping Rain Water - Leetcode 42.cpp new file mode 100644 index 0000000..28e8df7 --- /dev/null +++ b/Trapping Rain Water - Leetcode 42/Trapping Rain Water - Leetcode 42.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + int trap(vector& height) { + int n = height.size(); + vector maxLeft(n, 0); + vector maxRight(n, 0); + + int lWall = 0, rWall = 0; + + for (int i = 0; i < n; ++i) { + int j = n - i - 1; + maxLeft[i] = lWall; + maxRight[j] = rWall; + lWall = max(lWall, height[i]); + rWall = max(rWall, height[j]); + } + + int sum = 0; + for (int i = 0; i < n; ++i) { + int pot = min(maxLeft[i], maxRight[i]); + sum += max(0, pot - height[i]); + } + + return sum; + } +}; diff --git a/Trapping Rain Water - Leetcode 42/Trapping Rain Water - Leetcode 42.java b/Trapping Rain Water - Leetcode 42/Trapping Rain Water - Leetcode 42.java new file mode 100644 index 0000000..e7a2612 --- /dev/null +++ b/Trapping Rain Water - Leetcode 42/Trapping Rain Water - Leetcode 42.java @@ -0,0 +1,25 @@ +public class Solution { + public int trap(int[] height) { + int n = height.length; + int[] maxLeft = new int[n]; + int[] maxRight = new int[n]; + + int lWall = 0, rWall = 0; + + for (int i = 0; i < n; i++) { + int j = n - i - 1; + maxLeft[i] = lWall; + maxRight[j] = rWall; + lWall = Math.max(lWall, height[i]); + rWall = Math.max(rWall, height[j]); + } + + int sum = 0; + for (int i = 0; i < n; i++) { + int pot = Math.min(maxLeft[i], maxRight[i]); + sum += Math.max(0, pot - height[i]); + } + + return sum; + } +} diff --git a/Trapping Rain Water - Leetcode 42/Trapping Rain Water - Leetcode 42.js b/Trapping Rain Water - Leetcode 42/Trapping Rain Water - Leetcode 42.js new file mode 100644 index 0000000..e21538c --- /dev/null +++ b/Trapping Rain Water - Leetcode 42/Trapping Rain Water - Leetcode 42.js @@ -0,0 +1,23 @@ +var trap = function(height) { + const n = height.length; + const maxLeft = Array(n).fill(0); + const maxRight = Array(n).fill(0); + + let lWall = 0, rWall = 0; + + for (let i = 0; i < n; i++) { + const j = n - i - 1; + maxLeft[i] = lWall; + maxRight[j] = rWall; + lWall = Math.max(lWall, height[i]); + rWall = Math.max(rWall, height[j]); + } + + let sum = 0; + for (let i = 0; i < n; i++) { + const pot = Math.min(maxLeft[i], maxRight[i]); + sum += Math.max(0, pot - height[i]); + } + + return sum; +}; diff --git a/Trapping Rain Water - Leetcode 42.py b/Trapping Rain Water - Leetcode 42/Trapping Rain Water - Leetcode 42.py similarity index 100% rename from Trapping Rain Water - Leetcode 42.py rename to Trapping Rain Water - Leetcode 42/Trapping Rain Water - Leetcode 42.py diff --git a/Two Sum - Leetcode 1.py b/Two Sum - Leetcode 1.py deleted file mode 100644 index 620d24a..0000000 --- a/Two Sum - Leetcode 1.py +++ /dev/null @@ -1,14 +0,0 @@ -class Solution: - def twoSum(self, nums: List[int], target: int) -> List[int]: - h = {} - for i in range(len(nums)): - h[nums[i]] = i - - for i in range(len(nums)): - y = target - nums[i] - - if y in h and h[y] != i: - return [i, h[y]] - -# Time Complexity: O(n) -# Space Complexity: O(n) diff --git a/Two Sum - Leetcode 1/Two Sum - Leetcode 1.cpp b/Two Sum - Leetcode 1/Two Sum - Leetcode 1.cpp new file mode 100644 index 0000000..538590b --- /dev/null +++ b/Two Sum - Leetcode 1/Two Sum - Leetcode 1.cpp @@ -0,0 +1,22 @@ +#include +#include +using namespace std; + +class Solution { +public: + vector twoSum(vector& nums, int target) { + unordered_map h; + for (int i = 0; i < nums.size(); ++i) { + h[nums[i]] = i; + } + + for (int i = 0; i < nums.size(); ++i) { + int y = target - nums[i]; + if (h.find(y) != h.end() && h[y] != i) { + return {i, h[y]}; + } + } + + throw invalid_argument("No two sum solution"); + } +}; diff --git a/Two Sum - Leetcode 1/Two Sum - Leetcode 1.java b/Two Sum - Leetcode 1/Two Sum - Leetcode 1.java new file mode 100644 index 0000000..3c4e059 --- /dev/null +++ b/Two Sum - Leetcode 1/Two Sum - Leetcode 1.java @@ -0,0 +1,20 @@ +import java.util.HashMap; +import java.util.Map; + +public class Solution { + public int[] twoSum(int[] nums, int target) { + Map h = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + h.put(nums[i], i); + } + + for (int i = 0; i < nums.length; i++) { + int y = target - nums[i]; + if (h.containsKey(y) && h.get(y) != i) { + return new int[] {i, h.get(y)}; + } + } + + throw new IllegalArgumentException("No two sum solution"); + } +} diff --git a/Two Sum - Leetcode 1/Two Sum - Leetcode 1.js b/Two Sum - Leetcode 1/Two Sum - Leetcode 1.js new file mode 100644 index 0000000..2696906 --- /dev/null +++ b/Two Sum - Leetcode 1/Two Sum - Leetcode 1.js @@ -0,0 +1,15 @@ +var twoSum = function(nums, target) { + const h = new Map(); + for (let i = 0; i < nums.length; i++) { + h.set(nums[i], i); + } + + for (let i = 0; i < nums.length; i++) { + const y = target - nums[i]; + if (h.has(y) && h.get(y) !== i) { + return [i, h.get(y)]; + } + } + + throw new Error("No two sum solution"); +}; diff --git a/Two Sum - Leetcode 1/Two Sum - Leetcode 1.py b/Two Sum - Leetcode 1/Two Sum - Leetcode 1.py new file mode 100644 index 0000000..7b51c94 --- /dev/null +++ b/Two Sum - Leetcode 1/Two Sum - Leetcode 1.py @@ -0,0 +1,50 @@ +# Brute Force Solution +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + n = len(nums) + for i in range(n): + for j in range(n): + if nums[i] + nums[j] == target and i != j: + return (i, j) + # Time: O(n^2) + # Space: O(1) + +# Better Brute Force Solution +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + n = len(nums) + for i in range(n): + for j in range(i+1, n): + if nums[i] + nums[j] == target: + return (i, j) + # Time: O(n^2) + # Space: O(1) + +# 2-Pass Optimal Solution +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + h = {} + for i in range(len(nums)): + h[nums[i]] = i + + for i in range(len(nums)): + y = target - nums[i] + + if y in h and h[y] != i: + return [i, h[y]] +# Time Complexity: O(n) +# Space Complexity: O(n) + +# One-Pass Optimal Solution (For Bootcamp) +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + h = {} + n = len(nums) + for i, x in enumerate(nums): + y = target - x + if y in h: + return [i, h[y]] + else: + h[x] = i +# Time Complexity: O(n) +# Space Complexity: O(n) diff --git a/Two Sum II - Leetcode 167/Two Sum II - Leetcode 167.cpp b/Two Sum II - Leetcode 167/Two Sum II - Leetcode 167.cpp new file mode 100644 index 0000000..136b0bd --- /dev/null +++ b/Two Sum II - Leetcode 167/Two Sum II - Leetcode 167.cpp @@ -0,0 +1,23 @@ +#include +using namespace std; + +class Solution { +public: + vector twoSum(vector& numbers, int target) { + int l = 0; + int r = numbers.size() - 1; + + while (l < r) { + int sum = numbers[l] + numbers[r]; + if (sum == target) { + return {l + 1, r + 1}; + } else if (sum < target) { + l++; + } else { + r--; + } + } + + throw invalid_argument("No two sum solution"); + } +}; diff --git a/Two Sum II - Leetcode 167/Two Sum II - Leetcode 167.java b/Two Sum II - Leetcode 167/Two Sum II - Leetcode 167.java new file mode 100644 index 0000000..6019e8a --- /dev/null +++ b/Two Sum II - Leetcode 167/Two Sum II - Leetcode 167.java @@ -0,0 +1,19 @@ +public class Solution { + public int[] twoSum(int[] numbers, int target) { + int l = 0; + int r = numbers.length - 1; + + while (l < r) { + int sum = numbers[l] + numbers[r]; + if (sum == target) { + return new int[] {l + 1, r + 1}; + } else if (sum < target) { + l++; + } else { + r--; + } + } + + throw new IllegalArgumentException("No two sum solution"); + } +} diff --git a/Two Sum II - Leetcode 167/Two Sum II - Leetcode 167.js b/Two Sum II - Leetcode 167/Two Sum II - Leetcode 167.js new file mode 100644 index 0000000..cf7a15c --- /dev/null +++ b/Two Sum II - Leetcode 167/Two Sum II - Leetcode 167.js @@ -0,0 +1,17 @@ +var twoSum = function(numbers, target) { + let l = 0; + let r = numbers.length - 1; + + while (l < r) { + let sum = numbers[l] + numbers[r]; + if (sum === target) { + return [l + 1, r + 1]; + } else if (sum < target) { + l++; + } else { + r--; + } + } + + throw new Error("No two sum solution"); +}; diff --git a/Two Sum II - Leetcode 167.py b/Two Sum II - Leetcode 167/Two Sum II - Leetcode 167.py similarity index 100% rename from Two Sum II - Leetcode 167.py rename to Two Sum II - Leetcode 167/Two Sum II - Leetcode 167.py diff --git a/Unique Paths - Leetcode 62/Unique Paths - Leetcode 62.cpp b/Unique Paths - Leetcode 62/Unique Paths - Leetcode 62.cpp new file mode 100644 index 0000000..19da20b --- /dev/null +++ b/Unique Paths - Leetcode 62/Unique Paths - Leetcode 62.cpp @@ -0,0 +1,23 @@ +#include +using namespace std; + +class Solution { +public: + int uniquePaths(int m, int n) { + vector> dp(m, vector(n, 0)); + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (i == 0 && j == 0) { + dp[i][j] = 1; + } else { + int fromTop = (i > 0) ? dp[i - 1][j] : 0; + int fromLeft = (j > 0) ? dp[i][j - 1] : 0; + dp[i][j] = fromTop + fromLeft; + } + } + } + + return dp[m - 1][n - 1]; + } +}; diff --git a/Unique Paths - Leetcode 62/Unique Paths - Leetcode 62.java b/Unique Paths - Leetcode 62/Unique Paths - Leetcode 62.java new file mode 100644 index 0000000..c5db3a1 --- /dev/null +++ b/Unique Paths - Leetcode 62/Unique Paths - Leetcode 62.java @@ -0,0 +1,19 @@ +public class Solution { + public int uniquePaths(int m, int n) { + int[][] dp = new int[m][n]; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (i == 0 && j == 0) { + dp[i][j] = 1; + } else { + int fromTop = (i > 0) ? dp[i - 1][j] : 0; + int fromLeft = (j > 0) ? dp[i][j - 1] : 0; + dp[i][j] = fromTop + fromLeft; + } + } + } + + return dp[m - 1][n - 1]; + } +} diff --git a/Unique Paths - Leetcode 62/Unique Paths - Leetcode 62.js b/Unique Paths - Leetcode 62/Unique Paths - Leetcode 62.js new file mode 100644 index 0000000..13f85b3 --- /dev/null +++ b/Unique Paths - Leetcode 62/Unique Paths - Leetcode 62.js @@ -0,0 +1,17 @@ +var uniquePaths = function(m, n) { + let dp = Array(m).fill().map(() => Array(n).fill(0)); + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (i === 0 && j === 0) { + dp[i][j] = 1; + } else { + let fromTop = i > 0 ? dp[i - 1][j] : 0; + let fromLeft = j > 0 ? dp[i][j - 1] : 0; + dp[i][j] = fromTop + fromLeft; + } + } + } + + return dp[m - 1][n - 1]; +}; diff --git a/Unique Paths - Leetcode 62/Unique Paths - Leetcode 62.py b/Unique Paths - Leetcode 62/Unique Paths - Leetcode 62.py new file mode 100644 index 0000000..542f1f4 --- /dev/null +++ b/Unique Paths - Leetcode 62/Unique Paths - Leetcode 62.py @@ -0,0 +1,66 @@ +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + # Recursive Solution + # Time: O(2^(m*n)) + # Space: O(m*n) + + def paths(i, j): + if i == j == 0: + return 1 + elif i < 0 or j < 0 or i == m or j == n: + return 0 + else: + return paths(i-1, j) + paths(i, j-1) + + return paths(m-1, n-1) + + + +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + # Top Down DP (Memoization) + # Time: O(m*n) + # Space: O(m*n) + + memo = {(0,0): 1} + def paths(i, j): + if (i,j) in memo: + return memo[(i,j)] + elif i < 0 or j < 0 or i == m or j == n: + return 0 + else: + val = paths(i, j-1) + paths(i-1, j) + memo[(i,j)] = val + return val + + return paths(m-1, n-1) + + + +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + # Bottom Up DP (Tabulation) + # Time: O(m*n) + # Space: O(m*n) + + dp = [] + for _ in range(m): + dp.append([0] * n) + + dp[0][0] = 1 + + for i in range(m): + for j in range(n): + if i == j == 0: + continue + + val = 0 + if i > 0: + val += dp[i-1][j] + if j > 0: + val += dp[i][j-1] + + dp[i][j] = val + + return dp[m-1][n-1] + diff --git a/Valid Anagram - Leetcode 242/Valid Anagram - Leetcode 242.cpp b/Valid Anagram - Leetcode 242/Valid Anagram - Leetcode 242.cpp new file mode 100644 index 0000000..26fdcda --- /dev/null +++ b/Valid Anagram - Leetcode 242/Valid Anagram - Leetcode 242.cpp @@ -0,0 +1,24 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool isAnagram(string s, string t) { + if (s.size() != t.size()) { + return false; + } + + unordered_map sMap, tMap; + + for (char c : s) { + sMap[c]++; + } + + for (char c : t) { + tMap[c]++; + } + + return sMap == tMap; + } +}; diff --git a/Valid Anagram - Leetcode 242/Valid Anagram - Leetcode 242.java b/Valid Anagram - Leetcode 242/Valid Anagram - Leetcode 242.java new file mode 100644 index 0000000..e914544 --- /dev/null +++ b/Valid Anagram - Leetcode 242/Valid Anagram - Leetcode 242.java @@ -0,0 +1,22 @@ +import java.util.HashMap; + +public class Solution { + public boolean isAnagram(String s, String t) { + if (s.length() != t.length()) { + return false; + } + + HashMap sMap = new HashMap<>(); + HashMap tMap = new HashMap<>(); + + for (char c : s.toCharArray()) { + sMap.put(c, sMap.getOrDefault(c, 0) + 1); + } + + for (char c : t.toCharArray()) { + tMap.put(c, tMap.getOrDefault(c, 0) + 1); + } + + return sMap.equals(tMap); + } +} diff --git a/Valid Anagram - Leetcode 242/Valid Anagram - Leetcode 242.js b/Valid Anagram - Leetcode 242/Valid Anagram - Leetcode 242.js new file mode 100644 index 0000000..533cb73 --- /dev/null +++ b/Valid Anagram - Leetcode 242/Valid Anagram - Leetcode 242.js @@ -0,0 +1,24 @@ +var isAnagram = function(s, t) { + if (s.length !== t.length) { + return false; + } + + const sCount = {}; + const tCount = {}; + + for (const char of s) { + sCount[char] = (sCount[char] || 0) + 1; + } + + for (const char of t) { + tCount[char] = (tCount[char] || 0) + 1; + } + + for (const key in sCount) { + if (sCount[key] !== tCount[key]) { + return false; + } + } + + return true; +}; diff --git a/Valid Anagram - Leetcode 242.py b/Valid Anagram - Leetcode 242/Valid Anagram - Leetcode 242.py similarity index 87% rename from Valid Anagram - Leetcode 242.py rename to Valid Anagram - Leetcode 242/Valid Anagram - Leetcode 242.py index f50edef..3d85457 100644 --- a/Valid Anagram - Leetcode 242.py +++ b/Valid Anagram - Leetcode 242/Valid Anagram - Leetcode 242.py @@ -9,5 +9,6 @@ def isAnagram(self, s: str, t: str) -> bool: return s_dict == t_dict +# Let n be the length of the longest word # Time complexity: O(n) # Space complexity: O(n) diff --git a/Valid Palindrome - Leetcode 125/Valid Palindrome - Leetcode 125.cpp b/Valid Palindrome - Leetcode 125/Valid Palindrome - Leetcode 125.cpp new file mode 100644 index 0000000..9ee816a --- /dev/null +++ b/Valid Palindrome - Leetcode 125/Valid Palindrome - Leetcode 125.cpp @@ -0,0 +1,25 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool isPalindrome(string s) { + int L = 0, R = s.size() - 1; + + while (L < R) { + while (L < R && !isalnum(s[L])) { + L++; + } + while (L < R && !isalnum(s[R])) { + R--; + } + if (L < R && tolower(s[L]) != tolower(s[R])) { + return false; + } + L++; + R--; + } + return true; + } +}; diff --git a/Valid Palindrome - Leetcode 125/Valid Palindrome - Leetcode 125.java b/Valid Palindrome - Leetcode 125/Valid Palindrome - Leetcode 125.java new file mode 100644 index 0000000..6617bd2 --- /dev/null +++ b/Valid Palindrome - Leetcode 125/Valid Palindrome - Leetcode 125.java @@ -0,0 +1,20 @@ +public class Solution { + public boolean isPalindrome(String s) { + int L = 0, R = s.length() - 1; + + while (L < R) { + while (L < R && !Character.isLetterOrDigit(s.charAt(L))) { + L++; + } + while (L < R && !Character.isLetterOrDigit(s.charAt(R))) { + R--; + } + if (L < R && Character.toLowerCase(s.charAt(L)) != Character.toLowerCase(s.charAt(R))) { + return false; + } + L++; + R--; + } + return true; + } +} diff --git a/Valid Palindrome - Leetcode 125/Valid Palindrome - Leetcode 125.js b/Valid Palindrome - Leetcode 125/Valid Palindrome - Leetcode 125.js new file mode 100644 index 0000000..3cc0374 --- /dev/null +++ b/Valid Palindrome - Leetcode 125/Valid Palindrome - Leetcode 125.js @@ -0,0 +1,18 @@ +var isPalindrome = function(s) { + let L = 0, R = s.length - 1; + + while (L < R) { + while (L < R && !/[a-zA-Z0-9]/.test(s[L])) { + L++; + } + while (L < R && !/[a-zA-Z0-9]/.test(s[R])) { + R--; + } + if (L < R && s[L].toLowerCase() !== s[R].toLowerCase()) { + return false; + } + L++; + R--; + } + return true; +}; diff --git a/Valid Palindrome - Leetcode 125.py b/Valid Palindrome - Leetcode 125/Valid Palindrome - Leetcode 125.py similarity index 100% rename from Valid Palindrome - Leetcode 125.py rename to Valid Palindrome - Leetcode 125/Valid Palindrome - Leetcode 125.py diff --git a/Valid Parentheses - Leetcode 20/Valid Parentheses - Leetcode 20.cpp b/Valid Parentheses - Leetcode 20/Valid Parentheses - Leetcode 20.cpp new file mode 100644 index 0000000..5304a8d --- /dev/null +++ b/Valid Parentheses - Leetcode 20/Valid Parentheses - Leetcode 20.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool isValid(string s) { + unordered_map hashmap = {{')', '('}, {'}', '{'}, {']', '['}}; + stack stk; + + for (char c : s) { + if (hashmap.find(c) == hashmap.end()) { + stk.push(c); + } else { + if (stk.empty() || stk.top() != hashmap[c]) { + return false; + } + stk.pop(); + } + } + + return stk.empty(); + } +}; diff --git a/Valid Parentheses - Leetcode 20/Valid Parentheses - Leetcode 20.java b/Valid Parentheses - Leetcode 20/Valid Parentheses - Leetcode 20.java new file mode 100644 index 0000000..c2c1215 --- /dev/null +++ b/Valid Parentheses - Leetcode 20/Valid Parentheses - Leetcode 20.java @@ -0,0 +1,24 @@ +import java.util.Stack; + +public class Solution { + public boolean isValid(String s) { + java.util.Map hashmap = new java.util.HashMap<>(); + hashmap.put(')', '('); + hashmap.put('}', '{'); + hashmap.put(']', '['); + + Stack stk = new Stack<>(); + + for (char c : s.toCharArray()) { + if (!hashmap.containsKey(c)) { + stk.push(c); + } else { + if (stk.isEmpty() || stk.pop() != hashmap.get(c)) { + return false; + } + } + } + + return stk.isEmpty(); + } +} diff --git a/Valid Parentheses - Leetcode 20/Valid Parentheses - Leetcode 20.js b/Valid Parentheses - Leetcode 20/Valid Parentheses - Leetcode 20.js new file mode 100644 index 0000000..56a92ba --- /dev/null +++ b/Valid Parentheses - Leetcode 20/Valid Parentheses - Leetcode 20.js @@ -0,0 +1,16 @@ +var isValid = function(s) { + const hashmap = { ')': '(', '}': '{', ']': '[' }; + const stk = []; + + for (const c of s) { + if (!(c in hashmap)) { + stk.push(c); + } else { + if (stk.length === 0 || stk.pop() !== hashmap[c]) { + return false; + } + } + } + + return stk.length === 0; +}; diff --git a/Valid Parentheses - Leetcode 20.py b/Valid Parentheses - Leetcode 20/Valid Parentheses - Leetcode 20.py similarity index 100% rename from Valid Parentheses - Leetcode 20.py rename to Valid Parentheses - Leetcode 20/Valid Parentheses - Leetcode 20.py diff --git a/Valid Perfect Square - Leetcode 367/Valid Perfect Square - Leetcode 367.cpp b/Valid Perfect Square - Leetcode 367/Valid Perfect Square - Leetcode 367.cpp new file mode 100644 index 0000000..1f88da6 --- /dev/null +++ b/Valid Perfect Square - Leetcode 367/Valid Perfect Square - Leetcode 367.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool isPerfectSquare(int num) { + long l = 1; // Use long to prevent overflow + long r = num; + + while (l <= r) { + long m = (l + r) / 2; + long mSquared = m * m; + + if (num == mSquared) { + return true; + } else if (mSquared < num) { + l = m + 1; + } else { + r = m - 1; + } + } + + return false; + } +}; diff --git a/Valid Perfect Square - Leetcode 367/Valid Perfect Square - Leetcode 367.java b/Valid Perfect Square - Leetcode 367/Valid Perfect Square - Leetcode 367.java new file mode 100644 index 0000000..5f02b62 --- /dev/null +++ b/Valid Perfect Square - Leetcode 367/Valid Perfect Square - Leetcode 367.java @@ -0,0 +1,21 @@ +public class Solution { + public boolean isPerfectSquare(int num) { + int l = 1; + int r = num; + + while (l <= r) { + int m = (l + r) / 2; + long mSquared = (long) m * m; // Use long to prevent overflow + + if (num == mSquared) { + return true; + } else if (mSquared < num) { + l = m + 1; + } else { + r = m - 1; + } + } + + return false; + } +} diff --git a/Valid Perfect Square - Leetcode 367/Valid Perfect Square - Leetcode 367.js b/Valid Perfect Square - Leetcode 367/Valid Perfect Square - Leetcode 367.js new file mode 100644 index 0000000..20842da --- /dev/null +++ b/Valid Perfect Square - Leetcode 367/Valid Perfect Square - Leetcode 367.js @@ -0,0 +1,19 @@ +var isPerfectSquare = function(num) { + let l = 1; + let r = num; + + while (l <= r) { + let m = Math.floor((l + r) / 2); + let mSquared = m * m; + + if (num === mSquared) { + return true; + } else if (mSquared < num) { + l = m + 1; + } else { + r = m - 1; + } + } + + return false; +}; diff --git a/Valid Perfect Square - Leetcode 367.py b/Valid Perfect Square - Leetcode 367/Valid Perfect Square - Leetcode 367.py similarity index 100% rename from Valid Perfect Square - Leetcode 367.py rename to Valid Perfect Square - Leetcode 367/Valid Perfect Square - Leetcode 367.py diff --git a/Valid Sudoku - Leetcode 36/Valid Sudoku - Leetcode 36.cpp b/Valid Sudoku - Leetcode 36/Valid Sudoku - Leetcode 36.cpp new file mode 100644 index 0000000..1f6dc3d --- /dev/null +++ b/Valid Sudoku - Leetcode 36/Valid Sudoku - Leetcode 36.cpp @@ -0,0 +1,49 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool isValidSudoku(vector>& board) { + // Validate Rows + for (int i = 0; i < 9; i++) { + unordered_set set; + for (int j = 0; j < 9; j++) { + char item = board[i][j]; + if (item != '.' && !set.insert(item).second) { + return false; + } + } + } + + // Validate Columns + for (int i = 0; i < 9; i++) { + unordered_set set; + for (int j = 0; j < 9; j++) { + char item = board[j][i]; + if (item != '.' && !set.insert(item).second) { + return false; + } + } + } + + // Validate 3x3 Sub-grids + vector> starts = {{0, 0}, {0, 3}, {0, 6}, + {3, 0}, {3, 3}, {3, 6}, + {6, 0}, {6, 3}, {6, 6}}; + + for (auto& start : starts) { + unordered_set set; + for (int row = start[0]; row < start[0] + 3; row++) { + for (int col = start[1]; col < start[1] + 3; col++) { + char item = board[row][col]; + if (item != '.' && !set.insert(item).second) { + return false; + } + } + } + } + + return true; + } +}; diff --git a/Valid Sudoku - Leetcode 36/Valid Sudoku - Leetcode 36.java b/Valid Sudoku - Leetcode 36/Valid Sudoku - Leetcode 36.java new file mode 100644 index 0000000..56d46d2 --- /dev/null +++ b/Valid Sudoku - Leetcode 36/Valid Sudoku - Leetcode 36.java @@ -0,0 +1,47 @@ +import java.util.HashSet; +import java.util.Set; + +public class Solution { + public boolean isValidSudoku(char[][] board) { + // Validate Rows + for (int i = 0; i < 9; i++) { + Set set = new HashSet<>(); + for (int j = 0; j < 9; j++) { + char item = board[i][j]; + if (item != '.' && !set.add(item)) { + return false; + } + } + } + + // Validate Columns + for (int i = 0; i < 9; i++) { + Set set = new HashSet<>(); + for (int j = 0; j < 9; j++) { + char item = board[j][i]; + if (item != '.' && !set.add(item)) { + return false; + } + } + } + + // Validate 3x3 Sub-grids + int[][] starts = {{0, 0}, {0, 3}, {0, 6}, + {3, 0}, {3, 3}, {3, 6}, + {6, 0}, {6, 3}, {6, 6}}; + + for (int[] start : starts) { + Set set = new HashSet<>(); + for (int row = start[0]; row < start[0] + 3; row++) { + for (int col = start[1]; col < start[1] + 3; col++) { + char item = board[row][col]; + if (item != '.' && !set.add(item)) { + return false; + } + } + } + } + + return true; + } +} diff --git a/Valid Sudoku - Leetcode 36/Valid Sudoku - Leetcode 36.js b/Valid Sudoku - Leetcode 36/Valid Sudoku - Leetcode 36.js new file mode 100644 index 0000000..9a0f6b0 --- /dev/null +++ b/Valid Sudoku - Leetcode 36/Valid Sudoku - Leetcode 36.js @@ -0,0 +1,45 @@ +var isValidSudoku = function(board) { + // Validate Rows + for (let i = 0; i < 9; i++) { + let set = new Set(); + for (let j = 0; j < 9; j++) { + let item = board[i][j]; + if (item !== '.' && set.has(item)) { + return false; + } + set.add(item); + } + } + + // Validate Columns + for (let i = 0; i < 9; i++) { + let set = new Set(); + for (let j = 0; j < 9; j++) { + let item = board[j][i]; + if (item !== '.' && set.has(item)) { + return false; + } + set.add(item); + } + } + + // Validate 3x3 Sub-grids + let starts = [[0, 0], [0, 3], [0, 6], + [3, 0], [3, 3], [3, 6], + [6, 0], [6, 3], [6, 6]]; + + for (let [startRow, startCol] of starts) { + let set = new Set(); + for (let row = startRow; row < startRow + 3; row++) { + for (let col = startCol; col < startCol + 3; col++) { + let item = board[row][col]; + if (item !== '.' && set.has(item)) { + return false; + } + set.add(item); + } + } + } + + return true; +}; diff --git a/Valid Sudoku - Leetcode 36.py b/Valid Sudoku - Leetcode 36/Valid Sudoku - Leetcode 36.py similarity index 100% rename from Valid Sudoku - Leetcode 36.py rename to Valid Sudoku - Leetcode 36/Valid Sudoku - Leetcode 36.py diff --git a/Validate Binary Search Tree - Leetcode 98.py b/Validate Binary Search Tree - Leetcode 98.py deleted file mode 100644 index f91cc2a..0000000 --- a/Validate Binary Search Tree - Leetcode 98.py +++ /dev/null @@ -1,15 +0,0 @@ -class Solution: - def isValidBST(self, root: Optional[TreeNode]) -> bool: - def is_valid(node, minn, maxx): - if not node: - return True - - if node.val <= minn or node.val >= maxx: - return False - - return is_valid(node.left, minn, node.val) and is_valid(node.right, node.val, maxx) - - return is_valid(root, float("-inf"), float("inf")) - -# Time Complexity: O(n) -# Space Complexity: O(h) { here "h" is height of tree } diff --git a/Validate Binary Search Tree - Leetcode 98/Validate Binary Search Tree - Leetcode 98.cpp b/Validate Binary Search Tree - Leetcode 98/Validate Binary Search Tree - Leetcode 98.cpp new file mode 100644 index 0000000..2d62a8f --- /dev/null +++ b/Validate Binary Search Tree - Leetcode 98/Validate Binary Search Tree - Leetcode 98.cpp @@ -0,0 +1,18 @@ +#include +using namespace std; + +class Solution { +public: + bool isValidBST(TreeNode* root) { + return isValid(root, LONG_MIN, LONG_MAX); + } + +private: + bool isValid(TreeNode* node, long min, long max) { + if (!node) return true; + + if (node->val <= min || node->val >= max) return false; + + return isValid(node->left, min, node->val) && isValid(node->right, node->val, max); + } +}; diff --git a/Validate Binary Search Tree - Leetcode 98/Validate Binary Search Tree - Leetcode 98.java b/Validate Binary Search Tree - Leetcode 98/Validate Binary Search Tree - Leetcode 98.java new file mode 100644 index 0000000..8a777fa --- /dev/null +++ b/Validate Binary Search Tree - Leetcode 98/Validate Binary Search Tree - Leetcode 98.java @@ -0,0 +1,17 @@ +public class Solution { + public boolean isValidBST(TreeNode root) { + return isValid(root, Long.MIN_VALUE, Long.MAX_VALUE); + } + + private boolean isValid(TreeNode node, long min, long max) { + if (node == null) { + return true; + } + + if (node.val <= min || node.val >= max) { + return false; + } + + return isValid(node.left, min, node.val) && isValid(node.right, node.val, max); + } +} diff --git a/Validate Binary Search Tree - Leetcode 98/Validate Binary Search Tree - Leetcode 98.js b/Validate Binary Search Tree - Leetcode 98/Validate Binary Search Tree - Leetcode 98.js new file mode 100644 index 0000000..9aed4d2 --- /dev/null +++ b/Validate Binary Search Tree - Leetcode 98/Validate Binary Search Tree - Leetcode 98.js @@ -0,0 +1,11 @@ +var isValidBST = function(root) { + function isValid(node, min, max) { + if (!node) return true; + + if (node.val <= min || node.val >= max) return false; + + return isValid(node.left, min, node.val) && isValid(node.right, node.val, max); + } + + return isValid(root, -Infinity, Infinity); +}; diff --git a/Validate Binary Search Tree - Leetcode 98/Validate Binary Search Tree - Leetcode 98.py b/Validate Binary Search Tree - Leetcode 98/Validate Binary Search Tree - Leetcode 98.py new file mode 100644 index 0000000..d8a9a1f --- /dev/null +++ b/Validate Binary Search Tree - Leetcode 98/Validate Binary Search Tree - Leetcode 98.py @@ -0,0 +1,37 @@ +class Solution: + def isValidBST(self, root: Optional[TreeNode]) -> bool: + def is_valid(node, minn, maxx): + if not node: + return True + + if node.val <= minn or node.val >= maxx: + return False + + return is_valid(node.left, minn, node.val) and is_valid(node.right, node.val, maxx) + + return is_valid(root, float("-inf"), float("inf")) + +# Time Complexity: O(n) +# Space Complexity: O(h) { here "h" is height of tree } + + +# Bootcamp solution +class Solution: + def isValidBST(self, root: Optional[TreeNode]) -> bool: + stk = [(root, float('-inf'), float('inf'))] + + while stk: + node, minn, maxx = stk.pop() + + if node.val <= minn or node.val >= maxx: + return False + else: + if node.left: + stk.append((node.left, minn, node.val)) + + if node.right: + stk.append((node.right, node.val, maxx)) + + return True +# Time Complexity: O(n) +# Space Complexity: O(h) { here "h" is height of tree } diff --git a/Word Search - Leetcode 79/Word Search - Leetcode 79.cpp b/Word Search - Leetcode 79/Word Search - Leetcode 79.cpp new file mode 100644 index 0000000..5c65885 --- /dev/null +++ b/Word Search - Leetcode 79/Word Search - Leetcode 79.cpp @@ -0,0 +1,47 @@ +#include +#include +using namespace std; + +class Solution { +public: + bool exist(vector>& board, string word) { + int m = board.size(); + int n = board[0].size(); + int W = word.size(); + + if (m == 1 && n == 1) { + return board[0][0] == word[0]; + } + + vector> visited(m, vector(n, false)); + + for (int i = 0; i < m; ++i) { + for (int j = 0; j < n; ++j) { + if (backtrack(board, word, i, j, 0, visited)) { + return true; + } + } + } + + return false; + } + +private: + bool backtrack(vector>& board, string& word, int i, int j, int index, vector>& visited) { + if (index == word.size()) return true; + + if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size() || visited[i][j] || board[i][j] != word[index]) { + return false; + } + + visited[i][j] = true; + + bool found = backtrack(board, word, i + 1, j, index + 1, visited) || + backtrack(board, word, i - 1, j, index + 1, visited) || + backtrack(board, word, i, j + 1, index + 1, visited) || + backtrack(board, word, i, j - 1, index + 1, visited); + + visited[i][j] = false; + return found; + } +}; diff --git a/Word Search - Leetcode 79/Word Search - Leetcode 79.java b/Word Search - Leetcode 79/Word Search - Leetcode 79.java new file mode 100644 index 0000000..6cfb17d --- /dev/null +++ b/Word Search - Leetcode 79/Word Search - Leetcode 79.java @@ -0,0 +1,41 @@ +public class Solution { + public boolean exist(char[][] board, String word) { + int m = board.length; + int n = board[0].length; + int W = word.length(); + + if (m == 1 && n == 1) { + return board[0][0] == word.charAt(0); + } + + boolean[][] visited = new boolean[m][n]; + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (backtrack(board, word, i, j, 0, visited)) { + return true; + } + } + } + + return false; + } + + private boolean backtrack(char[][] board, String word, int i, int j, int index, boolean[][] visited) { + if (index == word.length()) return true; + + if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || visited[i][j] || board[i][j] != word.charAt(index)) { + return false; + } + + visited[i][j] = true; + + boolean found = backtrack(board, word, i + 1, j, index + 1, visited) || + backtrack(board, word, i - 1, j, index + 1, visited) || + backtrack(board, word, i, j + 1, index + 1, visited) || + backtrack(board, word, i, j - 1, index + 1, visited); + + visited[i][j] = false; + return found; + } +} diff --git a/Word Search - Leetcode 79/Word Search - Leetcode 79.js b/Word Search - Leetcode 79/Word Search - Leetcode 79.js new file mode 100644 index 0000000..0cded4d --- /dev/null +++ b/Word Search - Leetcode 79/Word Search - Leetcode 79.js @@ -0,0 +1,35 @@ +var exist = function(board, word) { + const m = board.length; + const n = board[0].length; + const W = word.length; + + if (m === 1 && n === 1) { + return board[0][0] === word; + } + + const backtrack = function(i, j, index) { + if (index === W) return true; + if (i < 0 || j < 0 || i >= m || j >= n || board[i][j] !== word[index]) return false; + + const char = board[i][j]; + board[i][j] = "#"; + + const found = backtrack(i + 1, j, index + 1) || + backtrack(i - 1, j, index + 1) || + backtrack(i, j + 1, index + 1) || + backtrack(i, j - 1, index + 1); + + board[i][j] = char; + return found; + }; + + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (backtrack(i, j, 0)) { + return true; + } + } + } + + return false; +}; diff --git a/Word Search - Leetcode 79.py b/Word Search - Leetcode 79/Word Search - Leetcode 79.py similarity index 100% rename from Word Search - Leetcode 79.py rename to Word Search - Leetcode 79/Word Search - Leetcode 79.py diff --git a/Zigzag Conversion - Leetcode 6/Zigzag Conversion - Leetcode 6.cpp b/Zigzag Conversion - Leetcode 6/Zigzag Conversion - Leetcode 6.cpp new file mode 100644 index 0000000..fbc3619 --- /dev/null +++ b/Zigzag Conversion - Leetcode 6/Zigzag Conversion - Leetcode 6.cpp @@ -0,0 +1,25 @@ +#include +#include + +class Solution { +public: + std::string convert(const std::string& s, int numRows) { + if (numRows == 1) return s; + + std::vector rows(std::min(numRows, int(s.length()))); + int i = 0; + bool goingDown = false; + + for (char c : s) { + rows[i] += c; + if (i == 0 || i == numRows - 1) goingDown = !goingDown; + i += goingDown ? 1 : -1; + } + + std::string result; + for (const std::string& row : rows) { + result += row; + } + return result; + } +}; diff --git a/Zigzag Conversion - Leetcode 6/Zigzag Conversion - Leetcode 6.java b/Zigzag Conversion - Leetcode 6/Zigzag Conversion - Leetcode 6.java new file mode 100644 index 0000000..d4ccc57 --- /dev/null +++ b/Zigzag Conversion - Leetcode 6/Zigzag Conversion - Leetcode 6.java @@ -0,0 +1,25 @@ +public class Solution { + public String convert(String s, int numRows) { + if (numRows == 1) return s; + + List rows = new ArrayList<>(); + for (int i = 0; i < Math.min(numRows, s.length()); i++) { + rows.add(new StringBuilder()); + } + + int i = 0; + boolean goingDown = false; + + for (char c : s.toCharArray()) { + rows.get(i).append(c); + if (i == 0 || i == numRows - 1) goingDown = !goingDown; + i += goingDown ? 1 : -1; + } + + StringBuilder result = new StringBuilder(); + for (StringBuilder row : rows) { + result.append(row); + } + return result.toString(); + } +} diff --git a/Zigzag Conversion - Leetcode 6/Zigzag Conversion - Leetcode 6.js b/Zigzag Conversion - Leetcode 6/Zigzag Conversion - Leetcode 6.js new file mode 100644 index 0000000..2ac096a --- /dev/null +++ b/Zigzag Conversion - Leetcode 6/Zigzag Conversion - Leetcode 6.js @@ -0,0 +1,15 @@ +var convert = function(s, numRows) { + if (numRows === 1) return s; + + let rows = Array.from({ length: Math.min(numRows, s.length) }, () => []); + let i = 0; + let goingDown = false; + + for (let char of s) { + rows[i].push(char); + if (i === 0 || i === numRows - 1) goingDown = !goingDown; + i += goingDown ? 1 : -1; + } + + return rows.flat().join(''); +}; diff --git a/Zigzag Conversion - Leetcode 6/Zigzag Conversion - Leetcode 6.py b/Zigzag Conversion - Leetcode 6/Zigzag Conversion - Leetcode 6.py new file mode 100644 index 0000000..acb20dd --- /dev/null +++ b/Zigzag Conversion - Leetcode 6/Zigzag Conversion - Leetcode 6.py @@ -0,0 +1,22 @@ +class Solution: + def convert(self, s: str, numRows: int) -> str: + if numRows == 1: + return s + + i, d = 0, 1 + rows = [[] for _ in range(numRows)] + + for char in s: + rows[i].append(char) + if i == 0: + d = 1 + elif i == numRows - 1: + d = -1 + i += d + + for i in range(numRows): + rows[i] = ''.join(rows[i]) + + return ''.join(rows) + # Time: O(n * numRows) + # Space: O(n) \ No newline at end of file