From 833a7706bb6528b76803e7ee01a653a715f1caec Mon Sep 17 00:00:00 2001 From: Sri Hari Date: Fri, 17 Jan 2025 22:52:27 +0530 Subject: [PATCH 1/2] Batch-5/Neetcode-ALL/Added-articles --- articles/calculate-money-in-leetcode-bank.md | 248 +++++++ .../count-odd-numbers-in-an-interval-range.md | 187 ++++++ articles/count-of-matches-in-tournament.md | 120 ++++ articles/find-the-difference.md | 466 ++++++++++++++ articles/image-smoother.md | 530 +++++++++++++++ articles/largest-local-values-in-a-matrix.md | 439 +++++++++++++ articles/largest-odd-number-in-string.md | 166 +++++ articles/matrix-diagonal-sum.md | 184 ++++++ articles/max-points-on-a-line.md | 384 +++++++++++ articles/palindrome-number.md | 420 ++++++++++++ articles/power-of-four.md | 367 +++++++++++ articles/power-of-two.md | 351 ++++++++++ articles/shift-2d-grid.md | 502 +++++++++++++++ articles/shuffle-the-array.md | 257 ++++++++ articles/single-number-iii.md | 608 ++++++++++++++++++ articles/spiral-matrix-ii.md | 454 +++++++++++++ articles/ugly-number.md | 76 +++ articles/zigzag-conversion.md | 226 +++++++ 18 files changed, 5985 insertions(+) create mode 100644 articles/calculate-money-in-leetcode-bank.md create mode 100644 articles/count-odd-numbers-in-an-interval-range.md create mode 100644 articles/count-of-matches-in-tournament.md create mode 100644 articles/find-the-difference.md create mode 100644 articles/image-smoother.md create mode 100644 articles/largest-local-values-in-a-matrix.md create mode 100644 articles/largest-odd-number-in-string.md create mode 100644 articles/matrix-diagonal-sum.md create mode 100644 articles/max-points-on-a-line.md create mode 100644 articles/palindrome-number.md create mode 100644 articles/power-of-four.md create mode 100644 articles/power-of-two.md create mode 100644 articles/shift-2d-grid.md create mode 100644 articles/shuffle-the-array.md create mode 100644 articles/single-number-iii.md create mode 100644 articles/spiral-matrix-ii.md create mode 100644 articles/ugly-number.md create mode 100644 articles/zigzag-conversion.md diff --git a/articles/calculate-money-in-leetcode-bank.md b/articles/calculate-money-in-leetcode-bank.md new file mode 100644 index 000000000..1735a4724 --- /dev/null +++ b/articles/calculate-money-in-leetcode-bank.md @@ -0,0 +1,248 @@ +## 1. Simulation + +::tabs-start + +```python +class Solution: + def totalMoney(self, n: int) -> int: + day, deposit = 0, 1 + res = 0 + + while day < n: + res += deposit + deposit += 1 + day += 1 + + if day % 7 == 0: + deposit = 1 + day // 7 + + return res +``` + +```java +public class Solution { + public int totalMoney(int n) { + int day = 0, deposit = 1, res = 0; + + while (day < n) { + res += deposit; + deposit++; + day++; + + if (day % 7 == 0) { + deposit = 1 + day / 7; + } + } + + return res; + } +} +``` + +```cpp +class Solution { +public: + int totalMoney(int n) { + int day = 0, deposit = 1, res = 0; + + while (day < n) { + res += deposit; + deposit++; + day++; + + if (day % 7 == 0) { + deposit = 1 + day / 7; + } + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {number} + */ + totalMoney(n) { + let day = 0, deposit = 1, res = 0; + + while (day < n) { + res += deposit; + deposit++; + day++; + + if (day % 7 === 0) { + deposit = 1 + Math.floor(day / 7); + } + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ + +--- + +## 2. Math + +::tabs-start + +```python +class Solution: + def totalMoney(self, n: int) -> int: + weeks = n // 7 + low = 28 + high = 28 + 7 * (weeks - 1) + res = weeks * (low + high) // 2 + + monday = weeks + 1 + for i in range(n % 7): + res += i + monday + + return res +``` + +```java +public class Solution { + public int totalMoney(int n) { + int weeks = n / 7; + int low = 28; + int high = 28 + 7 * (weeks - 1); + int res = weeks * (low + high) / 2; + + int monday = weeks + 1; + for (int i = 0; i < n % 7; i++) { + res += i + monday; + } + + return res; + } +} +``` + +```cpp +class Solution { +public: + int totalMoney(int n) { + int weeks = n / 7; + int low = 28; + int high = 28 + 7 * (weeks - 1); + int res = weeks * (low + high) / 2; + + int monday = weeks + 1; + for (int i = 0; i < n % 7; i++) { + res += i + monday; + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {number} + */ + totalMoney(n) { + const weeks = Math.floor(n / 7); + const low = 28; + const high = 28 + 7 * (weeks - 1); + let res = weeks * (low + high) / 2; + + const monday = weeks + 1; + for (let i = 0; i < n % 7; i++) { + res += i + monday; + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ + +--- + +## 3. Math (Optimal) + +::tabs-start + +```python +class Solution: + def totalMoney(self, n: int) -> int: + SUM = lambda x: (x * (x + 1)) >> 1 + weeks = n // 7 + res = SUM(weeks - 1) * 7 + weeks * SUM(7) + res += SUM(n % 7) + weeks * (n % 7) + return res +``` + +```java +public class Solution { + public int totalMoney(int n) { + int weeks = n / 7; + int res = SUM(weeks - 1) * 7 + weeks * SUM(7); + res += SUM(n % 7) + weeks * (n % 7); + return res; + } + + private int SUM(int n) { + return (n * (n + 1)) / 2; + } +} +``` + +```cpp +class Solution { +public: + int totalMoney(int n) { + auto SUM = [](int x) { return (x * (x + 1)) / 2; }; + + int weeks = n / 7; + int res = SUM(weeks - 1) * 7 + weeks * SUM(7); + res += SUM(n % 7) + weeks * (n % 7); + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {number} + */ + totalMoney(n) { + const SUM = x => (x * (x + 1)) / 2; + + const weeks = Math.floor(n / 7); + let res = SUM(weeks - 1) * 7 + weeks * SUM(7); + res += SUM(n % 7) + weeks * (n % 7); + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ \ No newline at end of file diff --git a/articles/count-odd-numbers-in-an-interval-range.md b/articles/count-odd-numbers-in-an-interval-range.md new file mode 100644 index 000000000..1cbaf37b8 --- /dev/null +++ b/articles/count-odd-numbers-in-an-interval-range.md @@ -0,0 +1,187 @@ +## 1. Brute Force + +::tabs-start + +```python +class Solution: + def countOdds(self, low: int, high: int) -> int: + odd = 0 + for num in range(low, high + 1): + if num & 1: + odd += 1 + return odd +``` + +```java +public class Solution { + public int countOdds(int low, int high) { + int odd = 0; + for (int num = low; num <= high; num++) { + if ((num & 1) == 1) { + odd++; + } + } + return odd; + } +} +``` + +```cpp +class Solution { +public: + int countOdds(int low, int high) { + int odd = 0; + for (int num = low; num <= high; num++) { + if (num & 1) { + odd++; + } + } + return odd; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} low + * @param {number} high + * @return {number} + */ + countOdds(low, high) { + let odd = 0; + for (let num = low; num <= high; num++) { + if (num & 1) { + odd++; + } + } + return odd; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ + +> Where $n$ is the number of integers in the given range. + +--- + +## 2. Math + +::tabs-start + +```python +class Solution: + def countOdds(self, low: int, high: int) -> int: + length = high - low + 1 + count = length // 2 + if length % 2 and low % 2: + count += 1 + return count +``` + +```java +public class Solution { + public int countOdds(int low, int high) { + int length = high - low + 1; + int count = length / 2; + if (length % 2 == 1 && low % 2 == 1) { + count++; + } + return count; + } +} +``` + +```cpp +class Solution { +public: + int countOdds(int low, int high) { + int length = high - low + 1; + int count = length / 2; + if (length % 2 == 1 && low % 2 == 1) { + count++; + } + return count; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} low + * @param {number} high + * @return {number} + */ + countOdds(low, high) { + let length = high - low + 1; + let count = Math.floor(length / 2); + if (length % 2 === 1 && low % 2 === 1) { + count++; + } + return count; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ + +--- + +## 3. Math (One Liner) + +::tabs-start + +```python +class Solution: + def countOdds(self, low: int, high: int) -> int: + return ((high + 1) >> 1) - (low >> 1) +``` + +```java +public class Solution { + public int countOdds(int low, int high) { + return ((high + 1) >> 1) - (low >> 1); + } +} +``` + +```cpp +class Solution { +public: + int countOdds(int low, int high) { + return ((high + 1) >> 1) - (low >> 1); + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} low + * @param {number} high + * @return {number} + */ + countOdds(low, high) { + return ((high + 1) >> 1) - (low >> 1); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ \ No newline at end of file diff --git a/articles/count-of-matches-in-tournament.md b/articles/count-of-matches-in-tournament.md new file mode 100644 index 000000000..2ceeeae80 --- /dev/null +++ b/articles/count-of-matches-in-tournament.md @@ -0,0 +1,120 @@ +## 1. Simulation + +::tabs-start + +```python +class Solution: + def numberOfMatches(self, n: int) -> int: + res = 0 + + while n > 1: + res += n // 2 + n = (n + 1) // 2 + + return res +``` + +```java +public class Solution { + public int numberOfMatches(int n) { + int res = 0; + + while (n > 1) { + res += n / 2; + n = (n + 1) / 2; + } + + return res; + } +} +``` + +```cpp +class Solution { +public: + int numberOfMatches(int n) { + int res = 0; + + while (n > 1) { + res += n / 2; + n = (n + 1) / 2; + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {number} + */ + numberOfMatches(n) { + let res = 0; + + while (n > 1) { + res += Math.floor(n / 2); + n = Math.ceil(n / 2); + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(\log n)$ +* Space complexity: $O(1)$ + +--- + +## 2. Math + +::tabs-start + +```python +class Solution: + def numberOfMatches(self, n: int) -> int: + return n - 1 +``` + +```java +public class Solution { + public int numberOfMatches(int n) { + return n - 1; + } +} +``` + +```cpp +class Solution { +public: + int numberOfMatches(int n) { + return n - 1; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {number} + */ + numberOfMatches(n) { + return n - 1; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ \ No newline at end of file diff --git a/articles/find-the-difference.md b/articles/find-the-difference.md new file mode 100644 index 000000000..b06b2803f --- /dev/null +++ b/articles/find-the-difference.md @@ -0,0 +1,466 @@ +## 1. Two Hash Maps + +::tabs-start + +```python +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + count_s, count_t = Counter(s), Counter(t) + for c in count_t: + if c not in count_s or count_s[c] < count_t[c]: + return c +``` + +```java +public class Solution { + public char findTheDifference(String s, String t) { + int[] countS = new int[26]; + int[] countT = new int[26]; + + for (char c : s.toCharArray()) countS[c - 'a']++; + for (char c : t.toCharArray()) countT[c - 'a']++; + + for (int i = 0; i < 26; i++) { + if (countT[i] > countS[i]) { + return (char) (i + 'a'); + } + } + return ' '; + } +} +``` + +```cpp +class Solution { +public: + char findTheDifference(string s, string t) { + vector countS(26, 0), countT(26, 0); + + for (char c : s) countS[c - 'a']++; + for (char c : t) countT[c - 'a']++; + + for (int i = 0; i < 26; i++) { + if (countT[i] > countS[i]) { + return i + 'a'; + } + } + return ' '; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} s + * @param {string} t + * @return {character} + */ + findTheDifference(s, t) { + let countS = Array(26).fill(0); + let countT = Array(26).fill(0); + + for (let char of s) countS[char.charCodeAt(0) - 'a'.charCodeAt(0)]++; + for (let char of t) countT[char.charCodeAt(0) - 'a'.charCodeAt(0)]++; + + for (let i = 0; i < 26; i++) { + if (countT[i] > countS[i]) { + return String.fromCharCode(i + 'a'.charCodeAt(0)); + } + } + return ''; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ since we have at most $26$ different characters. + +--- + +## 2. One Hash Map + +::tabs-start + +```python +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + count = Counter(t) + for c in s: + count[c] -= 1 + for c in count: + if count[c] == 1: + return c +``` + +```java +public class Solution { + public char findTheDifference(String s, String t) { + int[] count = new int[26]; + + for (char c : t.toCharArray()) count[c - 'a']++; + for (char c : s.toCharArray()) count[c - 'a']--; + + for (int i = 0; i < 26; i++) { + if (count[i] == 1) { + return (char) (i + 'a'); + } + } + return ' '; + } +} +``` + +```cpp +class Solution { +public: + char findTheDifference(string s, string t) { + vector count(26); + + for (char c : t) count[c - 'a']++; + for (char c : s) count[c - 'a']--; + + for (int i = 0; i < 26; i++) { + if (count[i] == 1) { + return i + 'a'; + } + } + return ' '; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} s + * @param {string} t + * @return {character} + */ + findTheDifference(s, t) { + let count = Array(26).fill(0); + + for (let char of t) count[char.charCodeAt(0) - 'a'.charCodeAt(0)]++; + for (let char of s) count[char.charCodeAt(0) - 'a'.charCodeAt(0)]--; + + for (let i = 0; i < 26; i++) { + if (count[i] === 1) { + return String.fromCharCode(i + 'a'.charCodeAt(0)); + } + } + return ''; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ since we have at most $26$ different characters. + +--- + +## 3. Sorting + +::tabs-start + +```python +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + s, t = sorted(s), sorted(t) + for c1, c2 in zip(s, t): + if c1 != c2: + return c2 + return t[-1] +``` + +```java +public class Solution { + public char findTheDifference(String s, String t) { + char[] sArr = s.toCharArray(); + char[] tArr = t.toCharArray(); + Arrays.sort(sArr); + Arrays.sort(tArr); + for (int i = 0; i < sArr.length; i++) { + if (sArr[i] != tArr[i]) { + return tArr[i]; + } + } + return tArr[tArr.length - 1]; + } +} +``` + +```cpp +class Solution { +public: + char findTheDifference(string s, string t) { + sort(s.begin(), s.end()); + sort(t.begin(), t.end()); + for (int i = 0; i < s.size(); i++) { + if (s[i] != t[i]) { + return t[i]; + } + } + return t[t.size() - 1]; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} s + * @param {string} t + * @return {character} + */ + findTheDifference(s, t) { + s = s.split('').sort(); + t = t.split('').sort(); + for (let i = 0; i < s.length; i++) { + if (s[i] !== t[i]) { + return t[i]; + } + } + return t[t.length - 1]; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n \log n)$ +* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. + +--- + +## 4. Difference Between ASCII Values + +::tabs-start + +```python +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + sum_s, sum_t = 0, 0 + for c in s: + sum_s += ord(c) + for c in t: + sum_t += ord(c) + return chr(sum_t - sum_s) +``` + +```java +public class Solution { + public char findTheDifference(String s, String t) { + int sumS = 0, sumT = 0; + for (int i = 0; i < s.length(); i++) { + sumS += s.charAt(i); + } + for (int i = 0; i < t.length(); i++) { + sumT += t.charAt(i); + } + return (char) (sumT - sumS); + } +} +``` + +```cpp +class Solution { +public: + char findTheDifference(string s, string t) { + int sumS = 0, sumT = 0; + for (char c : s) { + sumS += c; + } + for (char c : t) { + sumT += c; + } + return (char) (sumT - sumS); + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} s + * @param {string} t + * @return {character} + */ + findTheDifference(s, t) { + let sumS = 0, sumT = 0; + for (let char of s) { + sumS += char.charCodeAt(0); + } + for (let char of t) { + sumT += char.charCodeAt(0); + } + return String.fromCharCode(sumT - sumS); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ extra space. + +--- + +## 5. Difference Between ASCII Values (Optimal) + +::tabs-start + +```python +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + res = 0 + for c in s: + res -= ord(c) + for c in t: + res += ord(c) + return chr(res) +``` + +```java +public class Solution { + public char findTheDifference(String s, String t) { + int res = 0; + for (int i = 0; i < s.length(); i++) { + res -= s.charAt(i); + } + for (int i = 0; i < t.length(); i++) { + res += t.charAt(i); + } + return (char) (res); + } +} +``` + +```cpp +class Solution { +public: + char findTheDifference(string s, string t) { + int res = 0; + for (char c : s) { + res -= c; + } + for (char c : t) { + res += c; + } + return (char) (res); + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} s + * @param {string} t + * @return {character} + */ + findTheDifference(s, t) { + let res = 0; + for (let char of s) { + res -= char.charCodeAt(0); + } + for (let char of t) { + res += char.charCodeAt(0); + } + return String.fromCharCode(res); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ extra space. + +--- + +## 6. Bitwise XOR + +::tabs-start + +```python +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + res = 0 + for c in s: + res ^= ord(c) + for c in t: + res ^= ord(c) + return chr(res) +``` + +```java +public class Solution { + public char findTheDifference(String s, String t) { + int res = 0; + for (int i = 0; i < s.length(); i++) { + res ^= s.charAt(i); + } + for (int i = 0; i < t.length(); i++) { + res ^= t.charAt(i); + } + return (char) (res); + } +} +``` + +```cpp +class Solution { +public: + char findTheDifference(string s, string t) { + int res = 0; + for (char c : s) { + res ^= c; + } + for (char c : t) { + res ^= c; + } + return (char) (res); + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} s + * @param {string} t + * @return {character} + */ + findTheDifference(s, t) { + let res = 0; + for (let char of s) { + res ^= char.charCodeAt(0); + } + for (let char of t) { + res ^= char.charCodeAt(0); + } + return String.fromCharCode(res); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ extra space. \ No newline at end of file diff --git a/articles/image-smoother.md b/articles/image-smoother.md new file mode 100644 index 000000000..767d82e16 --- /dev/null +++ b/articles/image-smoother.md @@ -0,0 +1,530 @@ +## 1. Iteration (Using Extra Matrix) + +::tabs-start + +```python +class Solution: + def imageSmoother(self, img: List[List[int]]) -> List[List[int]]: + ROWS, COLS = len(img), len(img[0]) + res = [[0] * COLS for _ in range(ROWS)] + + for r in range(ROWS): + for c in range(COLS): + total, cnt = 0, 0 + for i in range(r - 1, r + 2): + for j in range(c - 1, c + 2): + if 0 <= i < ROWS and 0 <= j < COLS: + total += img[i][j] + cnt += 1 + res[r][c] = total // cnt + + return res +``` + +```java +public class Solution { + public int[][] imageSmoother(int[][] img) { + int ROWS = img.length, COLS = img[0].length; + int[][] res = new int[ROWS][COLS]; + + for (int r = 0; r < ROWS; r++) { + for (int c = 0; c < COLS; c++) { + int total = 0, count = 0; + for (int i = r - 1; i <= r + 1; i++) { + for (int j = c - 1; j <= c + 1; j++) { + if (i >= 0 && i < ROWS && j >= 0 && j < COLS) { + total += img[i][j]; + count++; + } + } + } + res[r][c] = total / count; + } + } + + return res; + } +} +``` + +```cpp +class Solution { +public: + vector> imageSmoother(vector>& img) { + int ROWS = img.size(), COLS = img[0].size(); + vector> res(ROWS, vector(COLS, 0)); + + for (int r = 0; r < ROWS; r++) { + for (int c = 0; c < COLS; c++) { + int total = 0, count = 0; + for (int i = r - 1; i <= r + 1; i++) { + for (int j = c - 1; j <= c + 1; j++) { + if (i >= 0 && i < ROWS && j >= 0 && j < COLS) { + total += img[i][j]; + count++; + } + } + } + res[r][c] = total / count; + } + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} img + * @return {number[][]} + */ + imageSmoother(img) { + const ROWS = img.length, COLS = img[0].length; + const res = Array.from({ length: ROWS }, () => Array(COLS).fill(0)); + + for (let r = 0; r < ROWS; r++) { + for (let c = 0; c < COLS; c++) { + let total = 0, count = 0; + for (let i = r - 1; i <= r + 1; i++) { + for (let j = c - 1; j <= c + 1; j++) { + if (i >= 0 && i < ROWS && j >= 0 && j < COLS) { + total += img[i][j]; + count++; + } + } + } + res[r][c] = Math.floor(total / count); + } + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n * m)$ +* Space complexity: $O(n * m)$ + +> Where $n$ is the number of rows and $m$ is the number of columns of the matrix. + +--- + +## 2. Iteration (Using Extra Row) + +::tabs-start + +```python +class Solution: + def imageSmoother(self, img: List[List[int]]) -> List[List[int]]: + ROWS, COLS = len(img), len(img[0]) + prev_row = img[0][:] + + for r in range(ROWS): + curr_row = img[r][:] + + for c in range(COLS): + total, cnt = 0, 0 + for i in range(max(0, r - 1), min(ROWS, r + 2)): + for j in range(max(0, c - 1), min(COLS, c + 2)): + if i == r: + total += curr_row[j] + elif i == r - 1: + total += prev_row[j] + else: + total += img[i][j] + cnt += 1 + img[r][c] = total // cnt + + prev_row = curr_row + + return img +``` + +```java +public class Solution { + public int[][] imageSmoother(int[][] img) { + int ROWS = img.length, COLS = img[0].length; + int[] prevRow = img[0].clone(); + + for (int r = 0; r < ROWS; r++) { + int[] currRow = img[r].clone(); + + for (int c = 0; c < COLS; c++) { + int total = 0, count = 0; + for (int i = Math.max(0, r - 1); i < Math.min(ROWS, r + 2); i++) { + for (int j = Math.max(0, c - 1); j < Math.min(COLS, c + 2); j++) { + if (i == r) { + total += currRow[j]; + } else if (i == r - 1) { + total += prevRow[j]; + } else { + total += img[i][j]; + } + count++; + } + } + img[r][c] = total / count; + } + + prevRow = currRow; + } + + return img; + } +} +``` + +```cpp +class Solution { +public: + vector> imageSmoother(vector>& img) { + int ROWS = img.size(), COLS = img[0].size(); + vector prevRow = img[0]; + + for (int r = 0; r < ROWS; r++) { + vector currRow = img[r]; + + for (int c = 0; c < COLS; c++) { + int total = 0, count = 0; + for (int i = max(0, r - 1); i < min(ROWS, r + 2); i++) { + for (int j = max(0, c - 1); j < min(COLS, c + 2); j++) { + if (i == r) { + total += currRow[j]; + } else if (i == r - 1) { + total += prevRow[j]; + } else { + total += img[i][j]; + } + count++; + } + } + img[r][c] = total / count; + } + + prevRow = currRow; + } + + return img; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} img + * @return {number[][]} + */ + imageSmoother(img) { + const ROWS = img.length, COLS = img[0].length; + let prevRow = [...img[0]]; + + for (let r = 0; r < ROWS; r++) { + let currRow = [...img[r]]; + + for (let c = 0; c < COLS; c++) { + let total = 0, count = 0; + for (let i = Math.max(0, r - 1); i < Math.min(ROWS, r + 2); i++) { + for (let j = Math.max(0, c - 1); j < Math.min(COLS, c + 2); j++) { + if (i === r) { + total += currRow[j]; + } else if (i === r - 1) { + total += prevRow[j]; + } else { + total += img[i][j]; + } + count++; + } + } + img[r][c] = Math.floor(total / count); + } + + prevRow = currRow; + } + + return img; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n * m)$ +* Space complexity: $O(n)$ extra space. + +> Where $n$ is the number of rows and $m$ is the number of columns of the matrix. + +--- + +## 3. Iteration (Without Extra Space) + +::tabs-start + +```python +class Solution: + def imageSmoother(self, img: List[List[int]]) -> List[List[int]]: + ROWS, COLS = len(img), len(img[0]) + LIMIT = 256 + + for r in range(ROWS): + for c in range(COLS): + total, cnt = 0, 0 + for i in range(max(0, r - 1), min(ROWS, r + 2)): + for j in range(max(0, c - 1), min(COLS, c + 2)): + total += img[i][j] % LIMIT + cnt += 1 + img[r][c] += (total // cnt) * LIMIT + + for r in range(ROWS): + for c in range(COLS): + img[r][c] //= LIMIT + + return img +``` + +```java +public class Solution { + public int[][] imageSmoother(int[][] img) { + int ROWS = img.length, COLS = img[0].length; + int LIMIT = 256; + + for (int r = 0; r < ROWS; r++) { + for (int c = 0; c < COLS; c++) { + int total = 0, count = 0; + for (int i = Math.max(0, r - 1); i < Math.min(ROWS, r + 2); i++) { + for (int j = Math.max(0, c - 1); j < Math.min(COLS, c + 2); j++) { + total += img[i][j] % LIMIT; + count++; + } + } + img[r][c] += (total / count) * LIMIT; + } + } + + for (int r = 0; r < ROWS; r++) { + for (int c = 0; c < COLS; c++) { + img[r][c] /= LIMIT; + } + } + + return img; + } +} +``` + +```cpp +class Solution { +public: + vector> imageSmoother(vector>& img) { + int ROWS = img.size(), COLS = img[0].size(); + int LIMIT = 256; + + for (int r = 0; r < ROWS; ++r) { + for (int c = 0; c < COLS; ++c) { + int total = 0, count = 0; + for (int i = max(0, r - 1); i < min(ROWS, r + 2); ++i) { + for (int j = max(0, c - 1); j < min(COLS, c + 2); ++j) { + total += img[i][j] % LIMIT; + count++; + } + } + img[r][c] += (total / count) * LIMIT; + } + } + + for (int r = 0; r < ROWS; ++r) { + for (int c = 0; c < COLS; ++c) { + img[r][c] /= LIMIT; + } + } + + return img; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} img + * @return {number[][]} + */ + imageSmoother(img) { + const ROWS = img.length, COLS = img[0].length; + const LIMIT = 256; + + for (let r = 0; r < ROWS; r++) { + for (let c = 0; c < COLS; c++) { + let total = 0, count = 0; + for (let i = Math.max(0, r - 1); i < Math.min(ROWS, r + 2); i++) { + for (let j = Math.max(0, c - 1); j < Math.min(COLS, c + 2); j++) { + total += img[i][j] % LIMIT; + count++; + } + } + img[r][c] += Math.floor(total / count) * LIMIT; + } + } + + for (let r = 0; r < ROWS; r++) { + for (let c = 0; c < COLS; c++) { + img[r][c] = Math.floor(img[r][c] / LIMIT); + } + } + + return img; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n * m)$ +* Space complexity: $O(1)$ extra space. + +> Where $n$ is the number of rows and $m$ is the number of columns of the matrix. + +--- + +## 4. Bit Mask + +::tabs-start + +```python +class Solution: + def imageSmoother(self, img: List[List[int]]) -> List[List[int]]: + ROWS, COLS = len(img), len(img[0]) + + for r in range(ROWS): + for c in range(COLS): + total, cnt = 0, 0 + for i in range(r - 1, r + 2): + for j in range(c - 1, c + 2): + if i < 0 or i == ROWS or j < 0 or j == COLS: + continue + total += img[i][j] % 256 + cnt += 1 + img[r][c] ^= ((total // cnt) << 8) + + for r in range(ROWS): + for c in range(COLS): + img[r][c] >>= 8 + return img +``` + +```java +public class Solution { + public int[][] imageSmoother(int[][] img) { + int ROWS = img.length, COLS = img[0].length; + + for (int r = 0; r < ROWS; r++) { + for (int c = 0; c < COLS; c++) { + int total = 0, cnt = 0; + for (int i = r - 1; i <= r + 1; i++) { + for (int j = c - 1; j <= c + 1; j++) { + if (i < 0 || i >= ROWS || j < 0 || j >= COLS) { + continue; + } + total += img[i][j] % 256; + cnt++; + } + } + img[r][c] ^= ((total / cnt) << 8); + } + } + + for (int r = 0; r < ROWS; r++) { + for (int c = 0; c < COLS; c++) { + img[r][c] >>= 8; + } + } + return img; + } +} +``` + +```cpp +class Solution { +public: + vector> imageSmoother(vector>& img) { + int ROWS = img.size(), COLS = img[0].size(); + + for (int r = 0; r < ROWS; r++) { + for (int c = 0; c < COLS; c++) { + int total = 0, cnt = 0; + for (int i = r - 1; i <= r + 1; i++) { + for (int j = c - 1; j <= c + 1; j++) { + if (i < 0 || i >= ROWS || j < 0 || j >= COLS) { + continue; + } + total += img[i][j] % 256; + cnt++; + } + } + img[r][c] ^= ((total / cnt) << 8); + } + } + + for (int r = 0; r < ROWS; r++) { + for (int c = 0; c < COLS; c++) { + img[r][c] >>= 8; + } + } + return img; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} img + * @return {number[][]} + */ + imageSmoother(img) { + const ROWS = img.length, COLS = img[0].length; + + for (let r = 0; r < ROWS; r++) { + for (let c = 0; c < COLS; c++) { + let total = 0, cnt = 0; + for (let i = r - 1; i <= r + 1; i++) { + for (let j = c - 1; j <= c + 1; j++) { + if (i < 0 || i >= ROWS || j < 0 || j >= COLS) { + continue; + } + total += img[i][j] % 256; + cnt++; + } + } + img[r][c] ^= ((total / cnt) << 8); + } + } + + for (let r = 0; r < ROWS; r++) { + for (let c = 0; c < COLS; c++) { + img[r][c] >>= 8; + } + } + return img; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n * m)$ +* Space complexity: $O(1)$ extra space. + +> Where $n$ is the number of rows and $m$ is the number of columns of the matrix. \ No newline at end of file diff --git a/articles/largest-local-values-in-a-matrix.md b/articles/largest-local-values-in-a-matrix.md new file mode 100644 index 000000000..169c4d992 --- /dev/null +++ b/articles/largest-local-values-in-a-matrix.md @@ -0,0 +1,439 @@ +## 1. Iteration + +::tabs-start + +```python +class Solution: + def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: + N = len(grid) + res = [[0] * (N - 2) for _ in range(N - 2)] + + for i in range(N - 2): + for j in range(N - 2): + for r in range(i, i + 3): + for c in range(j, j + 3): + res[i][j] = max(res[i][j], grid[r][c]) + + return res +``` + +```java +public class Solution { + public int[][] largestLocal(int[][] grid) { + int N = grid.length; + int[][] res = new int[N - 2][N - 2]; + + for (int i = 0; i < N - 2; i++) { + for (int j = 0; j < N - 2; j++) { + for (int r = i; r < i + 3; r++) { + for (int c = j; c < j + 3; c++) { + res[i][j] = Math.max(res[i][j], grid[r][c]); + } + } + } + } + + return res; + } +} +``` + +```cpp +class Solution { +public: + vector> largestLocal(vector>& grid) { + int N = grid.size(); + vector> res(N - 2, vector(N - 2, 0)); + + for (int i = 0; i < N - 2; i++) { + for (int j = 0; j < N - 2; j++) { + for (int r = i; r < i + 3; r++) { + for (int c = j; c < j + 3; c++) { + res[i][j] = max(res[i][j], grid[r][c]); + } + } + } + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} grid + * @return {number[][]} + */ + largestLocal(grid) { + const N = grid.length; + const res = Array.from({ length: N - 2 }, () => Array(N - 2).fill(0)); + + for (let i = 0; i < N - 2; i++) { + for (let j = 0; j < N - 2; j++) { + for (let r = i; r < i + 3; r++) { + for (let c = j; c < j + 3; c++) { + res[i][j] = Math.max(res[i][j], grid[r][c]); + } + } + } + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 2)$ +* Space complexity: + * $O(1)$ extra space. + * $O(n ^ 2)$ for the output array. + +--- + +## 2. Generalized Approach (Sparse Table) + +::tabs-start + +```python +class SparseTable: + def __init__(self, grid: List[List[int]]): + self.n = len(grid) + self.LOG = [0] * (self.n + 1) + for i in range(2, self.n + 1): + self.LOG[i] = self.LOG[i // 2] + 1 + + self.sparse_table = [[[[0] * (self.LOG[self.n] + 1) for _ in range(self.LOG[self.n] + 1)] for _ in range(self.n)] for _ in range(self.n)] + + for r in range(self.n): + for c in range(self.n): + self.sparse_table[r][c][0][0] = grid[r][c] + + for i in range(self.LOG[self.n] + 1): + for j in range(self.LOG[self.n] + 1): + for r in range(self.n - (1 << i) + 1): + for c in range(self.n - (1 << j) + 1): + if i == 0 and j == 0: + self.sparse_table[r][c][i][j] = grid[r][c] + elif i == 0: + self.sparse_table[r][c][i][j] = max( + self.sparse_table[r][c][i][j - 1], + self.sparse_table[r][c + (1 << (j - 1))][i][j - 1], + ) + elif j == 0: + self.sparse_table[r][c][i][j] = max( + self.sparse_table[r][c][i - 1][j], + self.sparse_table[r + (1 << (i - 1))][c][i - 1][j], + ) + else: + self.sparse_table[r][c][i][j] = max( + self.sparse_table[r][c][i - 1][j - 1], + self.sparse_table[r + (1 << (i - 1))][c][i - 1][j - 1], + self.sparse_table[r][c + (1 << (j - 1))][i - 1][j - 1], + self.sparse_table[r + (1 << (i - 1))][c + (1 << (j - 1))][i - 1][j - 1], + ) + + def query(self, x1: int, y1: int, x2: int, y2: int) -> int: + lx, ly = self.LOG[x2 - x1 + 1], self.LOG[y2 - y1 + 1] + return max( + self.sparse_table[x1][y1][lx][ly], + self.sparse_table[x2 - (1 << lx) + 1][y1][lx][ly], + self.sparse_table[x1][y2 - (1 << ly) + 1][lx][ly], + self.sparse_table[x2 - (1 << lx) + 1][y2 - (1 << ly) + 1][lx][ly], + ) + + +class Solution: + def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: + N, k = len(grid), 3 + sparse_table = SparseTable(grid) + res = [[0] * (N - k + 1) for _ in range(N - k + 1)] + + for i in range(N - k + 1): + for j in range(N - k + 1): + res[i][j] = sparse_table.query(i, j, i + k - 1, j + k - 1) + + return res +``` + +```java +class SparseTable { + private int[][][][] sparseTable; + private int[] log; + private int n; + + public SparseTable(int[][] grid) { + n = grid.length; + log = new int[n + 1]; + for (int i = 2; i <= n; i++) { + log[i] = log[i >> 1] + 1; + } + + int maxLog = log[n]; + sparseTable = new int[n][n][maxLog + 1][maxLog + 1]; + + for (int r = 0; r < n; r++) { + for (int c = 0; c < n; c++) { + sparseTable[r][c][0][0] = grid[r][c]; + } + } + + for (int i = 0; i <= maxLog; i++) { + for (int j = 0; j <= maxLog; j++) { + for (int r = 0; r + (1 << i) <= n; r++) { + for (int c = 0; c + (1 << j) <= n; c++) { + if (i == 0 && j == 0) continue; + if (i == 0) { + sparseTable[r][c][i][j] = Math.max( + sparseTable[r][c][i][j - 1], + sparseTable[r][c + (1 << (j - 1))][i][j - 1] + ); + } else if (j == 0) { + sparseTable[r][c][i][j] = Math.max( + sparseTable[r][c][i - 1][j], + sparseTable[r + (1 << (i - 1))][c][i - 1][j] + ); + } else { + sparseTable[r][c][i][j] = Math.max( + Math.max(sparseTable[r][c][i - 1][j - 1], sparseTable[r + (1 << (i - 1))][c][i - 1][j - 1]), + Math.max(sparseTable[r][c + (1 << (j - 1))][i - 1][j - 1], + sparseTable[r + (1 << (i - 1))][c + (1 << (j - 1))][i - 1][j - 1]) + ); + } + } + } + } + } + } + + public int query(int x1, int y1, int x2, int y2) { + int lx = log[x2 - x1 + 1]; + int ly = log[y2 - y1 + 1]; + return Math.max( + Math.max(sparseTable[x1][y1][lx][ly], sparseTable[x2 - (1 << lx) + 1][y1][lx][ly]), + Math.max(sparseTable[x1][y2 - (1 << ly) + 1][lx][ly], + sparseTable[x2 - (1 << lx) + 1][y2 - (1 << ly) + 1][lx][ly]) + ); + } +} + +public class Solution { + public int[][] largestLocal(int[][] grid) { + int n = grid.length; + int k = 3; + SparseTable st = new SparseTable(grid); + int[][] res = new int[n - k + 1][n - k + 1]; + + for (int i = 0; i <= n - k; i++) { + for (int j = 0; j <= n - k; j++) { + res[i][j] = st.query(i, j, i + k - 1, j + k - 1); + } + } + + return res; + } +} +``` + +```cpp +class SparseTable { +public: + vector>>> sparseTable; + vector log; + int n; + + SparseTable(vector>& grid) { + n = grid.size(); + log.resize(n + 1, 0); + for (int i = 2; i <= n; i++) { + log[i] = log[i / 2] + 1; + } + + int maxLog = log[n]; + sparseTable.resize(n, vector>>(n, vector>(maxLog + 1, vector(maxLog + 1)))); + + for (int r = 0; r < n; r++) { + for (int c = 0; c < n; c++) { + sparseTable[r][c][0][0] = grid[r][c]; + } + } + + for (int i = 0; i <= maxLog; i++) { + for (int j = 0; j <= maxLog; j++) { + for (int r = 0; r + (1 << i) <= n; r++) { + for (int c = 0; c + (1 << j) <= n; c++) { + if (i == 0 && j == 0) continue; + if (i == 0) { + sparseTable[r][c][i][j] = max( + sparseTable[r][c][i][j - 1], + sparseTable[r][c + (1 << (j - 1))][i][j - 1] + ); + } else if (j == 0) { + sparseTable[r][c][i][j] = max( + sparseTable[r][c][i - 1][j], + sparseTable[r + (1 << (i - 1))][c][i - 1][j] + ); + } else { + sparseTable[r][c][i][j] = max( + max(sparseTable[r][c][i - 1][j - 1], sparseTable[r + (1 << (i - 1))][c][i - 1][j - 1]), + max(sparseTable[r][c + (1 << (j - 1))][i - 1][j - 1], + sparseTable[r + (1 << (i - 1))][c + (1 << (j - 1))][i - 1][j - 1]) + ); + } + } + } + } + } + } + + int query(int x1, int y1, int x2, int y2) { + int lx = log[x2 - x1 + 1]; + int ly = log[y2 - y1 + 1]; + return max( + max(sparseTable[x1][y1][lx][ly], sparseTable[x2 - (1 << lx) + 1][y1][lx][ly]), + max(sparseTable[x1][y2 - (1 << ly) + 1][lx][ly], + sparseTable[x2 - (1 << lx) + 1][y2 - (1 << ly) + 1][lx][ly]) + ); + } +}; + +class Solution { +public: + vector> largestLocal(vector>& grid) { + int n = grid.size(), k = 3; + SparseTable st(grid); + vector> res(n - k + 1, vector(n - k + 1)); + + for (int i = 0; i <= n - k; i++) { + for (int j = 0; j <= n - k; j++) { + res[i][j] = st.query(i, j, i + k - 1, j + k - 1); + } + } + + return res; + } +}; +``` + +```javascript +class SparseTable { + /** + * @constructor + * @param {number[][]} grid + */ + constructor(grid) { + this.n = grid.length; + this.log = Array(this.n + 1).fill(0); + for (let i = 2; i <= this.n; i++) { + this.log[i] = this.log[Math.floor(i / 2)] + 1; + } + + const maxLog = this.log[this.n]; + this.sparseTable = Array.from({ length: this.n }, () => + Array.from({ length: this.n }, () => + Array.from({ length: maxLog + 1 }, () => + Array(maxLog + 1).fill(0) + ) + ) + ); + + for (let r = 0; r < this.n; r++) { + for (let c = 0; c < this.n; c++) { + this.sparseTable[r][c][0][0] = grid[r][c]; + } + } + + for (let i = 0; i <= maxLog; i++) { + for (let j = 0; j <= maxLog; j++) { + for (let r = 0; r + (1 << i) <= this.n; r++) { + for (let c = 0; c + (1 << j) <= this.n; c++) { + if (i === 0 && j === 0) continue; + if (i === 0) { + this.sparseTable[r][c][i][j] = Math.max( + this.sparseTable[r][c][i][j - 1], + this.sparseTable[r][c + (1 << (j - 1))][i][j - 1] + ); + } else if (j === 0) { + this.sparseTable[r][c][i][j] = Math.max( + this.sparseTable[r][c][i - 1][j], + this.sparseTable[r + (1 << (i - 1))][c][i - 1][j] + ); + } else { + this.sparseTable[r][c][i][j] = Math.max( + Math.max( + this.sparseTable[r][c][i - 1][j - 1], + this.sparseTable[r + (1 << (i - 1))][c][i - 1][j - 1] + ), + Math.max( + this.sparseTable[r][c + (1 << (j - 1))][i - 1][j - 1], + this.sparseTable[r + (1 << (i - 1))][c + (1 << (j - 1))][i - 1][j - 1] + ) + ); + } + } + } + } + } + } + + /** + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @return {number} + */ + query(x1, y1, x2, y2) { + const lx = this.log[x2 - x1 + 1]; + const ly = this.log[y2 - y1 + 1]; + return Math.max( + Math.max( + this.sparseTable[x1][y1][lx][ly], + this.sparseTable[x2 - (1 << lx) + 1][y1][lx][ly] + ), + Math.max( + this.sparseTable[x1][y2 - (1 << ly) + 1][lx][ly], + this.sparseTable[x2 - (1 << lx) + 1][y2 - (1 << ly) + 1][lx][ly] + ) + ); + } +} + +class Solution { + /** + * @param {number[][]} grid + * @return {number[][]} + */ + largestLocal(grid) { + const n = grid.length, k = 3; + const st = new SparseTable(grid); + const res = Array.from({ length: n - k + 1 }, () => + Array(n - k + 1).fill(0) + ); + + for (let i = 0; i <= n - k; i++) { + for (let j = 0; j <= n - k; j++) { + res[i][j] = st.query(i, j, i + k - 1, j + k - 1); + } + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 2 \log ^ 2 n)$ +* Space complexity: + * $O(n ^ 2 \log ^ 2 n)$ extra space. + * $O((n - k) ^ 2)$ for the output matrix. + +> Where $n$ is the size of the given square grid and $k$ is the fixed size of the submatrix window. \ No newline at end of file diff --git a/articles/largest-odd-number-in-string.md b/articles/largest-odd-number-in-string.md new file mode 100644 index 000000000..566fb7c11 --- /dev/null +++ b/articles/largest-odd-number-in-string.md @@ -0,0 +1,166 @@ +## 1. Brute Force + +::tabs-start + +```python +class Solution: + def largestOddNumber(self, num: str) -> str: + res = "" + for i in range(len(num)): + for j in range(i, len(num)): + ones_digit = ord(num[j]) - ord('0') + if ones_digit & 1: + cur = num[i:j + 1] + if len(res) < len(cur) or (len(cur) == len(res) and res < cur): + res = cur + return res +``` + +```java +public class Solution { + public String largestOddNumber(String num) { + String res = ""; + int n = num.length(); + + for (int i = 0; i < n; i++) { + for (int j = i; j < n; j++) { + int onesDigit = num.charAt(j) - '0'; + if ((onesDigit & 1) == 1) { + String cur = num.substring(i, j + 1); + if (res.length() < cur.length() || + (res.length() == cur.length() && res.compareTo(cur) < 0)) { + res = cur; + } + } + } + } + return res; + } +} +``` + +```cpp +class Solution { +public: + string largestOddNumber(string num) { + string res = ""; + int n = num.size(); + + for (int i = 0; i < n; i++) { + for (int j = i; j < n; j++) { + int onesDigit = num[j] - '0'; + if (onesDigit & 1) { + string cur = num.substr(i, j - i + 1); + if (res.size() < cur.size() || + (res.size() == cur.size() && res < cur)) { + res = cur; + } + } + } + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} num + * @return {string} + */ + largestOddNumber(num) { + let res = ""; + const n = num.length; + + for (let i = 0; i < n; i++) { + for (let j = i; j < n; j++) { + const onesDigit = num[j].charCodeAt(0) - '0'.charCodeAt(0); + if (onesDigit & 1) { + const cur = num.slice(i, j + 1); + if (res.length < cur.length || + (res.length === cur.length && res < cur)) { + res = cur; + } + } + } + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 3)$ +* Space complexity: $O(n)$ + +--- + +## 2. Find The Rightmost Odd Digit + +::tabs-start + +```python +class Solution: + def largestOddNumber(self, num: str) -> str: + for i in range(len(num) - 1, -1, -1): + if int(num[i]) % 2: + return num[:i + 1] + return "" +``` + +```java +public class Solution { + public String largestOddNumber(String num) { + for (int i = num.length() - 1; i >= 0; i--) { + if ((num.charAt(i) - '0') % 2 == 1) { + return num.substring(0, i + 1); + } + } + return ""; + } +} +``` + +```cpp +class Solution { +public: + string largestOddNumber(string num) { + for (int i = num.size() - 1; i >= 0; i--) { + if ((num[i] - '0') % 2 == 1) { + return num.substr(0, i + 1); + } + } + return ""; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} num + * @return {string} + */ + largestOddNumber(num) { + for (let i = num.length - 1; i >= 0; i--) { + if (parseInt(num[i]) % 2 === 1) { + return num.slice(0, i + 1); + } + } + return ""; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: + * $O(1)$ extra space. + * $O(n)$ for the output string. \ No newline at end of file diff --git a/articles/matrix-diagonal-sum.md b/articles/matrix-diagonal-sum.md new file mode 100644 index 000000000..8524ff1a7 --- /dev/null +++ b/articles/matrix-diagonal-sum.md @@ -0,0 +1,184 @@ +## 1. Iteration + +::tabs-start + +```python +class Solution: + def diagonalSum(self, mat: List[List[int]]) -> int: + n = len(mat) + + def helper(matrix): + res = 0 + for i in range(n): + for j in range(n): + if i == j: + res += matrix[i][j] + matrix[i].reverse() + return res + + return helper(mat) + helper(mat) - (mat[n // 2][n // 2] if n & 1 else 0) +``` + +```java +public class Solution { + public int diagonalSum(int[][] mat) { + int n = mat.length; + return helper(mat) + helper(mat) - (n % 2 == 1 ? mat[n / 2][n / 2] : 0); + } + + int helper(int[][] matrix) { + int res = 0, n = matrix.length; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i == j) { + res += matrix[i][j]; + } + } + reverse(matrix[i]); + } + return res; + } + + void reverse(int[] row) { + int left = 0, right = row.length - 1; + while (left < right) { + int temp = row[left]; + row[left++] = row[right]; + row[right--] = temp; + } + } +} +``` + +```cpp +class Solution { +public: + int diagonalSum(vector>& mat) { + int n = mat.size(); + return helper(mat) + helper(mat) - (n % 2 == 1 ? mat[n / 2][n / 2] : 0); + } + +private: + int helper(vector>& matrix) { + int res = 0, n = matrix.size(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i == j) { + res += matrix[i][j]; + } + } + reverse(matrix[i].begin(), matrix[i].end()); + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} mat + * @return {number} + */ + diagonalSum(mat) { + const n = mat.length; + + const helper = (matrix) => { + let res = 0; + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (i === j) { + res += matrix[i][j]; + } + } + matrix[i].reverse(); + } + return res; + }; + + return helper(mat) + helper(mat) - (n % 2 === 1 ? mat[Math.floor(n / 2)][Math.floor(n / 2)] : 0); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 2)$ +* Space complexity: $O(1)$ extra space. + +--- + +## 2. Iteration (Optimal) + +::tabs-start + +```python +class Solution: + def diagonalSum(self, mat: List[List[int]]) -> int: + res, n = 0, len(mat) + + for r in range(n): + res += mat[r][r] + res += mat[r][n - r - 1] + + return res - (mat[n // 2][n // 2] if n & 1 else 0) +``` + +```java +public class Solution { + public int diagonalSum(int[][] mat) { + int res = 0, n = mat.length; + + for (int r = 0; r < n; r++) { + res += mat[r][r]; + res += mat[r][n - r - 1]; + } + + return res - (n % 2 == 1 ? mat[n / 2][n / 2] : 0); + } +} +``` + +```cpp +class Solution { +public: + int diagonalSum(vector>& mat) { + int res = 0, n = mat.size(); + + for (int r = 0; r < n; r++) { + res += mat[r][r]; + res += mat[r][n - r - 1]; + } + + return res - (n % 2 == 1 ? mat[n / 2][n / 2] : 0); + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} mat + * @return {number} + */ + diagonalSum(mat) { + let res = 0, n = mat.length; + + for (let r = 0; r < n; r++) { + res += mat[r][r]; + res += mat[r][n - r - 1]; + } + + return res - (n % 2 == 1 ? mat[Math.floor(n / 2)][Math.floor(n / 2)] : 0); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ extra space. \ No newline at end of file diff --git a/articles/max-points-on-a-line.md b/articles/max-points-on-a-line.md new file mode 100644 index 000000000..8c87a3369 --- /dev/null +++ b/articles/max-points-on-a-line.md @@ -0,0 +1,384 @@ +## 1. Math + +::tabs-start + +```python +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + n = len(points) + if n <= 2: + return n + + def get_slope(p1, p2): + if p1[0] == p2[0]: + return float("inf") + return (p2[1] - p1[1]) / (p2[0] - p1[0]) + + res = 1 + for i in range(n): + for j in range(i + 1, n): + slope = get_slope(points[i], points[j]) + cnt = 2 + for k in range(j + 1, n): + if slope == get_slope(points[i], points[k]): + cnt += 1 + res = max(res, cnt) + + return res +``` + +```java +public class Solution { + public int maxPoints(int[][] points) { + int n = points.length; + if (n <= 2) { + return n; + } + + int res = 1; + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + double slope = getSlope(points[i], points[j]); + int cnt = 2; + for (int k = j + 1; k < n; k++) { + if (slope == getSlope(points[i], points[k])) { + cnt++; + } + } + res = Math.max(res, cnt); + } + } + + return res; + } + + private double getSlope(int[] p1, int[] p2) { + if (p1[0] == p2[0]) { + return Double.POSITIVE_INFINITY; + } + return (double) (p2[1] - p1[1]) / (p2[0] - p1[0]); + } +} +``` + +```cpp +class Solution { +public: + int maxPoints(vector>& points) { + int n = points.size(); + if (n <= 2) { + return n; + } + + int res = 1; + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + double slope = getSlope(points[i], points[j]); + int cnt = 2; + for (int k = j + 1; k < n; k++) { + if (slope == getSlope(points[i], points[k])) { + cnt++; + } + } + res = max(res, cnt); + } + } + + return res; + } + +private: + double getSlope(vector& p1, vector& p2) { + if (p1[0] == p2[0]) { + return INFINITY; + } + return (double)(p2[1] - p1[1]) / (p2[0] - p1[0]); + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} points + * @return {number} + */ + maxPoints(points) { + const n = points.length; + if (n <= 2) { + return n; + } + + let res = 1; + const getSlope = (p1, p2) => { + if (p1[0] === p2[0]) { + return Infinity; + } + return (p2[1] - p1[1]) / (p2[0] - p1[0]); + }; + + for (let i = 0; i < n; i++) { + for (let j = i + 1; j < n; j++) { + const slope = getSlope(points[i], points[j]); + let cnt = 2; + for (let k = j + 1; k < n; k++) { + if (slope === getSlope(points[i], points[k])) { + cnt++; + } + } + res = Math.max(res, cnt); + } + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 3)$ +* Space complexity: $O(1)$ extra space. + +--- + +## 2. Math + Hash Map + +::tabs-start + +```python +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + res = 1 + for i in range(len(points)): + p1 = points[i] + count = defaultdict(int) + for j in range(i + 1, len(points)): + p2 = points[j] + if p2[0] == p1[0]: + slope = float("inf") + else: + slope = (p2[1] - p1[1]) / (p2[0] - p1[0]) + count[slope] += 1 + res = max(res, count[slope] + 1) + return res +``` + +```java +public class Solution { + public int maxPoints(int[][] points) { + int res = 1; + for (int i = 0; i < points.length; i++) { + Map count = new HashMap<>(); + for (int j = i + 1; j < points.length; j++) { + double slope = getSlope(points[i], points[j]); + if (slope == -0.0) slope = 0.0; + + count.put(slope, count.getOrDefault(slope, 0) + 1); + res = Math.max(res, count.get(slope) + 1); + } + } + return res; + } + + private double getSlope(int[] p1, int[] p2) { + if (p1[0] == p2[0]) { + return Double.POSITIVE_INFINITY; + } + return (double) (p2[1] - p1[1]) / (p2[0] - p1[0]); + } +} +``` + +```cpp +class Solution { +public: + int maxPoints(vector>& points) { + int res = 1; + for (int i = 0; i < points.size(); i++) { + vector& p1 = points[i]; + unordered_map count; + for (int j = i + 1; j < points.size(); j++) { + vector& p2 = points[j]; + double slope = (p2[0] == p1[0]) ? INFINITY : + (double)(p2[1] - p1[1]) / (p2[0] - p1[0]); + count[slope]++; + res = max(res, count[slope] + 1); + } + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} points + * @return {number} + */ + maxPoints(points) { + let res = 1; + for (let i = 0; i < points.length; i++) { + const p1 = points[i]; + const count = new Map(); + for (let j = i + 1; j < points.length; j++) { + const p2 = points[j]; + const slope = (p2[0] === p1[0]) ? Infinity : + (p2[1] - p1[1]) / (p2[0] - p1[0]); + count.set(slope, (count.get(slope) || 0) + 1); + res = Math.max(res, count.get(slope) + 1); + } + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 2)$ +* Space complexity: $O(n)$ + +--- + +## 3. Math + Hash Map (Optimal) + +::tabs-start + +```python +class Solution: + def maxPoints(self, points: List[List[int]]) -> int: + if len(points) <= 2: + return len(points) + + def gcd(a, b): + return gcd(b, a % b) if b else a + + res = 1 + for i in range(len(points) - 1): + count = defaultdict(int) + for j in range(i + 1, len(points)): + dx = points[j][0] - points[i][0] + dy = points[j][1] - points[i][1] + g = gcd(dx, dy) + dx //= g + dy //= g + slope = (dx, dy) + count[slope] += 1 + res = max(res, max(count.values()) + 1) + return res +``` + +```java +public class Solution { + public int maxPoints(int[][] points) { + if (points.length <= 2) { + return points.length; + } + + int res = 1; + for (int i = 0; i < points.length - 1; i++) { + Map count = new HashMap<>(); + for (int j = i + 1; j < points.length; j++) { + int dx = points[j][0] - points[i][0]; + int dy = points[j][1] - points[i][1]; + int g = gcd(dx, dy); + dx /= g; + dy /= g; + String slope = dx + ":" + dy; + count.put(slope, count.getOrDefault(slope, 0) + 1); + } + for (int val : count.values()) { + res = Math.max(res, val + 1); + } + } + return res; + } + + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +} +``` + +```cpp +class Solution { +public: + int maxPoints(vector>& points) { + if (points.size() <= 2) { + return points.size(); + } + + int res = 1; + for (int i = 0; i < points.size() - 1; i++) { + unordered_map count; + for (int j = i + 1; j < points.size(); j++) { + int dx = points[j][0] - points[i][0]; + int dy = points[j][1] - points[i][1]; + int g = gcd(dx, dy); + dx /= g; + dy /= g; + string slope = to_string(dx) + ":" + to_string(dy); + count[slope]++; + } + for (const auto& [slope, freq] : count) { + res = max(res, freq + 1); + } + } + return res; + } + +private: + int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} points + * @return {number} + */ + maxPoints(points) { + if (points.length <= 2) { + return points.length; + } + + const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b)); + + let res = 1; + for (let i = 0; i < points.length - 1; i++) { + const count = new Map(); + for (let j = i + 1; j < points.length; j++) { + let dx = points[j][0] - points[i][0]; + let dy = points[j][1] - points[i][1]; + const g = gcd(dx, dy); + dx /= g; + dy /= g; + const slope = `${dx}:${dy}`; + count.set(slope, (count.get(slope) || 0) + 1); + } + for (const freq of count.values()) { + res = Math.max(res, freq + 1); + } + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 2 \log m)$ +* Space complexity: $O(n)$ + +> Where $n$ is the number of points and $m$ is the maximum value in the points. \ No newline at end of file diff --git a/articles/palindrome-number.md b/articles/palindrome-number.md new file mode 100644 index 000000000..77f44aad6 --- /dev/null +++ b/articles/palindrome-number.md @@ -0,0 +1,420 @@ +## 1. Convert to String + +::tabs-start + +```python +class Solution: + def isPalindrome(self, x: int) -> bool: + s = str(x) + return s == s[::-1] +``` + +```java +public class Solution { + public boolean isPalindrome(int x) { + String s = String.valueOf(x); + return s.equals(new StringBuilder(s).reverse().toString()); + } +} +``` + +```cpp +class Solution { +public: + bool isPalindrome(int x) { + string s = to_string(x); + string rev = s; + reverse(rev.begin(), rev.end()); + return s == rev; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} x + * @return {boolean} + */ + isPalindrome(x) { + const s = String(x); + return s === s.split('').reverse().join(''); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ + +> Where $n$ is the number of digits in the given integer. + +--- + +## 2. Convert to String (Optimal) + +::tabs-start + +```python +class Solution: + def isPalindrome(self, x: int) -> bool: + s = str(x) + n = len(s) + for i in range(n // 2): + if s[i] != s[n - i - 1]: + return False + return True +``` + +```java +public class Solution { + public boolean isPalindrome(int x) { + String s = String.valueOf(x); + int n = s.length(); + for (int i = 0; i < n / 2; i++) { + if (s.charAt(i) != s.charAt(n - i - 1)) { + return false; + } + } + return true; + } +} +``` + +```cpp +class Solution { +public: + bool isPalindrome(int x) { + string s = to_string(x); + int n = s.length(); + for (int i = 0; i < n / 2; i++) { + if (s[i] != s[n - i - 1]) { + return false; + } + } + return true; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} x + * @return {boolean} + */ + isPalindrome(x) { + const s = String(x); + let n = s.length; + for (let i = 0; i < (n >> 1); i++) { + if (s.charAt(i) != s.charAt(n - i - 1)) { + return false; + } + } + return true; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ + +> Where $n$ is the number of digits in the given integer. + +--- + +## 3. Reverse the Integer + +::tabs-start + +```python +class Solution: + def isPalindrome(self, x: int) -> bool: + if x < 0: + return False + + rev = 0 + num = x + while num: + rev = (rev * 10) + (num % 10) + num //= 10 + + return rev == x +``` + +```java +public class Solution { + public boolean isPalindrome(int x) { + if (x < 0) { + return false; + } + + long rev = 0, num = x; + while (num != 0) { + rev = (rev * 10) + (num % 10); + num /= 10; + } + + return rev == x; + } +} +``` + +```cpp +class Solution { +public: + bool isPalindrome(int x) { + if (x < 0) { + return false; + } + + long long rev = 0, num = x; + while (num != 0) { + rev = (rev * 10) + (num % 10); + num /= 10; + } + + return rev == x; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} x + * @return {boolean} + */ + isPalindrome(x) { + if (x < 0) { + return false; + } + + let rev = 0, num = x; + while (num !== 0) { + rev = (rev * 10) + (num % 10); + num = Math.floor(num / 10); + } + + return rev === x; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ + +> Where $n$ is the number of digits in the given integer. + +--- + +## 4. Two Pointers + +::tabs-start + +```python +class Solution: + def isPalindrome(self, x: int) -> bool: + if x < 0: + return False + + div = 1 + while x >= 10 * div: + div *= 10 + + while x: + if x // div != x % 10: + return False + x = (x % div) // 10 + div //= 100 + + return True +``` + +```java +public class Solution { + public boolean isPalindrome(int x) { + if (x < 0) { + return false; + } + + long div = 1; + while (x >= 10 * div) { + div *= 10; + } + + while (x != 0) { + if (x / div != x % 10) { + return false; + } + x = (int) (x % div) / 10; + div /= 100; + } + + return true; + } +} +``` + +```cpp +class Solution { +public: + bool isPalindrome(int x) { + if (x < 0) { + return false; + } + + long long div = 1; + while (x >= 10 * div) { + div *= 10; + } + + while (x != 0) { + if (x / div != x % 10) { + return false; + } + x = (x % div) / 10; + div /= 100; + } + + return true; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} x + * @return {boolean} + */ + isPalindrome(x) { + if (x < 0) { + return false; + } + + let div = 1; + while (x >= 10 * div) { + div *= 10; + } + + while (x !== 0) { + if (Math.floor(x / div) !== x % 10) { + return false; + } + x = Math.floor((x % div) / 10); + div = Math.floor(div / 100); + } + + return true; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ + +> Where $n$ is the number of digits in the given integer. + +--- + +## 5. Reverse Half of the Number + +::tabs-start + +```python +class Solution: + def isPalindrome(self, x: int) -> bool: + if x < 0 or (x != 0 and x % 10 == 0): + return False + + rev = 0 + while x > rev: + rev = (rev * 10) + (x % 10) + x //= 10 + + return x == rev or x == rev // 10 +``` + +```java +public class Solution { + public boolean isPalindrome(int x) { + if (x < 0 || (x != 0 && x % 10 == 0)) { + return false; + } + + int rev = 0; + while (x > rev) { + rev = rev * 10 + x % 10; + x /= 10; + } + + return x == rev || x == rev / 10; + } +} +``` + +```cpp +class Solution { +public: + bool isPalindrome(int x) { + if (x < 0 || (x != 0 && x % 10 == 0)) { + return false; + } + + int rev = 0; + while (x > rev) { + rev = rev * 10 + x % 10; + x /= 10; + } + + return x == rev || x == rev / 10; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} x + * @return {boolean} + */ + isPalindrome(x) { + if (x < 0 || (x !== 0 && x % 10 === 0)) { + return false; + } + + let rev = 0; + while (x > rev) { + rev = rev * 10 + (x % 10); + x = Math.floor(x / 10); + } + + return x === rev || x === Math.floor(rev / 10); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ + +> Where $n$ is the number of digits in the given integer. \ No newline at end of file diff --git a/articles/power-of-four.md b/articles/power-of-four.md new file mode 100644 index 000000000..dc54669cc --- /dev/null +++ b/articles/power-of-four.md @@ -0,0 +1,367 @@ +## 1. Recursion + +::tabs-start + +```python +class Solution: + def isPowerOfFour(self, n: int) -> bool: + if n == 1: + return True + if n <= 0 or n % 4: + return False + return self.isPowerOfFour(n // 4) +``` + +```java +public class Solution { + public boolean isPowerOfFour(int n) { + if (n == 1) { + return true; + } + if (n <= 0 || n % 4 != 0) { + return false; + } + return isPowerOfFour(n / 4); + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfFour(int n) { + if (n == 1) { + return true; + } + if (n <= 0 || n % 4 != 0) { + return false; + } + return isPowerOfFour(n / 4); + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isPowerOfFour(n) { + if (n === 1) { + return true; + } + if (n <= 0 || n % 4 !== 0) { + return false; + } + return this.isPowerOfFour(Math.floor(n / 4)); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ + +--- + +## 2. Iteration + +::tabs-start + +```python +class Solution: + def isPowerOfFour(self, n: int) -> bool: + if n < 0: + return False + + while n > 1: + if n % 4: + return False + n //= 4 + + return n == 1 +``` + +```java +public class Solution { + public boolean isPowerOfFour(int n) { + if (n < 0) return false; + + while (n > 1) { + if (n % 4 != 0) return false; + n /= 4; + } + + return n == 1; + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfFour(int n) { + if (n < 0) return false; + + while (n > 1) { + if (n % 4 != 0) return false; + n /= 4; + } + + return n == 1; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isPowerOfFour(n) { + if (n < 0) return false; + + while (n > 1) { + if (n % 4 !== 0) return false; + n = Math.floor(n / 4); + } + + return n === 1; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ + +--- + +## 3. Math + +::tabs-start + +```python +class Solution: + def isPowerOfFour(self, n: int) -> bool: + return n > 0 and log(n, 4) % 1 == 0 +``` + +```java +public class Solution { + public boolean isPowerOfFour(int n) { + return n > 0 && Math.log(n) / Math.log(4) % 1 == 0; + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfFour(int n) { + return n > 0 && fmod(log(n) / log(4), 1) == 0; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isPowerOfFour(n) { + return n > 0 && (Math.log(n) / Math.log(4)) % 1 === 0; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ + +--- + +## 4. Bit Manipulation + +::tabs-start + +```python +class Solution: + def isPowerOfFour(self, n: int) -> bool: + if n < 0: + return False + + for i in range(0, 32, 2): + if n == (1 << i): + return True + + return False +``` + +```java +public class Solution { + public boolean isPowerOfFour(int n) { + if (n < 0) return false; + + for (int i = 0; i < 32; i += 2) { + if (n == (1 << i)) { + return true; + } + } + + return false; + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfFour(int n) { + if (n < 0) return false; + + for (int i = 0; i < 32; i += 2) { + if (n == (1 << i)) { + return true; + } + } + + return false; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isPowerOfFour(n) { + if (n < 0) return false; + + for (let i = 0; i < 32; i += 2) { + if (n === (1 << i)) { + return true; + } + } + + return false; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ + +--- + +## 5. Bit Mask - I + +::tabs-start + +```python +class Solution: + def isPowerOfFour(self, n: int) -> bool: + return n > 0 and (n & (n - 1)) == 0 and (n & 0x55555555) == n +``` + +```java +public class Solution { + public boolean isPowerOfFour(int n) { + return n > 0 && (n & (n - 1)) == 0 && (n & 0x55555555) == n; + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfFour(int n) { + return n > 0 && (n & (n - 1)) == 0 && (n & 0x55555555) == n; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isPowerOfFour(n) { + return n > 0 && (n & (n - 1)) === 0 && (n & 0x55555555) === n; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ + +--- + +## 6. Bit Mask - II + +::tabs-start + +```python +class Solution: + def isPowerOfFour(self, n: int) -> bool: + return n > 0 and (n & (n - 1)) == 0 and (n % 3 == 1) +``` + +```java +public class Solution { + public boolean isPowerOfFour(int n) { + return n > 0 && (n & (n - 1)) == 0 && (n % 3 == 1); + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfFour(int n) { + return n > 0 && (n & (n - 1)) == 0 && (n % 3 == 1); + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isPowerOfFour(n) { + return n > 0 && (n & (n - 1)) === 0 && (n % 3 == 1); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ \ No newline at end of file diff --git a/articles/power-of-two.md b/articles/power-of-two.md new file mode 100644 index 000000000..5024ea27a --- /dev/null +++ b/articles/power-of-two.md @@ -0,0 +1,351 @@ +## 1. Brute Force + +::tabs-start + +```python +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + if n <= 0: + return False + + x = 1 + while x < n: + x *= 2 + return x == n +``` + +```java +public class Solution { + public boolean isPowerOfTwo(int n) { + if (n <= 0) return false; + + long x = 1; + while (x < n) { + x *= 2; + } + return x == n; + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfTwo(int n) { + if (n <= 0) return false; + + long long x = 1; + while (x < n) { + x *= 2; + } + return x == n; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isPowerOfTwo(n) { + if (n <= 0) return false; + + let x = 1; + while (x < n) { + x *= 2; + } + return x === n; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(\log n)$ +* Space complexity: $O(1)$ + +--- + +## 2. Recursion + +::tabs-start + +```python +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + if n == 1: + return True + if n <= 0 or n % 2 == 1: + return False + return self.isPowerOfTwo(n // 2) +``` + +```java +public class Solution { + public boolean isPowerOfTwo(int n) { + if (n == 1) { + return true; + } + if (n <= 0 || n % 2 == 1) { + return false; + } + return isPowerOfTwo(n / 2); + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfTwo(int n) { + if (n == 1) { + return true; + } + if (n <= 0 || n % 2 == 1) { + return false; + } + return isPowerOfTwo(n / 2); + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isPowerOfTwo(n) { + if (n === 1) { + return true; + } + if (n <= 0 || n % 2 === 1) { + return false; + } + return this.isPowerOfTwo(Math.floor(n / 2)); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(\log n)$ +* Space complexity: $O(\log n)$ for recursion stack. + +--- + +## 3. Iteration + +::tabs-start + +```python +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + if n <= 0: + return False + + while n % 2 == 0: + n >>= 1 + return n == 1 +``` + +```java +public class Solution { + public boolean isPowerOfTwo(int n) { + if (n <= 0) return false; + + while (n % 2 == 0) { + n >>= 1; + } + return n == 1; + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfTwo(int n) { + if (n <= 0) return false; + + while (n % 2 == 0) { + n >>= 1; + } + return n == 1; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isPowerOfTwo(n) { + if (n <= 0) return 0; + + while (n % 2 === 0) { + n >>= 1; + } + return n === 1; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(\log n)$ +* Space complexity: $O(1)$ + +--- + +## 4. Bit Manipulation - I + +::tabs-start + +```python +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + return n > 0 and (n & (-n)) == n +``` + +```java +public class Solution { + public boolean isPowerOfTwo(int n) { + return n > 0 && (n & (-n)) == n; + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfTwo(int n) { + return n > 0 && (n & (-n)) == n; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isPowerOfTwo(n) { + return n > 0 && (n & (-n)) === n; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ + +--- + +## 5. Bit Manipulation - II + +::tabs-start + +```python +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + return n > 0 and (n & (n - 1)) == 0 +``` + +```java +public class Solution { + public boolean isPowerOfTwo(int n) { + return n > 0 && (n & (n - 1)) == 0; + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfTwo(int n) { + return n > 0 && (n & (n - 1)) == 0; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isPowerOfTwo(n) { + return n > 0 && (n & (n - 1)) === 0; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ + +--- + +## 6. Math + +::tabs-start + +```python +class Solution: + def isPowerOfTwo(self, n: int) -> bool: + return n > 0 and ((1 << 30) % n) == 0 +``` + +```java +public class Solution { + public boolean isPowerOfTwo(int n) { + return n > 0 && ((1 << 30) % n) == 0; + } +} +``` + +```cpp +class Solution { +public: + bool isPowerOfTwo(int n) { + return n > 0 && ((1 << 30) % n) == 0; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isPowerOfTwo(n) { + return n > 0 && ((1 << 30) % n) === 0; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(1)$ +* Space complexity: $O(1)$ \ No newline at end of file diff --git a/articles/shift-2d-grid.md b/articles/shift-2d-grid.md new file mode 100644 index 000000000..78f570a31 --- /dev/null +++ b/articles/shift-2d-grid.md @@ -0,0 +1,502 @@ +## 1. Simulation (Extra Space) + +::tabs-start + +```python +class Solution: + def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + m, n = len(grid), len(grid[0]) + + while k: + cur = [[0] * n for _ in range(m)] + + for r in range(m): + for c in range(n - 1): + cur[r][c + 1] = grid[r][c] + + for r in range(m): + cur[(r + 1) % m][0] = grid[r][n - 1] + + grid = cur + k -= 1 + + return grid +``` + +```java +public class Solution { + public List> shiftGrid(int[][] grid, int k) { + int m = grid.length, n = grid[0].length; + + while (k > 0) { + int[][] cur = new int[m][n]; + + for (int r = 0; r < m; r++) { + for (int c = 0; c < n - 1; c++) { + cur[r][c + 1] = grid[r][c]; + } + } + + for (int r = 0; r < m; r++) { + cur[(r + 1) % m][0] = grid[r][n - 1]; + } + + grid = cur; + k--; + } + + List> res = new ArrayList<>(); + for (int r = 0; r < m; r++) { + List tmp = new ArrayList<>(); + for (int c = 0; c < n; c++) { + tmp.add(grid[r][c]); + } + res.add(tmp); + } + return res; + } +} +``` + +```cpp +class Solution { +public: + vector> shiftGrid(vector>& grid, int k) { + int m = grid.size(), n = grid[0].size(); + + while (k > 0) { + vector> cur(m, vector(n, 0)); + + for (int r = 0; r < m; r++) { + for (int c = 0; c < n - 1; c++) { + cur[r][c + 1] = grid[r][c]; + } + } + + for (int r = 0; r < m; r++) { + cur[(r + 1) % m][0] = grid[r][n - 1]; + } + + grid = cur; + k--; + } + + return grid; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} grid + * @param {number} k + * @return {number[][]} + */ + shiftGrid(grid, k) { + const m = grid.length, n = grid[0].length; + + while (k > 0) { + const cur = Array.from({ length: m }, () => Array(n).fill(0)); + + for (let r = 0; r < m; r++) { + for (let c = 0; c < n - 1; c++) { + cur[r][c + 1] = grid[r][c]; + } + } + + for (let r = 0; r < m; r++) { + cur[(r + 1) % m][0] = grid[r][n - 1]; + } + + grid = cur; + k--; + } + + return grid; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(k * m * n)$ +* Space complexity: $O(m * n)$ + +> Where $m$ is the number of rows in the grid, $n$ is the number of columns in the grid, and $k$ is the shift count. + +--- + +## 2. Simulation + +::tabs-start + +```python +class Solution: + def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + m, n = len(grid), len(grid[0]) + + while k: + prev = grid[m - 1][n - 1] + for r in range(m): + for c in range(n): + grid[r][c], prev = prev, grid[r][c] + k -= 1 + + return grid +``` + +```java +public class Solution { + public List> shiftGrid(int[][] grid, int k) { + int m = grid.length, n = grid[0].length; + + while (k > 0) { + int prev = grid[m - 1][n - 1]; + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + int temp = grid[r][c]; + grid[r][c] = prev; + prev = temp; + } + } + k--; + } + + List> res = new ArrayList<>(); + for (int r = 0; r < m; r++) { + List tmp = new ArrayList<>(); + for (int c = 0; c < n; c++) { + tmp.add(grid[r][c]); + } + res.add(tmp); + } + return res; + } +} +``` + +```cpp +class Solution { +public: + vector> shiftGrid(vector>& grid, int k) { + int m = grid.size(), n = grid[0].size(); + + while (k > 0) { + int prev = grid[m - 1][n - 1]; + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + swap(grid[r][c], prev); + } + } + k--; + } + + return grid; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} grid + * @param {number} k + * @return {number[][]} + */ + shiftGrid(grid, k) { + const m = grid.length, n = grid[0].length; + + while (k > 0) { + let prev = grid[m - 1][n - 1]; + for (let r = 0; r < m; r++) { + for (let c = 0; c < n; c++) { + [prev, grid[r][c]] = [grid[r][c], prev]; + } + } + k--; + } + + return grid; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(k * m * n)$ +* Space complexity: $O(m * n)$ for the output matrix. + +> Where $m$ is the number of rows in the grid, $n$ is the number of columns in the grid, and $k$ is the shift count. + +--- + +## 3. Convert to One Dimensional Array + +::tabs-start + +```python +class Solution: + def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + m, n = len(grid), len(grid[0]) + N = m * n + k %= N + + arr = [0] * N + for r in range(m): + for c in range(n): + arr[r * n + c] = grid[r][c] + + def reverse(l, r): + while l < r: + arr[l], arr[r] = arr[r], arr[l] + l += 1 + r -= 1 + + reverse(0, N - 1) + reverse(0, k - 1) + reverse(k, N - 1) + + for r in range(m): + for c in range(n): + grid[r][c] = arr[r * n + c] + + return grid +``` + +```java +public class Solution { + public List> shiftGrid(int[][] grid, int k) { + int m = grid.length, n = grid[0].length; + int N = m * n; + k %= N; + + int[] arr = new int[N]; + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + arr[r * n + c] = grid[r][c]; + } + } + + reverse(arr, 0, N - 1); + reverse(arr, 0, k - 1); + reverse(arr, k, N - 1); + + List> res = new ArrayList<>(); + for (int r = 0; r < m; r++) { + List tmp = new ArrayList<>(); + for (int c = 0; c < n; c++) { + tmp.add(arr[r * n + c]); + } + res.add(tmp); + } + return res; + } + + private void reverse(int[] arr, int l, int r) { + while (l < r) { + int temp = arr[l]; + arr[l] = arr[r]; + arr[r] = temp; + l++; + r--; + } + } +} +``` + +```cpp +class Solution { +public: + vector> shiftGrid(vector>& grid, int k) { + int m = grid.size(), n = grid[0].size(); + int N = m * n; + k %= N; + + vector arr(N); + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + arr[r * n + c] = grid[r][c]; + } + } + + reverse(arr.begin(), arr.end()); + reverse(arr.begin(), arr.begin() + k); + reverse(arr.begin() + k, arr.end()); + + for (int r = 0; r < m; r++) { + for (int c = 0; c < n; c++) { + grid[r][c] = arr[r * n + c]; + } + } + + return grid; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} grid + * @param {number} k + * @return {number[][]} + */ + shiftGrid(grid, k) { + const m = grid.length, n = grid[0].length; + const N = m * n; + k %= N; + + const arr = new Array(N); + for (let r = 0; r < m; r++) { + for (let c = 0; c < n; c++) { + arr[r * n + c] = grid[r][c]; + } + } + + const reverse = (l, r) => { + while (l < r) { + [arr[l], arr[r]] = [arr[r], arr[l]]; + l++; + r--; + } + }; + + reverse(0, N - 1); + reverse(0, k - 1); + reverse(k, N - 1); + + for (let r = 0; r < m; r++) { + for (let c = 0; c < n; c++) { + grid[r][c] = arr[r * n + c]; + } + } + + return grid; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(m * n)$ +* Space complexity: $O(m * n)$ + +> Where $m$ is the number of rows in the grid and $n$ is the number of columns in the grid. + +--- + +## 4. Iteration + +::tabs-start + +```python +class Solution: + def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + M, N = len(grid), len(grid[0]) + + def posToVal(r, c): + return r * N + c + + def valToPos(v): + return [v // N, v % N] + + res = [[0] * N for _ in range(M)] + for r in range(M): + for c in range(N): + newVal = (posToVal(r, c) + k) % (M * N) + newR, newC = valToPos(newVal) + res[newR][newC] = grid[r][c] + + return res +``` + +```java +public class Solution { + public List> shiftGrid(int[][] grid, int k) { + int M = grid.length, N = grid[0].length; + int[][] arr = new int[M][N]; + + for (int r = 0; r < M; r++) { + for (int c = 0; c < N; c++) { + int newVal = (r * N + c + k) % (M * N); + int newR = newVal / N, newC = newVal % N; + arr[newR][newC] = grid[r][c]; + } + } + + List> res = new ArrayList<>(); + for (int r = 0; r < M; r++) { + List tmp = new ArrayList<>(); + for (int c = 0; c < N; c++) { + tmp.add(arr[r][c]); + } + res.add(tmp); + } + return res; + } + +} +``` + +```cpp +class Solution { +public: + vector> shiftGrid(vector>& grid, int k) { + int M = grid.size(), N = grid[0].size(); + vector> res(M, vector(N)); + + for (int r = 0; r < M; r++) { + for (int c = 0; c < N; c++) { + int newVal = (r * N + c + k) % (M * N); + int newR = newVal / N, newC = newVal % N; + res[newR][newC] = grid[r][c]; + } + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[][]} grid + * @param {number} k + * @return {number[][]} + */ + shiftGrid(grid, k) { + const M = grid.length, N = grid[0].length; + + const posToVal = (r, c) => r * N + c; + const valToPos = (v) => [Math.floor(v / N), v % N]; + + const res = Array.from({ length: M }, () => Array(N).fill(0)); + for (let r = 0; r < M; r++) { + for (let c = 0; c < N; c++) { + const newVal = (posToVal(r, c) + k) % (M * N); + const [newR, newC] = valToPos(newVal); + res[newR][newC] = grid[r][c]; + } + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(m * n)$ +* Space complexity: $O(m * n)$ + +> Where $m$ is the number of rows in the grid and $n$ is the number of columns in the grid. \ No newline at end of file diff --git a/articles/shuffle-the-array.md b/articles/shuffle-the-array.md new file mode 100644 index 000000000..eded033b7 --- /dev/null +++ b/articles/shuffle-the-array.md @@ -0,0 +1,257 @@ +## 1. Iteration (Extra Space) + +::tabs-start + +```python +class Solution: + def shuffle(self, nums: List[int], n: int) -> List[int]: + res = [] + for i in range(n): + res.append(nums[i]) + res.append(nums[i + n]) + return res +``` + +```java +public class Solution { + public int[] shuffle(int[] nums, int n) { + int[] res = new int[2 * n]; + int idx = 0; + for (int i = 0; i < n; i++) { + res[idx++] = nums[i]; + res[idx++] = nums[i + n]; + } + return res; + } +} +``` + +```cpp +class Solution { +public: + vector shuffle(vector& nums, int n) { + vector res; + for (int i = 0; i < n; i++) { + res.push_back(nums[i]); + res.push_back(nums[i + n]); + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @param {number} n + * @return {number[]} + */ + shuffle(nums) { + const res = []; + for (let i = 0; i < n; i++) { + res.push(nums[i]); + res.push(nums[i + n]); + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ extra space. + +--- + +## 2. Multiplication And Modulo + +::tabs-start + +```python +class Solution: + def shuffle(self, nums: List[int], n: int) -> List[int]: + M = max(nums) + 1 + for i in range(2 * n): + if i % 2 == 0: + nums[i] += (nums[i // 2] % M) * M + else: + nums[i] += (nums[n + i // 2] % M) * M + + for i in range(2 * n): + nums[i] //= M + + return nums +``` + +```java +public class Solution { + public int[] shuffle(int[] nums, int n) { + int M = 1001; + for (int i = 0; i < 2 * n; i++) { + if (i % 2 == 0) { + nums[i] += (nums[i / 2] % M) * M; + } else { + nums[i] += (nums[n + i / 2] % M) * M; + } + } + for (int i = 0; i < 2 * n; i++) { + nums[i] /= M; + } + return nums; + } +} +``` + +```cpp +class Solution { +public: + vector shuffle(vector& nums, int n) { + int M = *max_element(nums.begin(), nums.end()) + 1; + for (int i = 0; i < 2 * n; i++) { + if (i % 2 == 0) { + nums[i] += (nums[i / 2] % M) * M; + } else { + nums[i] += (nums[n + i / 2] % M) * M; + } + } + for (int i = 0; i < 2 * n; i++) { + nums[i] /= M; + } + return nums; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @param {number} n + * @return {number[]} + */ + shuffle(nums) { + const M = Math.max(...nums) + 1; + for (let i = 0; i < 2 * n; i++) { + if (i % 2 === 0) { + nums[i] += (nums[i >> 1] % M) * M; + } else { + nums[i] += (nums[n + (i >> 1)] % M) * M; + } + } + for (let i = 0; i < 2 * n; i++) { + nums[i] = Math.floor(nums[i] / M); + } + return nums; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ extra space. + +--- + +## 3. Bit Manipulation + +::tabs-start + +```python +class Solution: + def shuffle(self, nums: List[int], n: int) -> List[int]: + for i in range(n): + nums[i] = (nums[i] << 10) | nums[i + n] # Store x, y in nums[i] + + j = 2 * n - 1 + for i in range(n - 1, -1, -1): + y = nums[i] & ((1 << 10) - 1) + x = nums[i] >> 10 + nums[j] = y + nums[j - 1] = x + j -= 2 + + return nums +``` + +```java +public class Solution { + public int[] shuffle(int[] nums, int n) { + for (int i = 0; i < n; i++) { + nums[i] = (nums[i] << 10) | nums[i + n]; // Store x, y in nums[i] + } + + int j = 2 * n - 1; + for (int i = n - 1; i >= 0; i--) { + int y = nums[i] & ((1 << 10) - 1); + int x = nums[i] >> 10; + nums[j] = y; + nums[j - 1] = x; + j -= 2; + } + + return nums; + } +} +``` + +```cpp +class Solution { +public: + vector shuffle(vector& nums, int n) { + for (int i = 0; i < n; i++) { + nums[i] = (nums[i] << 10) | nums[i + n]; // Store x, y in nums[i] + } + + int j = 2 * n - 1; + for (int i = n - 1; i >= 0; i--) { + int y = nums[i] & ((1 << 10) - 1); + int x = nums[i] >> 10; + nums[j] = y; + nums[j - 1] = x; + j -= 2; + } + + return nums; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @param {number} n + * @return {number[]} + */ + shuffle(nums) { + for (let i = 0; i < n; i++) { + nums[i] = (nums[i] << 10) | nums[i + n]; // Store x, y in nums[i] + } + + let j = 2 * n - 1; + for (let i = n - 1; i >= 0; i--) { + let y = nums[i] & ((1 << 10) - 1); + let x = nums[i] >> 10; + nums[j] = y; + nums[j - 1] = x; + j -= 2; + } + + return nums; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ extra space. \ No newline at end of file diff --git a/articles/single-number-iii.md b/articles/single-number-iii.md new file mode 100644 index 000000000..5e714092d --- /dev/null +++ b/articles/single-number-iii.md @@ -0,0 +1,608 @@ +## 1. Brute Force + +::tabs-start + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> List[int]: + n, res = len(nums), [] + + for i in range(n): + flag = True + for j in range(n): + if i != j and nums[i] == nums[j]: + flag = False + break + + if flag: + res.append(nums[i]) + if len(res) == 2: + break + + return res +``` + +```java +public class Solution { + public int[] singleNumber(int[] nums) { + int n = nums.length; + List res = new ArrayList<>(); + + for (int i = 0; i < n; i++) { + boolean flag = true; + for (int j = 0; j < n; j++) { + if (i != j && nums[i] == nums[j]) { + flag = false; + break; + } + } + + if (flag) { + res.add(nums[i]); + if (res.size() == 2) { + break; + } + } + } + + return new int[] {res.get(0), res.get(1)}; + } +} +``` + +```cpp +class Solution { +public: + vector singleNumber(vector& nums) { + int n = nums.size(); + vector res; + + for (int i = 0; i < n; i++) { + bool flag = true; + for (int j = 0; j < n; j++) { + if (i != j && nums[i] == nums[j]) { + flag = false; + break; + } + } + + if (flag) { + res.push_back(nums[i]); + if (res.size() == 2) { + break; + } + } + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number[]} + */ + singleNumber(nums) { + const n = nums.length; + const res = []; + + for (let i = 0; i < n; i++) { + let flag = true; + for (let j = 0; j < n; j++) { + if (i !== j && nums[i] === nums[j]) { + flag = false; + break; + } + } + + if (flag) { + res.push(nums[i]); + if (res.length === 2) { + break; + } + } + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 2)$ +* Space complexity: $O(1)$ extra space. + +--- + +## 2. Hash Map + +::tabs-start + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> List[int]: + count = {} + for num in nums: + count[num] = 1 + count.get(num, 0) + + return [k for k in count if count[k] == 1] +``` + +```java +public class Solution { + public int[] singleNumber(int[] nums) { + Map count = new HashMap<>(); + for (int num : nums) { + count.put(num, count.getOrDefault(num, 0) + 1); + } + + ArrayList res = new ArrayList<>(); + for (int key : count.keySet()) { + if (count.get(key) == 1) { + res.add(key); + } + } + + return new int[] {res.get(0), res.get(1)}; + } +} +``` + +```cpp +class Solution { +public: + vector singleNumber(vector& nums) { + unordered_map count; + for (int num : nums) { + count[num]++; + } + + vector res; + for (const auto& pair : count) { + if (pair.second == 1) { + res.push_back(pair.first); + } + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number[]} + */ + singleNumber(nums) { + const count = new Map(); + for (const num of nums) { + count.set(num, (count.get(num) || 0) + 1); + } + + const res = []; + for (const [key, value] of count) { + if (value === 1) { + res.push(key); + } + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ + +--- + +## 3. Hash Set + +::tabs-start + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> List[int]: + seen = set() + for num in nums: + if num in seen: + seen.remove(num) + else: + seen.add(num) + return list(seen) +``` + +```java +public class Solution { + public int[] singleNumber(int[] nums) { + HashSet seen = new HashSet<>(); + for (int num : nums) { + if (seen.contains(num)) { + seen.remove(num); + } else { + seen.add(num); + } + } + + int[] res = new int[2]; + int index = 0; + for (int num : seen) { + res[index++] = num; + } + + return res; + } +} +``` + +```cpp +class Solution { +public: + vector singleNumber(vector& nums) { + unordered_set seen; + for (int& num : nums) { + if (seen.count(num)) { + seen.erase(num); + } else { + seen.insert(num); + } + } + + return vector(seen.begin(), seen.end()); + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number[]} + */ + singleNumber(nums) { + const seen = new Set(); + for (const num of nums) { + if (seen.has(num)) { + seen.delete(num); + } else { + seen.add(num); + } + } + + return Array.from(seen); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ + +--- + +## 4. Sorting + +::tabs-start + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> List[int]: + res, n = [], len(nums) + nums.sort() + + for i in range(n): + if ((i > 0 and nums[i] == nums[i - 1]) or + (i + 1 < n and nums[i] == nums[i + 1])): + continue + res.append(nums[i]) + + return res +``` + +```java +public class Solution { + public int[] singleNumber(int[] nums) { + Arrays.sort(nums); + List res = new ArrayList<>(); + int n = nums.length; + + for (int i = 0; i < n; i++) { + if ((i > 0 && nums[i] == nums[i - 1]) || + (i + 1 < n && nums[i] == nums[i + 1])) { + continue; + } + res.add(nums[i]); + } + + return res.stream().mapToInt(i -> i).toArray(); + } +} +``` + +```cpp +class Solution { +public: + vector singleNumber(vector& nums) { + sort(nums.begin(), nums.end()); + vector res; + int n = nums.size(); + + for (int i = 0; i < n; i++) { + if ((i > 0 && nums[i] == nums[i - 1]) || + (i + 1 < n && nums[i] == nums[i + 1])) { + continue; + } + res.push_back(nums[i]); + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number[]} + */ + singleNumber(nums) { + nums.sort((a, b) => a - b); + const res = []; + const n = nums.length; + + for (let i = 0; i < n; i++) { + if ((i > 0 && nums[i] === nums[i - 1]) || + (i + 1 < n && nums[i] === nums[i + 1])) { + continue; + } + res.push(nums[i]); + } + + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n \log n)$ +* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. + +--- + +## 5. Bitwise XOR (Least Significant Bit) + +::tabs-start + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> List[int]: + xor = 0 + for num in nums: + xor ^= num + + diff_bit = 1 + while not (xor & diff_bit): + diff_bit <<= 1 + + a = b = 0 + for num in nums: + if diff_bit & num: + a ^= num + else: + b ^= num + return [a, b] +``` + +```java +public class Solution { + public int[] singleNumber(int[] nums) { + int xor = 0; + for (int num : nums) { + xor ^= num; + } + + int diff_bit = 1; + while ((xor & diff_bit) == 0) { + diff_bit <<= 1; + } + + int a = 0, b = 0; + for (int num : nums) { + if ((num & diff_bit) != 0) { + a ^= num; + } else { + b ^= num; + } + } + return new int[]{a, b}; + } +} +``` + +```cpp +class Solution { +public: + vector singleNumber(vector& nums) { + int xor_all = 0; + for (int& num : nums) { + xor_all ^= num; + } + + int diff_bit = 1; + while ((xor_all & diff_bit) == 0) { + diff_bit <<= 1; + } + + int a = 0, b = 0; + for (int& num : nums) { + if (num & diff_bit) { + a ^= num; + } else { + b ^= num; + } + } + return {a, b}; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number[]} + */ + singleNumber(nums) { + let xor = 0; + for (const num of nums) { + xor ^= num; + } + + let diff_bit = 1; + while ((xor & diff_bit) === 0) { + diff_bit <<= 1; + } + + let a = 0, b = 0; + for (const num of nums) { + if (num & diff_bit) { + a ^= num; + } else { + b ^= num; + } + } + return [a, b]; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ extra space. + +--- + +## 6. Bitwise XOR (Most Significant Bit) + +::tabs-start + +```python +class Solution: + def singleNumber(self, nums: List[int]) -> List[int]: + xor = 0 + for num in nums: + xor ^= num + + diff_bit = xor & (-xor) + + a = b = 0 + for num in nums: + if diff_bit & num: + a ^= num + else: + b ^= num + return [a, b] +``` + +```java +public class Solution { + public int[] singleNumber(int[] nums) { + int xor = 0; + for (int num : nums) { + xor ^= num; + } + + int diff_bit = xor & (-xor); + + int a = 0, b = 0; + for (int num : nums) { + if ((num & diff_bit) != 0) { + a ^= num; + } else { + b ^= num; + } + } + return new int[]{a, b}; + } +} +``` + +```cpp +class Solution { +public: + vector singleNumber(vector& nums) { + uint xor_all = 0; + for (int& num : nums) { + xor_all ^= num; + } + + int diff_bit = xor_all & (-xor_all); + + int a = 0, b = 0; + for (int& num : nums) { + if (num & diff_bit) { + a ^= num; + } else { + b ^= num; + } + } + return {a, b}; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} nums + * @return {number[]} + */ + singleNumber(nums) { + let xor = 0; + for (const num of nums) { + xor ^= num; + } + + let diff_bit = xor & (-xor); + + let a = 0, b = 0; + for (const num of nums) { + if (num & diff_bit) { + a ^= num; + } else { + b ^= num; + } + } + return [a, b]; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ extra space. \ No newline at end of file diff --git a/articles/spiral-matrix-ii.md b/articles/spiral-matrix-ii.md new file mode 100644 index 000000000..1df46f786 --- /dev/null +++ b/articles/spiral-matrix-ii.md @@ -0,0 +1,454 @@ +## 1. Iteration + +::tabs-start + +```python +class Solution: + def generateMatrix(self, n: int) -> List[List[int]]: + mat = [[0] * n for _ in range(n)] + left, right = 0, n - 1 + top, bottom = 0, n - 1 + val = 1 + + while left <= right: + # Fill every val in top row + for c in range(left, right + 1): + mat[top][c] = val + val += 1 + top += 1 + + # Fill every val in right col + for r in range(top, bottom + 1): + mat[r][right] = val + val += 1 + right -= 1 + + # Fill every val in bottom row (reverse order) + for c in range(right, left - 1, -1): + mat[bottom][c] = val + val += 1 + bottom -= 1 + + # Fill every val in the left col (reverse order) + for r in range(bottom, top - 1, -1): + mat[r][left] = val + val += 1 + left += 1 + + return mat +``` + +```java +public class Solution { + public int[][] generateMatrix(int n) { + int[][] mat = new int[n][n]; + int left = 0, right = n - 1, top = 0, bottom = n - 1, val = 1; + + while (left <= right) { + // Fill every val in top row + for (int c = left; c <= right; c++) { + mat[top][c] = val++; + } + top++; + + // Fill every val in right col + for (int r = top; r <= bottom; r++) { + mat[r][right] = val++; + } + right--; + + // Fill every val in bottom row (reverse order) + for (int c = right; c >= left; c--) { + mat[bottom][c] = val++; + } + bottom--; + + // Fill every val in the left col (reverse order) + for (int r = bottom; r >= top; r--) { + mat[r][left] = val++; + } + left++; + } + + return mat; + } +} +``` + +```cpp +class Solution { +public: + vector> generateMatrix(int n) { + vector> mat(n, vector(n, 0)); + int left = 0, right = n - 1, top = 0, bottom = n - 1, val = 1; + + while (left <= right) { + // Fill every val in top row + for (int c = left; c <= right; c++) { + mat[top][c] = val++; + } + top++; + + // Fill every val in right col + for (int r = top; r <= bottom; r++) { + mat[r][right] = val++; + } + right--; + + // Fill every val in bottom row (reverse order) + for (int c = right; c >= left; c--) { + mat[bottom][c] = val++; + } + bottom--; + + // Fill every val in the left col (reverse order) + for (int r = bottom; r >= top; r--) { + mat[r][left] = val++; + } + left++; + } + + return mat; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {number[][]} + */ + generateMatrix(n) { + const mat = Array.from({ length: n }, () => Array(n).fill(0)); + let left = 0, right = n - 1, top = 0, bottom = n - 1, val = 1; + + while (left <= right) { + // Fill every val in top row + for (let c = left; c <= right; c++) { + mat[top][c] = val++; + } + top++; + + // Fill every val in right col + for (let r = top; r <= bottom; r++) { + mat[r][right] = val++; + } + right--; + + // Fill every val in bottom row (reverse order) + for (let c = right; c >= left; c--) { + mat[bottom][c] = val++; + } + bottom--; + + // Fill every val in the left col (reverse order) + for (let r = bottom; r >= top; r--) { + mat[r][left] = val++; + } + left++; + } + + return mat; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 2)$ +* Space complexity: $O(n ^ 2)$ for the output matrix. + +--- + +## 2. Recursion + +::tabs-start + +```python +class Solution: + def generateMatrix(self, n: int) -> List[List[int]]: + mat = [[0] * n for _ in range(n)] + + def fill(left, right, top, bottom, val): + if left > right or top > bottom: + return + + # Fill every val in top row + for c in range(left, right + 1): + mat[top][c] = val + val += 1 + top += 1 + + # Fill every val in right col + for r in range(top, bottom + 1): + mat[r][right] = val + val += 1 + right -= 1 + + # Fill every val in bottom row (reverse order) + for c in range(right, left - 1, -1): + mat[bottom][c] = val + val += 1 + bottom -= 1 + + # Fill every val in the left col (reverse order) + for r in range(bottom, top - 1, -1): + mat[r][left] = val + val += 1 + left += 1 + + # Recur for the inner layer + fill(left, right, top, bottom, val) + + fill(0, n - 1, 0, n - 1, 1) + return mat +``` + +```java +public class Solution { + public int[][] generateMatrix(int n) { + int[][] mat = new int[n][n]; + fill(mat, 0, n - 1, 0, n - 1, 1); + return mat; + } + + private void fill(int[][] mat, int left, int right, int top, int bottom, int val) { + if (left > right || top > bottom) return; + + // Fill every val in top row + for (int c = left; c <= right; c++) { + mat[top][c] = val++; + } + top++; + + // Fill every val in right col + for (int r = top; r <= bottom; r++) { + mat[r][right] = val++; + } + right--; + + // Fill every val in bottom row (reverse order) + for (int c = right; c >= left; c--) { + mat[bottom][c] = val++; + } + bottom--; + + // Fill every val in the left col (reverse order) + for (int r = bottom; r >= top; r--) { + mat[r][left] = val++; + } + left++; + + // Recur for the inner layer + fill(mat, left, right, top, bottom, val); + } +} +``` + +```cpp +class Solution { +public: + vector> generateMatrix(int n) { + vector> mat(n, vector(n, 0)); + fill(mat, 0, n - 1, 0, n - 1, 1); + return mat; + } + +private: + void fill(vector> &mat, int left, int right, int top, int bottom, int val) { + if (left > right || top > bottom) return; + + // Fill every val in top row + for (int c = left; c <= right; c++) { + mat[top][c] = val++; + } + top++; + + // Fill every val in right col + for (int r = top; r <= bottom; r++) { + mat[r][right] = val++; + } + right--; + + // Fill every val in bottom row (reverse order) + for (int c = right; c >= left; c--) { + mat[bottom][c] = val++; + } + bottom--; + + // Fill every val in the left col (reverse order) + for (int r = bottom; r >= top; r--) { + mat[r][left] = val++; + } + left++; + + // Recur for the inner layer + fill(mat, left, right, top, bottom, val); + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {number[][]} + */ + generateMatrix(n) { + const mat = Array.from({ length: n }, () => Array(n).fill(0)); + + const fill = (left, right, top, bottom, val) => { + if (left > right || top > bottom) return; + + // Fill every val in top row + for (let c = left; c <= right; c++) { + mat[top][c] = val++; + } + top++; + + // Fill every val in right col + for (let r = top; r <= bottom; r++) { + mat[r][right] = val++; + } + right--; + + // Fill every val in bottom row (reverse order) + for (let c = right; c >= left; c--) { + mat[bottom][c] = val++; + } + bottom--; + + // Fill every val in the left col (reverse order) + for (let r = bottom; r >= top; r--) { + mat[r][left] = val++; + } + left++; + + // Recur for the inner layer + fill(left, right, top, bottom, val); + }; + + fill(0, n - 1, 0, n - 1, 1); + return mat; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 2)$ +* Space complexity: + * $O(n)$ space for recursion stack. + * $O(n ^ 2)$ space for the output matrix. + +--- + +## 3. Iteration (Optimal) + +::tabs-start + +```python +class Solution: + def generateMatrix(self, n: int) -> List[List[int]]: + mat = [[0] * n for _ in range(n)] + r = c = 0 + dr, dc = 0, 1 + + for val in range(n * n): + mat[r][c] = val + 1 + if mat[(r + dr) % n][(c + dc) % n] != 0: + dr, dc = dc, -dr + r, c = r + dr, c + dc + + return mat +``` + +```java +public class Solution { + public int[][] generateMatrix(int n) { + int[][] mat = new int[n][n]; + int r = 0, c = 0, dr = 0, dc = 1; + + for (int val = 0; val < n * n; val++) { + mat[r][c] = val + 1; + int nextR = (r + dr) % n, nextC = (c + dc) % n; + if (nextR < 0) nextR += n; + if (nextC < 0) nextC += n; + if (mat[nextR][nextC] != 0) { + int temp = dr; + dr = dc; + dc = -temp; + } + r += dr; + c += dc; + } + + return mat; + } +} +``` + +```cpp +class Solution { +public: + vector> generateMatrix(int n) { + vector> mat(n, vector(n, 0)); + int r = 0, c = 0, dr = 0, dc = 1; + + for (int val = 0; val < n * n; val++) { + mat[r][c] = val + 1; + int nextR = (r + dr) % n, nextC = (c + dc) % n; + if (nextR < 0) nextR += n; + if (nextC < 0) nextC += n; + if (mat[nextR][nextC] != 0) { + int temp = dr; + dr = dc; + dc = -temp; + } + r += dr; + c += dc; + } + + return mat; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {number[][]} + */ + generateMatrix(n) { + const mat = Array.from({ length: n }, () => Array(n).fill(0)); + let r = 0, c = 0, dr = 0, dc = 1; + + for (let val = 0; val < n * n; val++) { + mat[r][c] = val + 1; + let nextR = (r + dr) % n, nextC = (c + dc) % n; + if (nextR < 0) nextR += n; + if (nextC < 0) nextC += n; + if (mat[nextR][nextC] !== 0) { + [dr, dc] = [dc, -dr]; + } + r += dr; + c += dc; + } + + return mat; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n ^ 2)$ +* Space complexity: $O(n ^ 2)$ for the output matrix. \ No newline at end of file diff --git a/articles/ugly-number.md b/articles/ugly-number.md new file mode 100644 index 000000000..f2a68a2e5 --- /dev/null +++ b/articles/ugly-number.md @@ -0,0 +1,76 @@ +## 1. Math + +::tabs-start + +```python +class Solution: + def isUgly(self, n: int) -> bool: + if n <= 0: + return False + + for p in [2, 3, 5]: + while n % p == 0: + n //= p + + return n == 1 +``` + +```java +public class Solution { + public boolean isUgly(int n) { + if (n <= 0) return false; + + for (int p = 2; p <= 5 && n > 0; p++) { + while (n % p == 0) { + n /= p; + } + } + + return n == 1; + } +} +``` + +```cpp +class Solution { +public: + bool isUgly(int n) { + if (n <= 0) return false; + + for (int p = 2; p <= 5 && n > 0; p++) { + while (n % p == 0) { + n /= p; + } + } + + return n == 1; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number} n + * @return {boolean} + */ + isUgly(n) { + if (n <= 0) return false; + + for (let p of [2, 3, 5]) { + while (n % p == 0) { + n /= p; + } + } + + return n === 1; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(\log n)$ +* Space complexity: $O(1)$ \ No newline at end of file diff --git a/articles/zigzag-conversion.md b/articles/zigzag-conversion.md new file mode 100644 index 000000000..5df4dafff --- /dev/null +++ b/articles/zigzag-conversion.md @@ -0,0 +1,226 @@ +## 1. Iteration - I + +::tabs-start + +```python +class Solution: + def convert(self, s: str, numRows: int) -> str: + if numRows == 1: + return s + + res = [] + for r in range(numRows): + increment = 2 * (numRows - 1) + for i in range(r, len(s), increment): + res.append(s[i]) + if r > 0 and r < numRows - 1 and i + increment - 2 * r < len(s): + res.append(s[i + increment - 2 * r]) + + return ''.join(res) +``` + +```java +public class Solution { + public String convert(String s, int numRows) { + if (numRows == 1) { + return s; + } + + StringBuilder res = new StringBuilder(); + int len = s.length(); + + for (int r = 0; r < numRows; r++) { + int increment = 2 * (numRows - 1); + for (int i = r; i < len; i += increment) { + res.append(s.charAt(i)); + if (r > 0 && r < numRows - 1 && i + increment - 2 * r < len) { + res.append(s.charAt(i + increment - 2 * r)); + } + } + } + + return res.toString(); + } +} +``` + +```cpp +class Solution { +public: + string convert(string s, int numRows) { + if (numRows == 1) { + return s; + } + + string res; + int len = s.size(); + + for (int r = 0; r < numRows; r++) { + int increment = 2 * (numRows - 1); + for (int i = r; i < len; i += increment) { + res += s[i]; + if (r > 0 && r < numRows - 1 && i + increment - 2 * r < len) { + res += s[i + increment - 2 * r]; + } + } + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} s + * @param {number} numRows + * @return {string} + */ + convert(s, numRows) { + if (numRows === 1) { + return s; + } + + let res = []; + const len = s.length; + + for (let r = 0; r < numRows; r++) { + const increment = 2 * (numRows - 1); + for (let i = r; i < len; i += increment) { + res.push(s[i]); + if (r > 0 && r < numRows - 1 && i + increment - 2 * r < len) { + res.push(s[i + increment - 2 * r]); + } + } + } + + return res.join(''); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ for the ouput string. + +--- + +## 2. Iteration - II + +::tabs-start + +```python +class Solution: + def convert(self, s: str, numRows: int) -> str: + if numRows == 1 or numRows >= len(s): + return s + + res = [[] for _ in range(numRows)] + row, dir = 0, 1 + for c in s: + res[row].append(c) + row += dir + if row == 0 or row == (numRows - 1): + dir *= -1 + + return ''.join([''.join(row) for row in res]) +``` + +```java +public class Solution { + public String convert(String s, int numRows) { + if (numRows == 1 || numRows >= s.length()) { + return s; + } + + List[] res = new ArrayList[numRows]; + for (int i = 0; i < numRows; i++) { + res[i] = new ArrayList<>(); + } + + int row = 0, dir = 1; + for (int i = 0; i < s.length(); i++) { + res[row].add(s.charAt(i)); + row += dir; + if (row == 0 || row == numRows - 1) { + dir *= -1; + } + } + + StringBuilder result = new StringBuilder(); + for (List rowList : res) { + for (char c : rowList) { + result.append(c); + } + } + return result.toString(); + } +} +``` + +```cpp +class Solution { +public: + string convert(string s, int numRows) { + if (numRows == 1 || numRows >= s.size()) { + return s; + } + + vector res(numRows); + int row = 0, dir = 1; + + for (char& c : s) { + res[row] += c; + row += dir; + if (row == 0 || row == numRows - 1) { + dir *= -1; + } + } + + string result; + for (string& rowString : res) { + result += rowString; + } + return result; + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} s + * @param {number} numRows + * @return {string} + */ + convert(s, numRows) { + if (numRows === 1 || numRows >= s.length) { + return s; + } + + const res = Array.from({ length: numRows }, () => []); + let row = 0, dir = 1; + + for (const c of s) { + res[row].push(c); + row += dir; + if (row === 0 || row === numRows - 1) { + dir *= -1; + } + } + + return res.map(row => row.join("")).join(""); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(n)$ for the output string. \ No newline at end of file From 149c00e4ead6edb2fe3269448403d90f2b554a3d Mon Sep 17 00:00:00 2001 From: Sri Hari Date: Fri, 17 Jan 2025 23:26:20 +0530 Subject: [PATCH 2/2] Batch-5/Neetcode-ALL/Added-articles --- articles/find-missing-observations.md | 210 ++++++++++++++++++++++++++ articles/robot-bounded-in-circle.md | 107 +++++++++++++ 2 files changed, 317 insertions(+) create mode 100644 articles/find-missing-observations.md create mode 100644 articles/robot-bounded-in-circle.md diff --git a/articles/find-missing-observations.md b/articles/find-missing-observations.md new file mode 100644 index 000000000..218ffed24 --- /dev/null +++ b/articles/find-missing-observations.md @@ -0,0 +1,210 @@ +## 1. Math - I + +::tabs-start + +```python +class Solution: + def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]: + m = len(rolls) + nTotal = (mean * (n + m)) - sum(rolls) + + if nTotal < n or nTotal > n * 6: + return [] + + res = [] + while nTotal: + dice = min(nTotal - n + 1, 6) + res.append(dice) + nTotal -= dice + n -= 1 + return res +``` + +```java +public class Solution { + public int[] missingRolls(int[] rolls, int mean, int n) { + int m = rolls.length; + int nTotal = (mean * (n + m)) - Arrays.stream(rolls).sum(); + + if (nTotal < n || nTotal > n * 6) { + return new int[0]; + } + + int[] res = new int[n]; + for (int i = 0; i < n; i++) { + int dice = Math.min(nTotal - (n - i - 1), 6); + res[i] = dice; + nTotal -= dice; + } + return res; + } +} +``` + +```cpp +class Solution { +public: + vector missingRolls(vector& rolls, int mean, int n) { + int m = rolls.size(); + int nTotal = (mean * (n + m)) - accumulate(rolls.begin(), rolls.end(), 0); + + if (nTotal < n || nTotal > n * 6) { + return {}; + } + + vector res; + for (int i = 0; i < n; ++i) { + int dice = min(nTotal - (n - i - 1), 6); + res.push_back(dice); + nTotal -= dice; + } + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} rolls + * @param {number} mean + * @param {number} n + * @return {number[]} + */ + missingRolls(rolls, mean, n) { + const m = rolls.length; + let nTotal = (mean * (n + m)) - rolls.reduce((sum, roll) => sum + roll, 0); + + if (nTotal < n || nTotal > n * 6) { + return []; + } + + const res = []; + while (nTotal > 0) { + const dice = Math.min(nTotal - n + 1, 6); + res.push(dice); + nTotal -= dice; + n--; + } + return res; + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(m + n)$ +* Space complexity: + * $O(1)$ extra space. + * $O(n)$ space for the output array. + +> Where $m$ is the size of the array $rolls$ and $n$ is the number of missing observations. + +--- + +## 2. Math - II + +::tabs-start + +```python +class Solution: + def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]: + m = len(rolls) + nTotal = (mean * (n + m)) - sum(rolls) + + if nTotal < n or nTotal > n * 6: + return [] + + avg = nTotal // n + rem = nTotal - (avg * n) + return [avg] * (n - rem) + [avg + 1] * rem +``` + +```java +public class Solution { + public int[] missingRolls(int[] rolls, int mean, int n) { + int m = rolls.length; + int nTotal = (mean * (n + m)) - Arrays.stream(rolls).sum(); + + if (nTotal < n || nTotal > n * 6) { + return new int[0]; + } + + int avg = nTotal / n; + int rem = nTotal - (avg * n); + int[] res = new int[n]; + + for (int i = 0; i < n - rem; i++) { + res[i] = avg; + } + for (int i = n - rem; i < n; i++) { + res[i] = avg + 1; + } + + return res; + } +} +``` + +```cpp +class Solution { +public: + vector missingRolls(vector& rolls, int mean, int n) { + int m = rolls.size(); + int nTotal = (mean * (n + m)) - accumulate(rolls.begin(), rolls.end(), 0); + + if (nTotal < n || nTotal > n * 6) { + return {}; + } + + int avg = nTotal / n; + int rem = nTotal - (avg * n); + vector res; + + for (int i = 0; i < n - rem; ++i) { + res.push_back(avg); + } + for (int i = 0; i < rem; ++i) { + res.push_back(avg + 1); + } + + return res; + } +}; +``` + +```javascript +class Solution { + /** + * @param {number[]} rolls + * @param {number} mean + * @param {number} n + * @return {number[]} + */ + missingRolls(rolls, mean, n) { + const m = rolls.length; + const nTotal = (mean * (n + m)) - rolls.reduce((sum, roll) => sum + roll, 0); + + if (nTotal < n || nTotal > n * 6) { + return []; + } + + const avg = Math.floor(nTotal / n); + const rem = nTotal - (avg * n); + return Array(n - rem).fill(avg).concat(Array(rem).fill(avg + 1)); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(m + n)$ +* Space complexity: + * $O(1)$ extra space. + * $O(n)$ space for the output array. + +> Where $m$ is the size of the array $rolls$ and $n$ is the number of missing observations. \ No newline at end of file diff --git a/articles/robot-bounded-in-circle.md b/articles/robot-bounded-in-circle.md new file mode 100644 index 000000000..76ec62fc9 --- /dev/null +++ b/articles/robot-bounded-in-circle.md @@ -0,0 +1,107 @@ +## 1. Simulation + +::tabs-start + +```python +class Solution: + def isRobotBounded(self, instructions: str) -> bool: + dirX, dirY = 0, 1 + x, y = 0, 0 + + for d in instructions: + if d == "G": + x, y = x + dirX, y + dirY + elif d == "L": + dirX, dirY = -dirY, dirX + else: + dirX, dirY = dirY, -dirX + + return (x, y) == (0, 0) or (dirX, dirY) != (0, 1) +``` + +```java +public class Solution { + public boolean isRobotBounded(String instructions) { + int dirX = 0, dirY = 1; + int x = 0, y = 0; + + for (int i = 0; i < instructions.length(); i++) { + char d = instructions.charAt(i); + if (d == 'G') { + x += dirX; + y += dirY; + } else if (d == 'L') { + int temp = dirX; + dirX = -dirY; + dirY = temp; + } else { + int temp = dirX; + dirX = dirY; + dirY = -temp; + } + } + + return (x == 0 && y == 0) || (dirX != 0 || dirY != 1); + } +} +``` + +```cpp +class Solution { +public: + bool isRobotBounded(string instructions) { + int dirX = 0, dirY = 1; + int x = 0, y = 0; + + for (char d : instructions) { + if (d == 'G') { + x += dirX; + y += dirY; + } else if (d == 'L') { + int temp = dirX; + dirX = -dirY; + dirY = temp; + } else { + int temp = dirX; + dirX = dirY; + dirY = -temp; + } + } + + return (x == 0 && y == 0) || (dirX != 0 || dirY != 1); + } +}; +``` + +```javascript +class Solution { + /** + * @param {string} instructions + * @return {boolean} + */ + isRobotBounded(instructions) { + let dirX = 0, dirY = 1; + let x = 0, y = 0; + + for (const d of instructions) { + if (d === 'G') { + x += dirX; + y += dirY; + } else if (d === 'L') { + [dirX, dirY] = [-dirY, dirX]; + } else { + [dirX, dirY] = [dirY, -dirX]; + } + } + + return (x === 0 && y === 0) || (dirX !== 0 || dirY !== 1); + } +} +``` + +::tabs-end + +### Time & Space Complexity + +* Time complexity: $O(n)$ +* Space complexity: $O(1)$ extra space. \ No newline at end of file