From 36b5f5c9747854d1cdf557a03f0d5dac2e7c495d Mon Sep 17 00:00:00 2001 From: Sri Hari Date: Thu, 3 Oct 2024 21:40:51 +0530 Subject: [PATCH 1/2] Neetcode-150/added-5-articles --- articles/anagram-groups.md | 205 +++++++ articles/is-anagram.md | 318 +++++++++++ articles/longest-consecutive-sequence.md | 482 ++++++++++++++++ articles/products-of-array-discluding-self.md | 513 ++++++++++++++++++ articles/top-k-elements-in-list.md | 416 ++++++++++++++ 5 files changed, 1934 insertions(+) create mode 100644 articles/anagram-groups.md create mode 100644 articles/is-anagram.md create mode 100644 articles/longest-consecutive-sequence.md create mode 100644 articles/products-of-array-discluding-self.md create mode 100644 articles/top-k-elements-in-list.md diff --git a/articles/anagram-groups.md b/articles/anagram-groups.md new file mode 100644 index 000000000..1cce9924e --- /dev/null +++ b/articles/anagram-groups.md @@ -0,0 +1,205 @@ +## 1. Sorting + +::tabs-start + +```python +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + res = defaultdict(list) + for s in strs: + sortedS = ''.join(sorted(s)) + res[sortedS].append(s) + return res.values() +``` + +```java +public class Solution { + public List> groupAnagrams(String[] strs) { + Map> res = new HashMap<>(); + for (String s : strs) { + char[] charArray = s.toCharArray(); + Arrays.sort(charArray); + String sortedS = new String(charArray); + res.putIfAbsent(sortedS, new ArrayList<>()); + res.get(sortedS).add(s); + } + return new ArrayList<>(res.values()); + } +} +``` + +```cpp +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> res; + for (const auto& s : strs) { + string sortedS = s; + sort(sortedS.begin(), sortedS.end()); + res[sortedS].push_back(s); + } + vector> result; + for (auto& pair : res) { + result.push_back(pair.second); + } + return result; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string[]} strs + * @return {string[][]} + */ + groupAnagrams(strs) { + const res = {}; + for (let s of strs) { + const sortedS = s.split('').sort().join(''); + if (!res[sortedS]) { + res[sortedS] = []; + } + res[sortedS].push(s); + } + return Object.values(res); + } +} +``` + +```csharp +public class Solution { + public List> GroupAnagrams(string[] strs) { + var res = new Dictionary>(); + foreach (var s in strs) { + char[] charArray = s.ToCharArray(); + Array.Sort(charArray); + string sortedS = new string(charArray); + if (!res.ContainsKey(sortedS)) { + res[sortedS] = new List(); + } + res[sortedS].Add(s); + } + return res.Values.ToList>(); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(m * n \log n)$ +* Space complexity: $O(m * n)$ + +--- + +## 2. Hash Table + +::tabs-start + +```python +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + res = defaultdict(list) + for s in strs: + count = [0] * 26 + for c in s: + count[ord(c) - ord('a')] += 1 + res[tuple(count)].append(s) + return res.values() +``` + +```java +public class Solution { + public List> groupAnagrams(String[] strs) { + Map> res = new HashMap<>(); + for (String s : strs) { + int[] count = new int[26]; + for (char c : s.toCharArray()) { + count[c - 'a']++; + } + String key = Arrays.toString(count); + res.putIfAbsent(key, new ArrayList<>()); + res.get(key).add(s); + } + return new ArrayList<>(res.values()); + } +} +``` + +```cpp +class Solution { +public: + vector> groupAnagrams(vector& strs) { + unordered_map> res; + for (const auto& s : strs) { + vector count(26, 0); + for (char c : s) { + count[c - 'a']++; + } + string key = to_string(count[0]); + for (int i = 1; i < 26; ++i) { + key += ',' + to_string(count[i]); + } + res[key].push_back(s); + } + vector> result; + for (const auto& pair : res) { + result.push_back(pair.second); + } + return result; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string[]} strs + * @return {string[][]} + */ + groupAnagrams(strs) { + const res = {}; + for (let s of strs) { + const count = new Array(26).fill(0); + for (let c of s) { + count[c.charCodeAt(0) - 'a'.charCodeAt(0)] += 1; + } + const key = count.join(','); + if (!res[key]) { + res[key] = []; + } + res[key].push(s); + } + return Object.values(res); + } +} +``` + +```csharp +public class Solution { + public List> GroupAnagrams(string[] strs) { + var res = new Dictionary>(); + foreach (var s in strs) { + int[] count = new int[26]; + foreach (char c in s) { + count[c - 'a']++; + } + string key = string.Join(",", count); + if (!res.ContainsKey(key)) { + res[key] = new List(); + } + res[key].Add(s); + } + return res.Values.ToList>(); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(m * n)$ +* Space complexity: $O(m)$ \ No newline at end of file diff --git a/articles/is-anagram.md b/articles/is-anagram.md new file mode 100644 index 000000000..3e879f614 --- /dev/null +++ b/articles/is-anagram.md @@ -0,0 +1,318 @@ +## 1. Sorting + +::tabs-start + +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + + return sorted(s) == sorted(t) +``` + +```java +public class Solution { + public boolean isAnagram(String s, String t) { + if (s.length() != t.length()) { + return false; + } + + char[] sSort = s.toCharArray(); + char[] tSort = t.toCharArray(); + Arrays.sort(sSort); + Arrays.sort(tSort); + return Arrays.equals(sSort, tSort); + } +} +``` + +```cpp +class Solution { +public: + bool isAnagram(string s, string t) { + if (s.length() != t.length()) { + return false; + } + + sort(s.begin(), s.end()); + sort(t.begin(), t.end()); + return s == t; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} s + * @param {string} t + * @return {boolean} + */ + isAnagram(s, t) { + if (s.length !== t.length) { + return false; + } + + let sSort = s.split("").sort().join(); + let tSort = t.split("").sort().join(); + return sSort == tSort + } +} +``` + +```csharp +public class Solution { + public bool IsAnagram(string s, string t) { + if (s.Length != t.Length) { + return false; + } + + char[] sSort = s.ToCharArray(); + char[] tSort = t.ToCharArray(); + Array.Sort(sSort); + Array.Sort(tSort); + return sSort.SequenceEqual(tSort); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n \log n)$ +* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. + +--- + +## 2. Hash Table + +::tabs-start + +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + + countS, countT = {}, {} + + for i in range(len(s)): + countS[s[i]] = 1 + countS.get(s[i], 0) + countT[t[i]] = 1 + countT.get(t[i], 0) + return countS == countT +``` + +```java +public class Solution { + public boolean isAnagram(String s, String t) { + if (s.length() != t.length()) { + return false; + } + + HashMap countS = new HashMap<>(); + HashMap countT = new HashMap<>(); + for (int i = 0; i < s.length(); i++) { + countS.put(s.charAt(i), countS.getOrDefault(s.charAt(i), 0) + 1); + countT.put(t.charAt(i), countT.getOrDefault(t.charAt(i), 0) + 1); + } + return countS.equals(countT); + } +} +``` + +```cpp +class Solution { +public: + bool isAnagram(string s, string t) { + if (s.length() != t.length()) { + return false; + } + + unordered_map countS; + unordered_map countT; + for (int i = 0; i < s.length(); i++) { + countS[s[i]]++; + countT[t[i]]++; + } + return countS == countT; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} s + * @param {string} t + * @return {boolean} + */ + isAnagram(s, t) { + if (s.length !== t.length) { + return false; + } + + const countS = {}; + const countT = {}; + for (let i = 0; i < s.length; i++) { + countS[s[i]] = (countS[s[i]] || 0) + 1; + countT[t[i]] = (countT[t[i]] || 0) + 1; + } + + for (const key in countS) { + if (countS[key] !== countT[key]) { + return false; + } + } + return true; + } +} +``` + +```csharp +public class Solution { + public bool IsAnagram(string s, string t) { + if (s.Length != t.Length) { + return false; + } + + Dictionary countS = new Dictionary(); + Dictionary countT = new Dictionary(); + for (int i = 0; i < s.Length; i++) { + countS[s[i]] = countS.GetValueOrDefault(s[i], 0) + 1; + countT[t[i]] = countT.GetValueOrDefault(t[i], 0) + 1; + } + return countS.Count == countT.Count && !countS.Except(countT).Any(); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ + +--- + +## 3. Hash Table (Optimal) + +::tabs-start + +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + + count = [0] * 26 + for i in range(len(s)): + count[ord(s[i]) - ord('a')] += 1 + count[ord(t[i]) - ord('a')] -= 1 + + for val in count: + if val != 0: + return False + return True +``` + +```java +public class Solution { + public boolean isAnagram(String s, String t) { + if (s.length() != t.length()) { + return false; + } + + int[] count = new int[26]; + for (int i = 0; i < s.length(); i++) { + count[s.charAt(i) - 'a']++; + count[t.charAt(i) - 'a']--; + } + + for (int val : count) { + if (val != 0) { + return false; + } + } + return true; + } +} +``` + +```cpp +class Solution { +public: + bool isAnagram(string s, string t) { + if (s.length() != t.length()) { + return false; + } + + vector count(26, 0); + for (int i = 0; i < s.length(); i++) { + count[s[i] - 'a']++; + count[t[i] - 'a']--; + } + + for (int val : count) { + if (val != 0) { + return false; + } + } + return true; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} s + * @param {string} t + * @return {boolean} + */ + isAnagram(s, t) { + if (s.length !== t.length) { + return false; + } + + const count = new Array(26).fill(0); + for (let i = 0; i < s.length; i++) { + count[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; + count[t.charCodeAt(i) - 'a'.charCodeAt(0)]--; + } + return count.every(val => val === 0); + } +} +``` + +```csharp +public class Solution { + public bool IsAnagram(string s, string t) { + if (s.Length != t.Length) { + return false; + } + + int[] count = new int[26]; + for (int i = 0; i < s.Length; i++) { + count[s[i] - 'a']++; + count[t[i] - 'a']--; + } + + foreach (int val in count) { + if (val != 0) { + return false; + } + } + return true; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ \ No newline at end of file diff --git a/articles/longest-consecutive-sequence.md b/articles/longest-consecutive-sequence.md new file mode 100644 index 000000000..0c62e3d72 --- /dev/null +++ b/articles/longest-consecutive-sequence.md @@ -0,0 +1,482 @@ +## 1. Brute Force + +::tabs-start + +```python +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + res = 0 + store = set(nums) + + for num in nums: + streak, curr = 0, num + while curr in store: + streak += 1 + curr += 1 + res = max(res, streak) + return res +``` + +```java +public class Solution { + public int longestConsecutive(int[] nums) { + int res = 0; + Set store = new HashSet<>(); + for (int num : nums) { + store.add(num); + } + + for (int num : nums) { + int streak = 0, curr = num; + while (store.contains(curr)) { + streak++; + curr++; + } + res = Math.max(res, streak); + } + return res; + } +} +``` + +```cpp +class Solution { +public: + int longestConsecutive(vector& nums) { + int res = 0; + unordered_set store(nums.begin(), nums.end()); + + for (int num : nums) { + int streak = 0, curr = num; + while (store.find(curr) != store.end()) { + streak++; + curr++; + } + res = max(res, streak); + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number} + */ + longestConsecutive(nums) { + let res = 0; + const store = new Set(nums); + + for (let num of nums) { + let streak = 0, curr = num; + while (store.has(curr)) { + streak++; + curr++; + } + res = Math.max(res, streak); + } + return res; + } +} +``` + +```csharp +public class Solution { + public int LongestConsecutive(int[] nums) { + int res = 0; + HashSet store = new HashSet(nums); + + foreach (int num in nums) { + int streak = 0, curr = num; + while (store.Contains(curr)) { + streak++; + curr++; + } + res = Math.Max(res, streak); + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 2)$ +* Space complexity: $O(n)$ + +--- + +## 2. Sorting + +::tabs-start + +```python +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + if not nums: + return 0 + res = 0 + nums.sort() + + curr, streak = nums[0], 0 + i = 0 + while i < len(nums): + if curr != nums[i]: + curr = nums[i] + streak = 0 + while i < len(nums) and nums[i] == curr: + i += 1 + streak += 1 + curr += 1 + res = max(res, streak) + return res +``` + +```java +public class Solution { + public int longestConsecutive(int[] nums) { + if (nums.length == 0) { + return 0; + } + Arrays.sort(nums); + int res = 0, curr = nums[0], streak = 0, i = 0; + + while (i < nums.length) { + if (curr != nums[i]) { + curr = nums[i]; + streak = 0; + } + while (i < nums.length && nums[i] == curr) { + i++; + } + streak++; + curr++; + res = Math.max(res, streak); + } + return res; + } +} +``` + +```cpp +class Solution { +public: + int longestConsecutive(vector& nums) { + if (nums.empty()) return 0; + sort(nums.begin(), nums.end()); + + int res = 0, curr = nums[0], streak = 0, i = 0; + + while (i < nums.size()) { + if (curr != nums[i]) { + curr = nums[i]; + streak = 0; + } + while (i < nums.size() && nums[i] == curr) { + i++; + } + streak++; + curr++; + res = max(res, streak); + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number} + */ + longestConsecutive(nums) { + if (nums.length === 0) { + return 0; + } + nums.sort((a, b) => a - b); + + let res = 0, curr = nums[0], streak = 0, i = 0; + + while (i < nums.length) { + if (curr !== nums[i]) { + curr = nums[i]; + streak = 0; + } + while (i < nums.length && nums[i] === curr) { + i++; + } + streak++; + curr++; + res = Math.max(res, streak); + } + return res; + } +} +``` + +```csharp +public class Solution { + public int LongestConsecutive(int[] nums) { + if (nums.Length == 0) { + return 0; + } + Array.Sort(nums); + + int res = 0, curr = nums[0], streak = 0, i = 0; + + while (i < nums.Length) { + if (curr != nums[i]) { + curr = nums[i]; + streak = 0; + } + while (i < nums.Length && nums[i] == curr) { + i++; + } + streak++; + curr++; + res = Math.Max(res, streak); + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n \log n)$ +* Space complexity: $O(1)$ + +--- + +## 3. Hash Set + +::tabs-start + +```python +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + numSet = set(nums) + longest = 0 + + for num in numSet: + if (num - 1) not in numSet: + length = 1 + while (num + length) in numSet: + length += 1 + longest = max(length, longest) + return longest +``` + +```java +public class Solution { + public int longestConsecutive(int[] nums) { + Set numSet = new HashSet<>(); + for (int num : nums) { + numSet.add(num); + } + int longest = 0; + + for (int num : numSet) { + if (!numSet.contains(num - 1)) { + int length = 1; + while (numSet.contains(num + length)) { + length++; + } + longest = Math.max(longest, length); + } + } + return longest; + } +} +``` + +```cpp +class Solution { +public: + int longestConsecutive(vector& nums) { + unordered_set numSet(nums.begin(), nums.end()); + int longest = 0; + + for (int num : numSet) { + if (numSet.find(num - 1) == numSet.end()) { + int length = 1; + while (numSet.find(num + length) != numSet.end()) { + length++; + } + longest = max(longest, length); + } + } + return longest; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number} + */ + longestConsecutive(nums) { + const numSet = new Set(nums); + let longest = 0; + + for (let num of numSet) { + if (!numSet.has(num - 1)) { + let length = 1; + while (numSet.has(num + length)) { + length++; + } + longest = Math.max(longest, length); + } + } + return longest; + } +} +``` + +```csharp +public class Solution { + public int LongestConsecutive(int[] nums) { + HashSet numSet = new HashSet(nums); + int longest = 0; + + foreach (int num in numSet) { + if (!numSet.Contains(num - 1)) { + int length = 1; + while (numSet.Contains(num + length)) { + length++; + } + longest = Math.Max(longest, length); + } + } + return longest; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ + +--- + +## 4. Hash Map + +::tabs-start + +```python +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + mp = defaultdict(int) + res = 0 + + for num in nums: + if not mp[num]: + mp[num] = mp[num - 1] + mp[num + 1] + 1 + mp[num - mp[num - 1]] = mp[num] + mp[num + mp[num + 1]] = mp[num] + res = max(res, mp[num]) + return res +``` + +```java +public class Solution { + public int longestConsecutive(int[] nums) { + Map mp = new HashMap<>(); + int res = 0; + + for (int num : nums) { + if (!mp.containsKey(num)) { + mp.put(num, mp.getOrDefault(num - 1, 0) + mp.getOrDefault(num + 1, 0) + 1); + mp.put(num - mp.getOrDefault(num - 1, 0), mp.get(num)); + mp.put(num + mp.getOrDefault(num + 1, 0), mp.get(num)); + res = Math.max(res, mp.get(num)); + } + } + return res; + } +} +``` + +```cpp +class Solution { +public: + int longestConsecutive(vector& nums) { + unordered_map mp; + int res = 0; + + for (int num : nums) { + if (!mp[num]) { + mp[num] = mp[num - 1] + mp[num + 1] + 1; + mp[num - mp[num - 1]] = mp[num]; + mp[num + mp[num + 1]] = mp[num]; + res = max(res, mp[num]); + } + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number} + */ + longestConsecutive(nums) { + const mp = new Map(); + let res = 0; + + for (let num of nums) { + if (!mp.has(num)) { + mp.set(num, (mp.get(num - 1) || 0) + (mp.get(num + 1) || 0) + 1); + mp.set(num - (mp.get(num - 1) || 0), mp.get(num)); + mp.set(num + (mp.get(num + 1) || 0), mp.get(num)); + res = Math.max(res, mp.get(num)); + } + } + return res; + } +} +``` + +```csharp +public class Solution { + public int LongestConsecutive(int[] nums) { + Dictionary mp = new Dictionary(); + int res = 0; + + foreach (int num in nums) { + if (!mp.ContainsKey(num)) { + mp[num] = (mp.ContainsKey(num - 1) ? mp[num - 1] : 0) + + (mp.ContainsKey(num + 1) ? mp[num + 1] : 0) + 1; + + mp[num - (mp.ContainsKey(num - 1) ? mp[num - 1] : 0)] = mp[num]; + mp[num + (mp.ContainsKey(num + 1) ? mp[num + 1] : 0)] = mp[num]; + + res = Math.Max(res, mp[num]); + } + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ \ No newline at end of file diff --git a/articles/products-of-array-discluding-self.md b/articles/products-of-array-discluding-self.md new file mode 100644 index 000000000..c9719f7e2 --- /dev/null +++ b/articles/products-of-array-discluding-self.md @@ -0,0 +1,513 @@ +## 1. Brute Force + +::tabs-start + +```python +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + res = [0] * n + + for i in range(n): + prod = 1 + for j in range(n): + if i == j: + continue + prod *= nums[j] + + res[i] = prod + return res +``` + +```java +public class Solution { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + int[] res = new int[n]; + + for (int i = 0; i < n; i++) { + int prod = 1; + for (int j = 0; j < n; j++) { + if (i != j) { + prod *= nums[j]; + } + } + res[i] = prod; + } + return res; + } +} +``` + +```cpp +class Solution { +public: + vector productExceptSelf(vector& nums) { + int n = nums.size(); + vector res(n); + + for (int i = 0; i < n; i++) { + int prod = 1; + for (int j = 0; j < n; j++) { + if (i != j) { + prod *= nums[j]; + } + } + res[i] = prod; + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number[]} + */ + productExceptSelf(nums) { + const n = nums.length; + const res = new Array(n); + + for (let i = 0; i < n; i++) { + let prod = 1; + for (let j = 0; j < n; j++) { + if (i !== j) { + prod *= nums[j]; + } + } + res[i] = prod; + } + return res; + } +} +``` + +```csharp +public class Solution { + public int[] ProductExceptSelf(int[] nums) { + int n = nums.Length; + int[] res = new int[n]; + + for (int i = 0; i < n; i++) { + int prod = 1; + for (int j = 0; j < n; j++) { + if (i != j) { + prod *= nums[j]; + } + } + res[i] = prod; + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 2)$ +* Space complexity: $O(1)$ + +--- + +## 2. Division + +::tabs-start + +```python +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + prod, zero_cnt = 1, 0 + for num in nums: + if num: + prod *= num + else: + zero_cnt += 1 + if zero_cnt > 1: return [0] * len(nums) + + res = [0] * len(nums) + for i, c in enumerate(nums): + if zero_cnt: res[i] = 0 if c else prod + else: res[i] = prod // c + return res +``` + +```java +public class Solution { + public int[] productExceptSelf(int[] nums) { + int prod = 1, zeroCount = 0; + for (int num : nums) { + if (num != 0) { + prod *= num; + } else { + zeroCount++; + } + } + + if (zeroCount > 1) { + return new int[nums.length]; + } + + int[] res = new int[nums.length]; + for (int i = 0; i < nums.length; i++) { + if (zeroCount > 0) { + res[i] = (nums[i] == 0) ? prod : 0; + } else { + res[i] = prod / nums[i]; + } + } + return res; + } +} +``` + +```cpp +class Solution { +public: + vector productExceptSelf(vector& nums) { + int prod = 1, zeroCount = 0; + for (int num : nums) { + if (num != 0) { + prod *= num; + } else { + zeroCount++; + } + } + + if (zeroCount > 1) { + return vector(nums.size(), 0); + } + + vector res(nums.size()); + for (size_t i = 0; i < nums.size(); i++) { + if (zeroCount > 0) { + res[i] = (nums[i] == 0) ? prod : 0; + } else { + res[i] = prod / nums[i]; + } + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number[]} + */ + productExceptSelf(nums) { + let prod = 1; + let zeroCount = 0; + for (let num of nums) { + if (num !== 0) { + prod *= num; + } else { + zeroCount++; + } + } + + if (zeroCount > 1) { + return Array(nums.length).fill(0); + } + + const res = new Array(nums.length); + for (let i = 0; i < nums.length; i++) { + if (zeroCount > 0) { + res[i] = (nums[i] === 0) ? prod : 0; + } else { + res[i] = prod / nums[i]; + } + } + return res; + } +} +``` + +```csharp +public class Solution { + public int[] ProductExceptSelf(int[] nums) { + int prod = 1, zeroCount = 0; + foreach (int num in nums) { + if (num != 0) { + prod *= num; + } else { + zeroCount++; + } + } + + if (zeroCount > 1) { + return new int[nums.Length]; + } + + int[] res = new int[nums.Length]; + for (int i = 0; i < nums.Length; i++) { + if (zeroCount > 0) { + res[i] = (nums[i] == 0) ? prod : 0; + } else { + res[i] = prod / nums[i]; + } + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ + +--- + +## 3. Prefix & Suffix + +::tabs-start + +```python +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + res = [0] * n + pref = [0] * n + suff = [0] * n + + pref[0] = suff[n - 1] = 1 + for i in range(1, n): + pref[i] = nums[i - 1] * pref[i - 1] + for i in range(n - 2, -1, -1): + suff[i] = nums[i + 1] * suff[i + 1] + for i in range(n): + res[i] = pref[i] * suff[i] + return res +``` + +```java +public class Solution { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + int[] res = new int[n]; + int[] pref = new int[n]; + int[] suff = new int[n]; + + pref[0] = 1; + suff[n - 1] = 1; + for (int i = 1; i < n; i++) { + pref[i] = nums[i - 1] * pref[i - 1]; + } + for (int i = n - 2; i >= 0; i--) { + suff[i] = nums[i + 1] * suff[i + 1]; + } + for (int i = 0; i < n; i++) { + res[i] = pref[i] * suff[i]; + } + return res; + } +} +``` + +```cpp +class Solution { +public: + vector productExceptSelf(vector& nums) { + int n = nums.size(); + vector res(n); + vector pref(n); + vector suff(n); + + pref[0] = 1; + suff[n - 1] = 1; + for (int i = 1; i < n; i++) { + pref[i] = nums[i - 1] * pref[i - 1]; + } + for (int i = n - 2; i >= 0; i--) { + suff[i] = nums[i + 1] * suff[i + 1]; + } + for (int i = 0; i < n; i++) { + res[i] = pref[i] * suff[i]; + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number[]} + */ + productExceptSelf(nums) { + const n = nums.length; + const res = new Array(n); + const pref = new Array(n); + const suff = new Array(n); + + pref[0] = 1; + suff[n - 1] = 1; + for (let i = 1; i < n; i++) { + pref[i] = nums[i - 1] * pref[i - 1]; + } + for (let i = n - 2; i >= 0; i--) { + suff[i] = nums[i + 1] * suff[i + 1]; + } + for (let i = 0; i < n; i++) { + res[i] = pref[i] * suff[i]; + } + return res; + } +} +``` + +```csharp +public class Solution { + public int[] ProductExceptSelf(int[] nums) { + int n = nums.Length; + int[] res = new int[n]; + int[] pref = new int[n]; + int[] suff = new int[n]; + + pref[0] = 1; + suff[n - 1] = 1; + for (int i = 1; i < n; i++) { + pref[i] = nums[i - 1] * pref[i - 1]; + } + for (int i = n - 2; i >= 0; i--) { + suff[i] = nums[i + 1] * suff[i + 1]; + } + for (int i = 0; i < n; i++) { + res[i] = pref[i] * suff[i]; + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ + +--- + +## 4. Prefix & Suffix (Optimal) + +::tabs-start + +```python +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + res = [1] * (len(nums)) + + prefix = 1 + for i in range(len(nums)): + res[i] = prefix + prefix *= nums[i] + postfix = 1 + for i in range(len(nums) - 1, -1, -1): + res[i] *= postfix + postfix *= nums[i] + return res +``` + +```java +public class Solution { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + int[] res = new int[n]; + + res[0] = 1; + for (int i = 1; i < n; i++) { + res[i] = res[i - 1] * nums[i - 1]; + } + + int postfix = 1; + for (int i = n - 1; i >= 0; i--) { + res[i] *= postfix; + postfix *= nums[i]; + } + return res; + } +} +``` + +```cpp +class Solution { +public: + vector productExceptSelf(vector& nums) { + int n = nums.size(); + vector res(n, 1); + + for (int i = 1; i < n; i++) { + res[i] = res[i - 1] * nums[i - 1]; + } + + int postfix = 1; + for (int i = n - 1; i >= 0; i--) { + res[i] *= postfix; + postfix *= nums[i]; + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number[]} + */ + productExceptSelf(nums) { + const n = nums.length; + const res = new Array(n).fill(1); + + for (let i = 1; i < n; i++) { + res[i] = res[i - 1] * nums[i - 1]; + } + + let postfix = 1; + for (let i = n - 1; i >= 0; i--) { + res[i] *= postfix; + postfix *= nums[i]; + } + return res; + } +} +``` + +```csharp +public class Solution { + public int[] ProductExceptSelf(int[] nums) { + int n = nums.Length; + int[] res = new int[n]; + Array.Fill(res, 1); + + for (int i = 1; i < n; i++) { + res[i] = res[i - 1] * nums[i - 1]; + } + + int postfix = 1; + for (int i = n - 1; i >= 0; i--) { + res[i] *= postfix; + postfix *= nums[i]; + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ \ No newline at end of file diff --git a/articles/top-k-elements-in-list.md b/articles/top-k-elements-in-list.md new file mode 100644 index 000000000..734345363 --- /dev/null +++ b/articles/top-k-elements-in-list.md @@ -0,0 +1,416 @@ +## 1. Sorting + +::tabs-start + +```python +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + count = {} + for num in nums: + count[num] = 1 + count.get(num, 0) + + arr = [] + for num, cnt in count.items(): + arr.append([cnt, num]) + arr.sort() + + res = [] + while len(res) < k: + res.append(arr.pop()[1]) + return res +``` + +```java +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 arr = new ArrayList<>(); + for (Map.Entry entry : count.entrySet()) { + arr.add(new int[] {entry.getValue(), entry.getKey()}); + } + arr.sort((a, b) -> b[0] - a[0]); + + int[] res = new int[k]; + for (int i = 0; i < k; i++) { + res[i] = arr.get(i)[1]; + } + return res; + } +} +``` + +```cpp +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map count; + for (int num : nums) { + count[num]++; + } + + vector> arr; + for (const auto& p : count) { + arr.push_back({p.second, p.first}); + } + sort(arr.rbegin(), arr.rend()); + + vector res; + for (int i = 0; i < k; ++i) { + res.push_back(arr[i].second); + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ + topKFrequent(nums, k) { + const count = {}; + for (const num of nums) { + count[num] = (count[num] || 0) + 1; + } + + const arr = Object.entries(count).map(([num, freq]) => [freq, parseInt(num)]); + arr.sort((a, b) => b[0] - a[0]); + + return arr.slice(0, k).map(pair => pair[1]); + } +} +``` + +```csharp +public class Solution { + public int[] TopKFrequent(int[] nums, int k) { + Dictionary count = new Dictionary(); + foreach (int num in nums) { + if (count.ContainsKey(num)) count[num]++; + else count[num] = 1; + } + + List arr = count.Select(entry => new int[] {entry.Value, entry.Key}).ToList(); + arr.Sort((a, b) => b[0].CompareTo(a[0])); + + int[] res = new int[k]; + for (int i = 0; i < k; i++) { + res[i] = arr[i][1]; + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n \log n)$ +* Space complexity: $O(n)$ + +--- + +## 2. Heap + +::tabs-start + +```python +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + count = {} + for num in nums: + count[num] = 1 + count.get(num, 0) + + heap = [] + for num in count.keys(): + heapq.heappush(heap, (count[num], num)) + if len(heap) > k: + heapq.heappop(heap) + + res = [] + for i in range(k): + res.append(heapq.heappop(heap)[1]) + return res +``` + +```java +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); + } + + PriorityQueue heap = new PriorityQueue<>((a, b) -> a[0] - b[0]); + for (Map.Entry entry : count.entrySet()) { + heap.offer(new int[]{entry.getValue(), entry.getKey()}); + if (heap.size() > k) { + heap.poll(); + } + } + + int[] res = new int[k]; + for (int i = 0; i < k; i++) { + res[i] = heap.poll()[1]; + } + return res; + } +} +``` + +```cpp +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map count; + for (int num : nums) { + count[num]++; + } + + priority_queue, vector>, greater>> heap; + for (auto& entry : count) { + heap.push({entry.second, entry.first}); + if (heap.size() > k) { + heap.pop(); + } + } + + vector res; + for (int i = 0; i < k; i++) { + res.push_back(heap.top().second); + heap.pop(); + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ + topKFrequent(nums, k) { + const count = {}; + for (const num of nums) { + count[num] = (count[num] || 0) + 1; + } + + const heap = new MinPriorityQueue(); // Implement Custom Heap Class + for(const [num, cnt] of Object.entries(count)){ + heap.enqueue(num, cnt); + if (heap.size() > k) heap.dequeue(); + } + + const res = []; + for(let i = 0; i < k; i++) { + res.push(heap.dequeue().element) + } + return res; + } +} +``` + +```csharp +public class Solution { + public int[] TopKFrequent(int[] nums, int k) { + var count = new Dictionary(); + foreach (var num in nums) { + if (count.ContainsKey(num)) { + count[num]++; + } else { + count[num] = 1; + } + } + + var heap = new PriorityQueue(); + foreach (var entry in count) { + heap.Enqueue(entry.Key, entry.Value); + if (heap.Count > k) { + heap.Dequeue(); + } + } + + var res = new int[k]; + for (int i = 0; i < k; i++) { + res[i] = heap.Dequeue(); + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n \log k)$ +* Space complexity: $O(n)$ + +--- + +## 3. Bucket Sort + +::tabs-start + +```python +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + count = {} + freq = [[] for i in range(len(nums) + 1)] + + for num in nums: + count[num] = 1 + count.get(num, 0) + for num, cnt in count.items(): + freq[cnt].append(num) + + res = [] + for i in range(len(freq) - 1, 0, -1): + for num in freq[i]: + res.append(num) + if len(res) == k: + return res +``` + +```java +public class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map count = new HashMap<>(); + List[] freq = new List[nums.length + 1]; + + for (int i = 0; i < freq.length; i++) { + freq[i] = new ArrayList<>(); + } + + for (int n : nums) { + count.put(n, count.getOrDefault(n, 0) + 1); + } + for (Map.Entry entry : count.entrySet()) { + freq[entry.getValue()].add(entry.getKey()); + } + + int[] res = new int[k]; + int index = 0; + for (int i = freq.length - 1; i > 0 && index < k; i--) { + for (int n : freq[i]) { + res[index++] = n; + if (index == k) { + return res; + } + } + } + return res; + } +} +``` + +```cpp +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map count; + vector> freq(nums.size() + 1); + + for (int n : nums) { + count[n] = 1 + count[n]; + } + for (const auto& entry : count) { + freq[entry.second].push_back(entry.first); + } + + vector res; + for (int i = freq.size() - 1; i > 0; --i) { + for (int n : freq[i]) { + res.push_back(n); + if (res.size() == k) { + return res; + } + } + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ + topKFrequent(nums, k) { + const count = {}; + const freq = Array.from({ length: nums.length + 1 }, () => []); + + for (const n of nums) { + count[n] = (count[n] || 0) + 1; + } + for (const n in count) { + freq[count[n]].push(parseInt(n)); + } + + const res = []; + for (let i = freq.length - 1; i > 0; i--) { + for (const n of freq[i]) { + res.push(n); + if (res.length === k) { + return res; + } + } + } + } +} +``` + +```csharp +public class Solution { + public int[] TopKFrequent(int[] nums, int k) { + Dictionary count = new Dictionary(); + List[] freq = new List[nums.Length + 1]; + for (int i = 0; i < freq.Length; i++) { + freq[i] = new List(); + } + + foreach (int n in nums) { + if (count.ContainsKey(n)) { + count[n]++; + } else { + count[n] = 1; + } + } + foreach (var entry in count){ + freq[entry.Value].Add(entry.Key); + } + + int[] res = new int[k]; + int index = 0; + for (int i = freq.Length - 1; i > 0 && index < k; i--) { + foreach (int n in freq[i]) { + res[index++] = n; + if (index == k) { + return res; + } + } + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ \ No newline at end of file From 47ce740d3ccaa4975a71782791d254315fef2550 Mon Sep 17 00:00:00 2001 From: Sri Hari Date: Thu, 3 Oct 2024 23:15:52 +0530 Subject: [PATCH 2/2] Added comment for Time Complexity with more than one var --- articles/anagram-groups.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/articles/anagram-groups.md b/articles/anagram-groups.md index 1cce9924e..251b2e043 100644 --- a/articles/anagram-groups.md +++ b/articles/anagram-groups.md @@ -92,6 +92,8 @@ public class Solution { * Time complexity: $O(m * n \log n)$ * Space complexity: $O(m * n)$ +> Where $m$ is the number of strings and $n$ is the length of the longest string. + --- ## 2. Hash Table @@ -202,4 +204,6 @@ public class Solution { ### Time & Space Complexity * Time complexity: $O(m * n)$ -* Space complexity: $O(m)$ \ No newline at end of file +* Space complexity: $O(m)$ + +> Where $m$ is the number of strings and $n$ is the length of the longest string. \ No newline at end of file