From 8c191cdaec4157a88d0dbff6a2768c406298bcf2 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:21:08 +0530 Subject: [PATCH 01/59] Update 394. Decode String.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../394. Decode String/394. Decode String.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Solution/394. Decode String/394. Decode String.py b/Solution/394. Decode String/394. Decode String.py index e69de29..a928167 100644 --- a/Solution/394. Decode String/394. Decode String.py +++ b/Solution/394. Decode String/394. Decode String.py @@ -0,0 +1,16 @@ +class Solution: + def decodeString(self, s: str) -> str: + s1, s2 = [], [] + num, res = 0, '' + for c in s: + if c.isdigit(): + num = num * 10 + int(c) + elif c == '[': + s1.append(num) + s2.append(res) + num, res = 0, '' + elif c == ']': + res = s2.pop() + res * s1.pop() + else: + res += c + return res \ No newline at end of file From 6a252d482e6a8322258a6f035a8f0c8744831e6f Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:23:58 +0530 Subject: [PATCH 02/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/394. Decode String/readme.md | 227 ++++++++++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 Solution/394. Decode String/readme.md diff --git a/Solution/394. Decode String/readme.md b/Solution/394. Decode String/readme.md new file mode 100644 index 0000000..691b227 --- /dev/null +++ b/Solution/394. Decode String/readme.md @@ -0,0 +1,227 @@ + + + + +# [394. Decode String](https://leetcode.com/problems/decode-string) + + +--- +- **comments**: true +- **difficulty**: Medium + +- **tags**: + - Stack + - Recursion + - String +--- + +## Description + + + +Given an encoded string, return its decoded string. + +The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer. + +You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. + +The test cases are generated so that the length of the output will never exceed `10^5`. + +  + +**Example 1:** +``` +Input: s = "3[a]2[bc]" +Output: "aaabcbc" +``` + +**Example 2:** +``` +Input: s = "3[a2[c]]" +Output: "accaccacc" +``` + +**Example 3:** +``` +Input: s = "2[abc]3[cd]ef" +Output: "abcabccdcdcdef" +``` + +  + +**Constraints:** + +- `1 <= s.length <= 30` +- `s` consists of lowercase English letters, digits, and square brackets `'[]'`. +- `s` is guaranteed to be a valid input. +- All the integers in `s` are in the range `[1, 300]`. + + + +## Solutions + + + +### Solution 1: Stack + +We iterate through the string and process characters one by one: + +- If it's a digit, we calculate the full number. +- If we encounter `'['`, we push the current number and partial result to the stack, then reset. +- If we encounter `']'`, we pop the last number and string from the stack and repeat the current string that many times, then append. +- Otherwise, we add the character to the current result. + +Time complexity: O(n) +Space complexity: O(n) + + + +#### Python3 + +```python +class Solution: + def decodeString(self, s: str) -> str: + s1, s2 = [], [] + num, res = 0, '' + for c in s: + if c.isdigit(): + num = num * 10 + int(c) + elif c == '[': + s1.append(num) + s2.append(res) + num, res = 0, '' + elif c == ']': + res = s2.pop() + res * s1.pop() + else: + res += c + return res +``` + +#### Java + +```java +class Solution { + public String decodeString(String s) { + Deque s1 = new ArrayDeque<>(); + Deque s2 = new ArrayDeque<>(); + int num = 0; + String res = ""; + for (char c : s.toCharArray()) { + if (Character.isDigit(c)) { + num = num * 10 + c - '0'; + } else if (c == '[') { + s1.push(num); + s2.push(res); + num = 0; + res = ""; + } else if (c == ']') { + StringBuilder t = new StringBuilder(); + int times = s1.pop(); + for (int i = 0; i < times; ++i) { + t.append(res); + } + res = s2.pop() + t.toString(); + } else { + res += c; + } + } + return res; + } +} +``` + +#### TypeScript + +```ts +function decodeString(s: string): string { + let ans = ''; + let stack = []; + let count = 0; + for (let ch of s) { + if (/\d/.test(ch)) { + count = count * 10 + Number(ch); + } else if (ch === '[') { + stack.push([ans, count]); + ans = ''; + count = 0; + } else if (ch === ']') { + let [prev, num] = stack.pop(); + ans = prev + ans.repeat(num); + } else { + ans += ch; + } + } + return ans; +} +``` + +#### C++ + +```cpp +class Solution { +public: + string decodeString(string s) { + stack countStack; + stack strStack; + string currentStr = ""; + int k = 0; + for (char c : s) { + if (isdigit(c)) { + k = k * 10 + c - '0'; + } else if (c == '[') { + countStack.push(k); + strStack.push(currentStr); + currentStr = ""; + k = 0; + } else if (c == ']') { + string temp = currentStr; + currentStr = strStack.top(); + strStack.pop(); + int repeat = countStack.top(); + countStack.pop(); + while (repeat--) currentStr += temp; + } else { + currentStr += c; + } + } + return currentStr; + } +}; +``` + +#### Go + +```go +func decodeString(s string) string { + stack := []string{} + numStack := []int{} + res := "" + num := 0 + for _, c := range s { + switch { + case c >= '0' && c <= '9': + num = num*10 + int(c-'0') + case c == '[': + numStack = append(numStack, num) + stack = append(stack, res) + res = "" + num = 0 + case c == ']': + n := numStack[len(numStack)-1] + numStack = numStack[:len(numStack)-1] + prev := stack[len(stack)-1] + stack = stack[:len(stack)-1] + res = prev + strings.Repeat(res, n) + default: + res += string(c) + } + } + return res +} +``` + + + + + + From b11280ac0db784cd726f6e4757de00ce4e9ed3da Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:25:20 +0530 Subject: [PATCH 03/59] Create 933. Number of Recent Calls.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../933. Number of Recent Calls/933. Number of Recent Calls.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/933. Number of Recent Calls/933. Number of Recent Calls.py diff --git a/Solution/933. Number of Recent Calls/933. Number of Recent Calls.py b/Solution/933. Number of Recent Calls/933. Number of Recent Calls.py new file mode 100644 index 0000000..e69de29 From 144314ab5ab2f03b07bc0fb335b785e9866c2dbe Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:26:22 +0530 Subject: [PATCH 04/59] Update 933. Number of Recent Calls.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../933. Number of Recent Calls.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Solution/933. Number of Recent Calls/933. Number of Recent Calls.py b/Solution/933. Number of Recent Calls/933. Number of Recent Calls.py index e69de29..6a73e43 100644 --- a/Solution/933. Number of Recent Calls/933. Number of Recent Calls.py +++ b/Solution/933. Number of Recent Calls/933. Number of Recent Calls.py @@ -0,0 +1,14 @@ +class RecentCounter: + def __init__(self): + self.q = deque() + + def ping(self, t: int) -> int: + self.q.append(t) + while self.q[0] < t - 3000: + self.q.popleft() + return len(self.q) + + +# Your RecentCounter object will be instantiated and called as such: +# obj = RecentCounter() +# param_1 = obj.ping(t) \ No newline at end of file From 120ce7d8d376528ca734a17493d273ae1cca45ce Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:27:33 +0530 Subject: [PATCH 05/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/933. Number of Recent Calls/readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/933. Number of Recent Calls/readme.md diff --git a/Solution/933. Number of Recent Calls/readme.md b/Solution/933. Number of Recent Calls/readme.md new file mode 100644 index 0000000..e69de29 From 9d529645e311c4330edc7e33b678213556f23d9e Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:34:14 +0530 Subject: [PATCH 06/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../933. Number of Recent Calls/readme.md | 276 ++++++++++++++++++ 1 file changed, 276 insertions(+) diff --git a/Solution/933. Number of Recent Calls/readme.md b/Solution/933. Number of Recent Calls/readme.md index e69de29..6535161 100644 --- a/Solution/933. Number of Recent Calls/readme.md +++ b/Solution/933. Number of Recent Calls/readme.md @@ -0,0 +1,276 @@ + + +# 933. Number of Recent Calls +--- +- **difficulty**: Easy +- **title**: Number of Recent Calls +- **leetcode_id**: 933 +- **tags**: + - Design + - Queue + - Data Stream +--- + +## Description + +You have a `RecentCounter` class which counts the number of recent requests within a certain time frame. + +Implement the `RecentCounter` class: + +- `RecentCounter()` Initializes the counter with zero recent requests. +- `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, and returns the number of requests that has happened in the past `3000` milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range `[t - 3000, t]`. + +It is **guaranteed** that every call to `ping` uses a strictly larger value of `t` than the previous call. + +**Example:** + +``` +Input +["RecentCounter", "ping", "ping", "ping", "ping"] +[[], [1], [100], [3001], [3002]] +Output +[null, 1, 2, 3, 3] + +Explanation +RecentCounter recentCounter = new RecentCounter(); +recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1 +recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2 +recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3 +recentCounter.ping(3002); // requests = [100, 3001, 3002], range is [2,3002], return 3 +``` + +**Constraints:** + +- `1 <= t <= 10⁹` +- Each test case will call `ping` with strictly increasing values of `t`. +- At most `10⁴` calls will be made to `ping`. + +## Solutions + +### Solution 1: Queue + +We keep a queue to store timestamps and remove any timestamps outside of the range `[t - 3000, t]`. + +#### Python3 + +```python +from collections import deque + +class RecentCounter: + def __init__(self): + self.q = deque() + + def ping(self, t: int) -> int: + self.q.append(t) + while self.q[0] < t - 3000: + self.q.popleft() + return len(self.q) +``` + +#### Java + +```java +class RecentCounter { + private Queue q; + + public RecentCounter() { + q = new LinkedList<>(); + } + + public int ping(int t) { + q.offer(t); + while (q.peek() < t - 3000) { + q.poll(); + } + return q.size(); + } +} +``` + +#### C++ + +```cpp +class RecentCounter { +public: + queue q; + + RecentCounter() {} + + int ping(int t) { + q.push(t); + while (q.front() < t - 3000) q.pop(); + return q.size(); + } +}; +``` + +#### Go + +```go +type RecentCounter struct { + q []int +} + +func Constructor() RecentCounter { + return RecentCounter{[]int{}} +} + +func (this *RecentCounter) Ping(t int) int { + this.q = append(this.q, t) + for this.q[0] < t-3000 { + this.q = this.q[1:] + } + return len(this.q) +} +``` + +#### TypeScript + +```ts +class RecentCounter { + private queue: number[]; + + constructor() { + this.queue = []; + } + + ping(t: number): number { + this.queue.push(t); + while (this.queue[0] < t - 3000) { + this.queue.shift(); + } + return this.queue.length; + } +} +``` + +#### JavaScript + +```js +var RecentCounter = function () { + this.q = []; +}; + +RecentCounter.prototype.ping = function (t) { + this.q.push(t); + while (this.q[0] < t - 3000) { + this.q.shift(); + } + return this.q.length; +}; +``` + +#### C# + +```cs +public class RecentCounter { + private Queue q = new Queue(); + + public RecentCounter() {} + + public int Ping(int t) { + q.Enqueue(t); + while (q.Peek() < t - 3000) { + q.Dequeue(); + } + return q.Count; + } +} +``` + +#### Rust + +```rust +use std::collections::VecDeque; + +struct RecentCounter { + queue: VecDeque, +} + +impl RecentCounter { + fn new() -> Self { + Self { + queue: VecDeque::new(), + } + } + + fn ping(&mut self, t: i32) -> i32 { + self.queue.push_back(t); + while let Some(&v) = self.queue.front() { + if v >= t - 3000 { + break; + } + self.queue.pop_front(); + } + self.queue.len() as i32 + } +} +``` + +--- + +### Solution 2: Binary Search + +We use a list and binary search (via `bisect`) to find the count of requests in range. + +#### Python3 + +```python +from bisect import bisect_left + +class RecentCounter: + def __init__(self): + self.s = [] + + def ping(self, t: int) -> int: + self.s.append(t) + return len(self.s) - bisect_left(self.s, t - 3000) +``` + +#### C++ + +```cpp +class RecentCounter { +public: + vector s; + + RecentCounter() {} + + int ping(int t) { + s.push_back(t); + return s.size() - (lower_bound(s.begin(), s.end(), t - 3000) - s.begin()); + } +}; +``` + +#### Go + +```go +type RecentCounter struct { + s []int +} + +func Constructor() RecentCounter { + return RecentCounter{[]int{}} +} + +func (this *RecentCounter) Ping(t int) int { + this.s = append(this.s, t) + search := func(x int) int { + left, right := 0, len(this.s) + for left < right { + mid := (left + right) >> 1 + if this.s[mid] >= x { + right = mid + } else { + left = mid + 1 + } + } + return left + } + return len(this.s) - search(t-3000) +} +``` + +``` + From 4b23a617447890440dc5578b3749646c85ab1f04 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:36:43 +0530 Subject: [PATCH 07/59] Create 649. Dota2 Senate.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../649. Dota2 Senate/649. Dota2 Senate.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Solution/649. Dota2 Senate/649. Dota2 Senate.py diff --git a/Solution/649. Dota2 Senate/649. Dota2 Senate.py b/Solution/649. Dota2 Senate/649. Dota2 Senate.py new file mode 100644 index 0000000..0522fe0 --- /dev/null +++ b/Solution/649. Dota2 Senate/649. Dota2 Senate.py @@ -0,0 +1,18 @@ +class Solution: + def predictPartyVictory(self, senate: str) -> str: + qr = deque() + qd = deque() + for i, c in enumerate(senate): + if c == "R": + qr.append(i) + else: + qd.append(i) + n = len(senate) + while qr and qd: + if qr[0] < qd[0]: + qr.append(qr[0] + n) + else: + qd.append(qd[0] + n) + qr.popleft() + qd.popleft() + return "Radiant" if qr else "Dire" \ No newline at end of file From 71b20b7eaaaa398b1193c468cac0b851504bfc97 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:37:13 +0530 Subject: [PATCH 08/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/649. Dota2 Senate/readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/649. Dota2 Senate/readme.md diff --git a/Solution/649. Dota2 Senate/readme.md b/Solution/649. Dota2 Senate/readme.md new file mode 100644 index 0000000..e69de29 From b49235e7eab478eb432e00d51f2214824d8efd38 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:38:44 +0530 Subject: [PATCH 09/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/649. Dota2 Senate/readme.md | 240 +++++++++++++++++++++++++++ 1 file changed, 240 insertions(+) diff --git a/Solution/649. Dota2 Senate/readme.md b/Solution/649. Dota2 Senate/readme.md index e69de29..d9c6106 100644 --- a/Solution/649. Dota2 Senate/readme.md +++ b/Solution/649. Dota2 Senate/readme.md @@ -0,0 +1,240 @@ + +# [649. Dota2 Senate](https://leetcode.com/problems/dota2-senate) + +> Medium +> Greedy, Queue, String + +## Description + +In the world of Dota2, there are two parties: the Radiant and the Dire. + +The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise **one** of the two rights: + +- **Ban one senator's right:** A senator can make another senator lose all his rights in this and all the following rounds. +- **Announce the victory:** If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game. + +Given a string `senate` representing each senator's party belonging. The character `'R'` and `'D'` represent the Radiant party and the Dire party. Then if there are `n` senators, the size of the given string will be `n`. + +The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. + +Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be `"Radiant"` or `"Dire"`. + +## Examples + +### Example 1: + +``` +Input: senate = "RD" +Output: "Radiant" +Explanation: +The first senator comes from Radiant and he can just ban the next senator's right in round 1. +And the second senator can't exercise any rights anymore since his right has been banned. +And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. +``` + +### Example 2: + +``` +Input: senate = "RDD" +Output: "Dire" +Explanation: +The first senator comes from Radiant and he can just ban the next senator's right in round 1. +And the second senator can't exercise any rights anymore since his right has been banned. +And the third senator comes from Dire and he can ban the first senator's right in round 1. +And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. +``` + +## Constraints + +- `n == senate.length` +- `1 <= n <= 10⁴` +- `senate[i]` is either `'R'` or `'D'`. + +## Solutions + +### Approach 1: Queue + Simulation + +We use two queues to store the indices of Radiant (`'R'`) and Dire (`'D'`) senators. The index helps us maintain order and simulate the round-based voting system. + +In each round: +- The senator with the smaller index acts first and bans the other. +- The acting senator goes to the back of the queue with their index increased by `n` to simulate the next round. + +The process continues until one party's queue is empty. + +**Time Complexity:** `O(n)` +**Space Complexity:** `O(n)` + +### Python + +```python +from collections import deque + +class Solution: + def predictPartyVictory(self, senate: str) -> str: + qr = deque() + qd = deque() + for i, c in enumerate(senate): + if c == "R": + qr.append(i) + else: + qd.append(i) + n = len(senate) + while qr and qd: + if qr[0] < qd[0]: + qr.append(qr[0] + n) + else: + qd.append(qd[0] + n) + qr.popleft() + qd.popleft() + return "Radiant" if qr else "Dire" +``` + +### Java + +```java +class Solution { + public String predictPartyVictory(String senate) { + int n = senate.length(); + Deque qr = new ArrayDeque<>(); + Deque qd = new ArrayDeque<>(); + for (int i = 0; i < n; ++i) { + if (senate.charAt(i) == 'R') { + qr.offer(i); + } else { + qd.offer(i); + } + } + while (!qr.isEmpty() && !qd.isEmpty()) { + if (qr.peek() < qd.peek()) { + qr.offer(qr.poll() + n); + qd.poll(); + } else { + qd.offer(qd.poll() + n); + qr.poll(); + } + } + return qr.isEmpty() ? "Dire" : "Radiant"; + } +} +``` + +### C++ + +```cpp +class Solution { +public: + string predictPartyVictory(string senate) { + int n = senate.size(); + queue qr, qd; + for (int i = 0; i < n; ++i) { + if (senate[i] == 'R') { + qr.push(i); + } else { + qd.push(i); + } + } + while (!qr.empty() && !qd.empty()) { + int r = qr.front(), d = qd.front(); + qr.pop(); + qd.pop(); + if (r < d) { + qr.push(r + n); + } else { + qd.push(d + n); + } + } + return qr.empty() ? "Dire" : "Radiant"; + } +}; +``` + +### Go + +```go +func predictPartyVictory(senate string) string { + n := len(senate) + qr := []int{} + qd := []int{} + for i, c := range senate { + if c == 'R' { + qr = append(qr, i) + } else { + qd = append(qd, i) + } + } + for len(qr) > 0 && len(qd) > 0 { + r, d := qr[0], qd[0] + qr, qd = qr[1:], qd[1:] + if r < d { + qr = append(qr, r+n) + } else { + qd = append(qd, d+n) + } + } + if len(qr) > 0 { + return "Radiant" + } + return "Dire" +} +``` + +### TypeScript + +```ts +function predictPartyVictory(senate: string): string { + const n = senate.length; + const qr: number[] = []; + const qd: number[] = []; + for (let i = 0; i < n; ++i) { + if (senate[i] === 'R') { + qr.push(i); + } else { + qd.push(i); + } + } + while (qr.length && qd.length) { + const r = qr.shift()!; + const d = qd.shift()!; + if (r < d) { + qr.push(r + n); + } else { + qd.push(d + n); + } + } + return qr.length ? 'Radiant' : 'Dire'; +} +``` + +### Rust + +```rust +impl Solution { + pub fn predict_party_victory(senate: String) -> String { + let mut qr = std::collections::VecDeque::new(); + let mut qd = std::collections::VecDeque::new(); + let n = senate.len(); + for (i, c) in senate.chars().enumerate() { + if c == 'R' { + qr.push_back(i); + } else { + qd.push_back(i); + } + } + while !qr.is_empty() && !qd.is_empty() { + let r = qr.pop_front().unwrap(); + let d = qd.pop_front().unwrap(); + if r < d { + qr.push_back(r + n); + } else { + qd.push_back(d + n); + } + } + if qr.is_empty() { + "Dire".to_string() + } else { + "Radiant".to_string() + } + } +} +``` From a4ca44ce42d5792a3bf5a473cccd71c76111d34c Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:41:41 +0530 Subject: [PATCH 10/59] Create 2095. Delete the Middle Node of a Linked List.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- ...Delete the Middle Node of a Linked List.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Solution/2095. Delete the Middle Node of a Linked List/2095. Delete the Middle Node of a Linked List.py diff --git a/Solution/2095. Delete the Middle Node of a Linked List/2095. Delete the Middle Node of a Linked List.py b/Solution/2095. Delete the Middle Node of a Linked List/2095. Delete the Middle Node of a Linked List.py new file mode 100644 index 0000000..884d8e9 --- /dev/null +++ b/Solution/2095. Delete the Middle Node of a Linked List/2095. Delete the Middle Node of a Linked List.py @@ -0,0 +1,25 @@ +from typing import Optional + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]: + if not head or not head.next: + return None # If the list is empty or has only one node, return None + + dummy = ListNode(next=head) + slow, fast = dummy, head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + slow.next = slow.next.next # Remove the middle node + return dummy.next \ No newline at end of file From 8f22d0f9eace736e0d4a5e30d2bd7fc57794c243 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:41:58 +0530 Subject: [PATCH 11/59] Update 2095. Delete the Middle Node of a Linked List.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- ...Delete the Middle Node of a Linked List.py | 25 ------------------- 1 file changed, 25 deletions(-) diff --git a/Solution/2095. Delete the Middle Node of a Linked List/2095. Delete the Middle Node of a Linked List.py b/Solution/2095. Delete the Middle Node of a Linked List/2095. Delete the Middle Node of a Linked List.py index 884d8e9..e69de29 100644 --- a/Solution/2095. Delete the Middle Node of a Linked List/2095. Delete the Middle Node of a Linked List.py +++ b/Solution/2095. Delete the Middle Node of a Linked List/2095. Delete the Middle Node of a Linked List.py @@ -1,25 +0,0 @@ -from typing import Optional - -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next - -class ListNode: - def __init__(self, val=0, next=None): - self.val = val - self.next = next - -class Solution: - def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]: - if not head or not head.next: - return None # If the list is empty or has only one node, return None - - dummy = ListNode(next=head) - slow, fast = dummy, head - while fast and fast.next: - slow = slow.next - fast = fast.next.next - slow.next = slow.next.next # Remove the middle node - return dummy.next \ No newline at end of file From d8b9da9c454b6f9fa7ec5ddf6a833643af2023c1 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:42:07 +0530 Subject: [PATCH 12/59] Update 2095. Delete the Middle Node of a Linked List.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- ...095. Delete the Middle Node of a Linked List.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Solution/2095. Delete the Middle Node of a Linked List/2095. Delete the Middle Node of a Linked List.py b/Solution/2095. Delete the Middle Node of a Linked List/2095. Delete the Middle Node of a Linked List.py index e69de29..0c0f583 100644 --- a/Solution/2095. Delete the Middle Node of a Linked List/2095. Delete the Middle Node of a Linked List.py +++ b/Solution/2095. Delete the Middle Node of a Linked List/2095. Delete the Middle Node of a Linked List.py @@ -0,0 +1,14 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(next=head) + slow, fast = dummy, head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + slow.next = slow.next.next + return dummy.next \ No newline at end of file From 644e9942509a717e8398df9250ef2af96425a7ae Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:44:48 +0530 Subject: [PATCH 13/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../readme.md | 216 ++++++++++++++++++ 1 file changed, 216 insertions(+) create mode 100644 Solution/2095. Delete the Middle Node of a Linked List/readme.md diff --git a/Solution/2095. Delete the Middle Node of a Linked List/readme.md b/Solution/2095. Delete the Middle Node of a Linked List/readme.md new file mode 100644 index 0000000..f9a50e7 --- /dev/null +++ b/Solution/2095. Delete the Middle Node of a Linked List/readme.md @@ -0,0 +1,216 @@ +Here's the problem markdown for the problem "2095. Delete the Middle Node of a Linked List": + +```markdown +--- +comments: true +difficulty: Medium +edit_url: https://github.com/doocs/leetcode/edit/main/solution/2000-2099/2095.Delete%20the%20Middle%20Node%20of%20a%20Linked%20List/README_EN.md +rating: 1324 +source: Weekly Contest 270 Q2 +tags: + - Linked List + - Two Pointers +--- + + + +# [2095. Delete the Middle Node of a Linked List](https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list) + +[中文文档](/solution/2000-2099/2095.Delete%20the%20Middle%20Node%20of%20a%20Linked%20List/README.md) + +## Description + + + +

You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.

+ +

The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.

+ +
    +
  • For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.
  • +
+ +

 

+

Example 1:

+ +
+Input: head = [1,3,4,7,1,2,6]
+Output: [1,3,4,1,2,6]
+Explanation:
+The above figure represents the given linked list. The indices of the nodes are written below.
+Since n = 7, node 3 with value 7 is the middle node, which is marked in red.
+We return the new list after removing this node. 
+
+ +

Example 2:

+ +
+Input: head = [1,2,3,4]
+Output: [1,2,4]
+Explanation:
+The above figure represents the given linked list.
+For n = 4, node 2 with value 3 is the middle node, which is marked in red.
+
+ +

Example 3:

+ +
+Input: head = [2,1]
+Output: [2]
+Explanation:
+The above figure represents the given linked list.
+For n = 2, node 1 with value 1 is the middle node, which is marked in red.
+Node 0 with value 2 is the only node remaining after removing node 1.
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is in the range [1, 105].
  • +
  • 1 <= Node.val <= 105
  • +
+ + + +## Solutions + + + +### Solution 1: Fast and Slow Pointers + +The fast and slow pointer technique is a common method used to solve problems related to linked lists. We can maintain two pointers, a slow pointer $\textit{slow}$ and a fast pointer $\textit{fast}$. Initially, $\textit{slow}$ points to a dummy node, whose $\textit{next}$ pointer points to the head node $\textit{head}$ of the list, while $\textit{fast}$ points to the head node $\textit{head}$. + +Then, we move the slow pointer one position backward and the fast pointer two positions backward each time, until the fast pointer reaches the end of the list. At this point, the node next to the node pointed by the slow pointer is the middle node of the list. We can remove the middle node by setting the $\textit{next}$ pointer of the node pointed by the slow pointer to point to the next next node. + +The time complexity is $O(n)$, where $n$ is the length of the list. The space complexity is $O(1)$. + + + +#### Python3 + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(next=head) + slow, fast = dummy, head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + slow.next = slow.next.next + return dummy.next +``` + +#### Java + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode deleteMiddle(ListNode head) { + ListNode dummy = new ListNode(0, head); + ListNode slow = dummy, fast = head; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + slow.next = slow.next.next; + return dummy.next; + } +} +``` + +#### C++ + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* deleteMiddle(ListNode* head) { + ListNode* dummy = new ListNode(0, head); + ListNode* slow = dummy; + ListNode* fast = head; + while (fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + } + slow->next = slow->next->next; + return dummy->next; + } +}; +``` + +#### Go + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func deleteMiddle(head *ListNode) *ListNode { + dummy := &ListNode{Val: 0, Next: head} + slow, fast := dummy, dummy.Next + for fast != nil && fast.Next != nil { + slow, fast = slow.Next, fast.Next.Next + } + slow.Next = slow.Next.Next + return dummy.Next +} +``` + +#### TypeScript + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function deleteMiddle(head: ListNode | null): ListNode | null { + const dummy = new ListNode(0, head); + let [slow, fast] = [dummy, head]; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + slow.next = slow.next.next; + return dummy.next; +} +``` + + + + + + From 88760de265b07c29d194d90d87c15f7df384fee4 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:45:24 +0530 Subject: [PATCH 14/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../readme.md | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/Solution/2095. Delete the Middle Node of a Linked List/readme.md b/Solution/2095. Delete the Middle Node of a Linked List/readme.md index f9a50e7..3c09598 100644 --- a/Solution/2095. Delete the Middle Node of a Linked List/readme.md +++ b/Solution/2095. Delete the Middle Node of a Linked List/readme.md @@ -1,8 +1,10 @@ -Here's the problem markdown for the problem "2095. Delete the Middle Node of a Linked List": -```markdown ---- -comments: true + + + +# [2095. Delete the Middle Node of a Linked List](https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list) + +- **comments**: true difficulty: Medium edit_url: https://github.com/doocs/leetcode/edit/main/solution/2000-2099/2095.Delete%20the%20Middle%20Node%20of%20a%20Linked%20List/README_EN.md rating: 1324 @@ -11,13 +13,6 @@ tags: - Linked List - Two Pointers --- - - - -# [2095. Delete the Middle Node of a Linked List](https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list) - -[中文文档](/solution/2000-2099/2095.Delete%20the%20Middle%20Node%20of%20a%20Linked%20List/README.md) - ## Description From 471ce9f92261bc0dc1aa8a07565166a1e60f84ef Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:46:37 +0530 Subject: [PATCH 15/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../readme.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Solution/2095. Delete the Middle Node of a Linked List/readme.md b/Solution/2095. Delete the Middle Node of a Linked List/readme.md index 3c09598..426fa2e 100644 --- a/Solution/2095. Delete the Middle Node of a Linked List/readme.md +++ b/Solution/2095. Delete the Middle Node of a Linked List/readme.md @@ -5,11 +5,11 @@ # [2095. Delete the Middle Node of a Linked List](https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list) - **comments**: true -difficulty: Medium -edit_url: https://github.com/doocs/leetcode/edit/main/solution/2000-2099/2095.Delete%20the%20Middle%20Node%20of%20a%20Linked%20List/README_EN.md -rating: 1324 -source: Weekly Contest 270 Q2 -tags: +- **difficulty**: Medium + +- **rating**: 1324 +- **source**: Weekly Contest 270 Q2 +- **tags**: - Linked List - Two Pointers --- From 75e629301c969c51aff4808a21c85174a9b53682 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:54:08 +0530 Subject: [PATCH 16/59] Create 328. Odd Even Linked List.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../328. Odd Even Linked List.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Solution/328. Odd Even Linked List/328. Odd Even Linked List.py diff --git a/Solution/328. Odd Even Linked List/328. Odd Even Linked List.py b/Solution/328. Odd Even Linked List/328. Odd Even Linked List.py new file mode 100644 index 0000000..0ec3e81 --- /dev/null +++ b/Solution/328. Odd Even Linked List/328. Odd Even Linked List.py @@ -0,0 +1,18 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: + if head is None: + return None + a = head + b = c = head.next + while b and b.next: + a.next = b.next + a = a.next + b.next = a.next + b = b.next + a.next = c + return head \ No newline at end of file From 7c271bba17aa3964c8c2b3aab90456824f981853 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:54:43 +0530 Subject: [PATCH 17/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/328. Odd Even Linked List/readme.md | 223 +++++++++++++++++++ 1 file changed, 223 insertions(+) create mode 100644 Solution/328. Odd Even Linked List/readme.md diff --git a/Solution/328. Odd Even Linked List/readme.md b/Solution/328. Odd Even Linked List/readme.md new file mode 100644 index 0000000..fff03df --- /dev/null +++ b/Solution/328. Odd Even Linked List/readme.md @@ -0,0 +1,223 @@ +Here is a `README.md` formatted like the example you provided: + +--- + +```markdown +--- +comments: true +difficulty: Medium +edit_url: https://github.com/doocs/leetcode/edit/main/solution/0300-0399/0328.Odd%20Even%20Linked%20List/README_EN.md +tags: + - Linked List +--- + + + +# [328. Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list) + +[中文文档](/solution/0300-0399/0328.Odd%20Even%20Linked%20List/README.md) + +## Description + + + +

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

+ +

The first node is considered odd, and the second node is even, and so on.

+ +

Note that the relative order inside both the even and odd groups should remain as it was in the input.

+ +

You must solve the problem in O(1) extra space complexity and O(n) time complexity.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3,4,5]
+Output: [1,3,5,2,4]
+
+ +

Example 2:

+ +
+Input: head = [2,1,3,5,6,4,7]
+Output: [2,3,6,7,1,5,4]
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the linked list is in the range [0, 104].
  • +
  • -106 <= Node.val <= 106
  • +
+ + + +## Solutions + + + +### Solution 1: Single Pass + +We can use two pointers $a$ and $b$ to represent the tail nodes of the odd and even nodes respectively. Initially, pointer $a$ points to the head node $head$ of the list, and pointer $b$ points to the second node $head.next$ of the list. In addition, we use a pointer $c$ to point to the head node $head.next$ of the even nodes, which is the initial position of pointer $b$. + +We traverse the list, set pointer $a$ to point to the next node of $b$, i.e., $a.next = b.next$, then move pointer $a$ back by one position, i.e., $a = a.next$; set pointer $b$ to point to the next node of $a$, i.e., $b.next = a.next$, then move pointer $b$ back by one position, i.e., $b = b.next$. Continue to traverse until $b$ reaches the end of the list. + +Finally, we set the tail node $a$ of the odd nodes to point to the head node $c$ of the even nodes, i.e., $a.next = c$, then return the head node $head$ of the list. + +The time complexity is $O(n)$, where $n$ is the length of the list, and we need to traverse the list once. The space complexity is $O(1)$. We only need to maintain a limited number of pointers. + + + +#### Python3 + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]: + if head is None: + return None + a = head + b = c = head.next + while b and b.next: + a.next = b.next + a = a.next + b.next = a.next + b = b.next + a.next = c + return head +``` + +#### Java + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode oddEvenList(ListNode head) { + if (head == null) { + return null; + } + ListNode a = head; + ListNode b = head.next, c = b; + while (b != null && b.next != null) { + a.next = b.next; + a = a.next; + b.next = a.next; + b = b.next; + } + a.next = c; + return head; + } +} +``` + +#### C++ + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* oddEvenList(ListNode* head) { + if (!head) { + return nullptr; + } + ListNode* a = head; + ListNode *b = head->next, *c = b; + while (b && b->next) { + a->next = b->next; + a = a->next; + b->next = a->next; + b = b->next; + } + a->next = c; + return head; + } +}; +``` + +#### Go + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func oddEvenList(head *ListNode) *ListNode { + if head == nil { + return nil + } + a := head + b, c := head.Next, head.Next + for b != nil && b.Next != nil { + a.Next = b.Next + a = a.Next + b.Next = a.Next + b = b.Next + } + a.Next = c + return head +} +``` + +#### TypeScript + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ + +function oddEvenList(head: ListNode | null): ListNode | null { + if (!head) { + return null; + } + let [a, b, c] = [head, head.next, head.next]; + while (b && b.next) { + a.next = b.next; + a = a.next; + b.next = a.next; + b = b.next; + } + a.next = c; + return head; +} +``` + + + + + + +``` \ No newline at end of file From a8a67168a3e40cef5c0b7fbeaf8523cd361cfd8d Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:57:27 +0530 Subject: [PATCH 18/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/328. Odd Even Linked List/readme.md | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/Solution/328. Odd Even Linked List/readme.md b/Solution/328. Odd Even Linked List/readme.md index fff03df..a77faa8 100644 --- a/Solution/328. Odd Even Linked List/readme.md +++ b/Solution/328. Odd Even Linked List/readme.md @@ -1,22 +1,15 @@ -Here is a `README.md` formatted like the example you provided: - ---- - -```markdown ---- -comments: true -difficulty: Medium -edit_url: https://github.com/doocs/leetcode/edit/main/solution/0300-0399/0328.Odd%20Even%20Linked%20List/README_EN.md -tags: - - Linked List ---- # [328. Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list) -[中文文档](/solution/0300-0399/0328.Odd%20Even%20Linked%20List/README.md) + +- **comments**: true +- **difficulty**: Medium +- **edit_url**: https://github.com/doocs/leetcode/edit/main/solution/0300-0399/0328.Odd%20Even%20Linked%20List/README_EN.md +tags: + - Linked List ## Description From 46d6c5a2eec1b714702b821cb4b53339221bd2b1 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 17:59:16 +0530 Subject: [PATCH 19/59] Create 206. Reverse Linked List.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../206. Reverse Linked List.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Solution/206. Reverse Linked List/206. Reverse Linked List.py diff --git a/Solution/206. Reverse Linked List/206. Reverse Linked List.py b/Solution/206. Reverse Linked List/206. Reverse Linked List.py new file mode 100644 index 0000000..421d317 --- /dev/null +++ b/Solution/206. Reverse Linked List/206. Reverse Linked List.py @@ -0,0 +1,15 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + dummy = ListNode() + curr = head + while curr: + next = curr.next + curr.next = dummy.next + dummy.next = curr + curr = next + return dummy.next \ No newline at end of file From 822e01e449fadb3b84639d71eba22f88ef51a912 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:00:00 +0530 Subject: [PATCH 20/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/206. Reverse Linked List/readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/206. Reverse Linked List/readme.md diff --git a/Solution/206. Reverse Linked List/readme.md b/Solution/206. Reverse Linked List/readme.md new file mode 100644 index 0000000..e69de29 From bfce5eb5445230ba8548bb112d499ba2587d0725 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:02:39 +0530 Subject: [PATCH 21/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/206. Reverse Linked List/readme.md | 490 ++++++++++++++++++++ 1 file changed, 490 insertions(+) diff --git a/Solution/206. Reverse Linked List/readme.md b/Solution/206. Reverse Linked List/readme.md index e69de29..875f948 100644 --- a/Solution/206. Reverse Linked List/readme.md +++ b/Solution/206. Reverse Linked List/readme.md @@ -0,0 +1,490 @@ + + + +# [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list) + +- **comments**: true +- **difficulty**: Easy +- **edit_url**: https://github.com/doocs/leetcode/edit/main/solution/0200-0299/0206.Reverse%20Linked%20List/README_EN.md +- **tags**: + - Recursion + - Linked List +## Description + + + +

Given the head of a singly linked list, reverse the list, and return the reversed list.

+ +

 

+

Example 1:

+ +
+Input: head = [1,2,3,4,5]
+Output: [5,4,3,2,1]
+
+ +

Example 2:

+ +
+Input: head = [1,2]
+Output: [2,1]
+
+ +

Example 3:

+ +
+Input: head = []
+Output: []
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is the range [0, 5000].
  • +
  • -5000 <= Node.val <= 5000
  • +
+ +

 

+

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

+ + + +## Solutions + + + +### Solution 1: Head Insertion Method + +We create a dummy node $\textit{dummy}$, then traverse the linked list and insert each node after the $\textit{dummy}$ node. After traversal, return $\textit{dummy.next}$. + +The time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$. + + + +#### Python3 + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + dummy = ListNode() + curr = head + while curr: + next = curr.next + curr.next = dummy.next + dummy.next = curr + curr = next + return dummy.next +``` + +#### Java + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + ListNode dummy = new ListNode(); + ListNode curr = head; + while (curr != null) { + ListNode next = curr.next; + curr.next = dummy.next; + dummy.next = curr; + curr = next; + } + return dummy.next; + } +} +``` + +#### C++ + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + ListNode* dummy = new ListNode(); + ListNode* curr = head; + while (curr) { + ListNode* next = curr->next; + curr->next = dummy->next; + dummy->next = curr; + curr = next; + } + return dummy->next; + } +}; +``` + +#### Go + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseList(head *ListNode) *ListNode { + dummy := &ListNode{} + curr := head + for curr != nil { + next := curr.Next + curr.Next = dummy.Next + dummy.Next = curr + curr = next + } + return dummy.Next +} +``` + +#### TypeScript + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function reverseList(head: ListNode | null): ListNode | null { + if (head == null) { + return head; + } + let pre = null; + let cur = head; + while (cur != null) { + const next = cur.next; + cur.next = pre; + [pre, cur] = [cur, next]; + } + return pre; +} +``` + +#### Rust + +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn reverse_list(head: Option>) -> Option> { + let mut head = head; + let mut pre = None; + while let Some(mut node) = head { + head = node.next.take(); + node.next = pre.take(); + pre = Some(node); + } + pre + } +} +``` + +#### JavaScript + +```js +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var reverseList = function (head) { + let dummy = new ListNode(); + let curr = head; + while (curr) { + let next = curr.next; + curr.next = dummy.next; + dummy.next = curr; + curr = next; + } + return dummy.next; +}; +``` + +#### C# + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode ReverseList(ListNode head) { + ListNode dummy = new ListNode(); + ListNode curr = head; + while (curr != null) { + ListNode next = curr.next; + curr.next = dummy.next; + dummy.next = curr; + curr = next; + } + return dummy.next; + } +} +``` + + + + + + + +### Solution 2: Recursion + +We recursively reverse all nodes from the second node to the end of the list, then attach the $head$ to the end of the reversed list. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the linked list. + + + +#### Python3 + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: ListNode) -> ListNode: + if head is None or head.next is None: + return head + ans = self.reverseList(head.next) + head.next.next = head + head.next = None + return ans +``` + +#### Java + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode ans = reverseList(head.next); + head.next.next = head; + head.next = null; + return ans; + } +} +``` + +#### C++ + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if (!head || !head->next) return head; + ListNode* ans = reverseList(head->next); + head->next->next = head; + head->next = nullptr; + return ans; + } +}; +``` + +#### Go + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func reverseList(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + ans := reverseList(head.Next) + head.Next.Next = head + head.Next = nil + return ans +} +``` + +#### TypeScript + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ +const rev = (pre: ListNode | null, cur: ListNode | null): ListNode | null => { + if (cur == null) { + return pre; + } + const next = cur.next; + cur.next = pre; + return rev(cur, next); +}; + +function reverseList(head: ListNode | null): ListNode | null { + if (head == null) { + return head; + } + const next = head.next; + head.next = null; + return rev(head, next); +} +``` + +#### Rust + +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + fn rev(pre: Option>, cur: Option>) -> Option> { + match cur { + None => pre, + Some(mut node) => { + let next = node.next; + node.next = pre; + Self::rev(Some(node), next) + } + } + } + + pub fn reverse_list(head: Option>) -> Option> { + Self::rev(None, head) + } +} +``` + +#### C# + +```cs +/** + * Definition for singly-linked list. + * public class ListNode { + * public int val; + * public ListNode next; + * public ListNode(int val=0, ListNode next=null) { + * this.val = val; + * this.next = next; + * } + * } + */ +public class Solution { + public ListNode ReverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode ans = ReverseList(head.next); + head.next.next = head; + head.next = null; + return ans; + } +} +``` + + + + + + + From f2c1f528031c8006e084b5169447d764e9cea16f Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:04:15 +0530 Subject: [PATCH 22/59] Create 2130. Maximum Twin Sum of a Linked List.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../2130. Maximum Twin Sum of a Linked List.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/2130. Maximum Twin Sum of a Linked List/2130. Maximum Twin Sum of a Linked List.py diff --git a/Solution/2130. Maximum Twin Sum of a Linked List/2130. Maximum Twin Sum of a Linked List.py b/Solution/2130. Maximum Twin Sum of a Linked List/2130. Maximum Twin Sum of a Linked List.py new file mode 100644 index 0000000..e69de29 From 0cdf1a9b7dea3bed6cdf41d4104a849f54bfa913 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:06:16 +0530 Subject: [PATCH 23/59] code code Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- ...2130. Maximum Twin Sum of a Linked List.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Solution/2130. Maximum Twin Sum of a Linked List/2130. Maximum Twin Sum of a Linked List.py b/Solution/2130. Maximum Twin Sum of a Linked List/2130. Maximum Twin Sum of a Linked List.py index e69de29..72ba7fc 100644 --- a/Solution/2130. Maximum Twin Sum of a Linked List/2130. Maximum Twin Sum of a Linked List.py +++ b/Solution/2130. Maximum Twin Sum of a Linked List/2130. Maximum Twin Sum of a Linked List.py @@ -0,0 +1,21 @@ +from typing import Optional + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def pairSum(self, head: Optional[ListNode]) -> int: + s = [] + while head: + s.append(head.val) + head = head.next + n = len(s) + return max(s[i] + s[-(i + 1)] for i in range(n >> 1)) \ No newline at end of file From ca2464ecb85dff2c49e96d47e93d2d3597e15b04 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:07:03 +0530 Subject: [PATCH 24/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/2130. Maximum Twin Sum of a Linked List/readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/2130. Maximum Twin Sum of a Linked List/readme.md diff --git a/Solution/2130. Maximum Twin Sum of a Linked List/readme.md b/Solution/2130. Maximum Twin Sum of a Linked List/readme.md new file mode 100644 index 0000000..e69de29 From 660436afc5068dfdbd46e89a0ad01234e8f806a5 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:10:29 +0530 Subject: [PATCH 25/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../readme.md | 384 ++++++++++++++++++ 1 file changed, 384 insertions(+) diff --git a/Solution/2130. Maximum Twin Sum of a Linked List/readme.md b/Solution/2130. Maximum Twin Sum of a Linked List/readme.md index e69de29..4c46124 100644 --- a/Solution/2130. Maximum Twin Sum of a Linked List/readme.md +++ b/Solution/2130. Maximum Twin Sum of a Linked List/readme.md @@ -0,0 +1,384 @@ + +--- +comments: true +difficulty: Medium +edit_url: https://github.com/doocs/leetcode/edit/main/solution/2100-2199/2130.Maximum%20Twin%20Sum%20of%20a%20Linked%20List/README_EN.md +rating: 1317 +source: Biweekly Contest 69 Q2 +tags: + - Stack + - Linked List + - Two Pointers +--- + + + +# [2130. Maximum Twin Sum of a Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list) + +[中文文档](/solution/2100-2199/2130.Maximum%20Twin%20Sum%20of%20a%20Linked%20List/README.md) + +## Description + + + +

In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1.

+ +
    +
  • For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4.
  • +
+ +

The twin sum is defined as the sum of a node and its twin.

+ +

Given the head of a linked list with even length, return the maximum twin sum of the linked list.

+ +

 

+

Example 1:

+ +
+Input: head = [5,4,2,1]
+Output: 6
+Explanation:
+Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.
+There are no other nodes with twins in the linked list.
+Thus, the maximum twin sum of the linked list is 6. 
+
+ +

Example 2:

+ +
+Input: head = [4,2,2,3]
+Output: 7
+Explanation:
+The nodes with twins present in this linked list are:
+- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.
+- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.
+Thus, the maximum twin sum of the linked list is max(7, 4) = 7. 
+
+ +

Example 3:

+ +
+Input: head = [1,100000]
+Output: 100001
+Explanation:
+There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the list is an even integer in the range [2, 105].
  • +
  • 1 <= Node.val <= 105
  • +
+ + + +## Solutions + + + +### Solution 1 + + + +#### Python3 + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def pairSum(self, head: Optional[ListNode]) -> int: + s = [] + while head: + s.append(head.val) + head = head.next + n = len(s) + return max(s[i] + s[-(i + 1)] for i in range(n >> 1)) +``` + +#### Java + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public int pairSum(ListNode head) { + List s = new ArrayList<>(); + for (; head != null; head = head.next) { + s.add(head.val); + } + int ans = 0, n = s.size(); + for (int i = 0; i < (n >> 1); ++i) { + ans = Math.max(ans, s.get(i) + s.get(n - 1 - i)); + } + return ans; + } +} +``` + +#### C++ + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + int pairSum(ListNode* head) { + vector s; + for (; head != nullptr; head = head->next) s.push_back(head->val); + int ans = 0, n = s.size(); + for (int i = 0; i < (n >> 1); ++i) ans = max(ans, s[i] + s[n - i - 1]); + return ans; + } +}; +``` + +#### Go + +```go +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func pairSum(head *ListNode) int { + var s []int + for ; head != nil; head = head.Next { + s = append(s, head.Val) + } + ans, n := 0, len(s) + for i := 0; i < (n >> 1); i++ { + if ans < s[i]+s[n-i-1] { + ans = s[i] + s[n-i-1] + } + } + return ans +} +``` + +#### TypeScript + +```ts +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function pairSum(head: ListNode | null): number { + const arr = []; + let node = head; + while (node) { + arr.push(node.val); + node = node.next; + } + const n = arr.length; + let ans = 0; + for (let i = 0; i < n >> 1; i++) { + ans = Math.max(ans, arr[i] + arr[n - 1 - i]); + } + return ans; +} +``` + +#### Rust + +```rust +// Definition for singly-linked list. +// #[derive(PartialEq, Eq, Clone, Debug)] +// pub struct ListNode { +// pub val: i32, +// pub next: Option> +// } +// +// impl ListNode { +// #[inline] +// fn new(val: i32) -> Self { +// ListNode { +// next: None, +// val +// } +// } +// } +impl Solution { + pub fn pair_sum(head: Option>) -> i32 { + let mut arr = Vec::new(); + let mut node = &head; + while node.is_some() { + let t = node.as_ref().unwrap(); + arr.push(t.val); + node = &t.next; + } + let n = arr.len(); + let mut ans = 0; + for i in 0..n >> 1 { + ans = ans.max(arr[i] + arr[n - 1 - i]); + } + ans + } +} +``` + + + + + + + +### Solution 2 + + + +#### Python3 + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def pairSum(self, head: Optional[ListNode]) -> int: + def reverse(head): + dummy = ListNode() + curr = head + while curr: + next = curr.next + curr.next = dummy.next + dummy.next = curr + curr = next + return dummy.next + + slow, fast = head, head.next + while fast and fast.next: + slow, fast = slow.next, fast.next.next + pa = head + q = slow.next + slow.next = None + pb = reverse(q) + ans = 0 + while pa and pb: + ans = max(ans, pa.val + pb.val) + pa = pa.next + pb = pb.next + return ans +``` + +#### Java + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode() {} + * ListNode(int val) { this.val = val; } + * ListNode(int val, ListNode next) { this.val = val; this.next = next; } + * } + */ +class Solution { + public int pairSum(ListNode head) { + ListNode slow = head; + ListNode fast = head.next; + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + } + ListNode pa = head; + ListNode q = slow.next; + slow.next = null; + ListNode pb = reverse(q); + int ans = 0; + while (pa != null) { + ans = Math.max(ans, pa.val + pb.val); + pa = pa.next; + pb = pb.next; + } + return ans; + } + + private ListNode reverse(ListNode head) { + ListNode dummy = new ListNode(); + ListNode curr = head; + while (curr != null) { + ListNode next = curr.next; + curr.next = dummy.next; + dummy.next = curr; + curr = next; + } + return dummy.next; + } +} +``` + +#### C++ + +```cpp +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + int pairSum(ListNode* head) { + ListNode* slow = head; + ListNode* fast = head->next; + while (fast && fast->next) { + slow = slow->next; + fast = fast->next->next; + } + ListNode* pa = head; + ListNode* q = slow->next; + slow->next = nullptr; + ListNode* pb = reverse(q); + int ans = 0; + while (pa) { + ans = max(ans, pa->val + pb->val); + pa = pa->next; + pb = pb->next; + } + return ans; + } + + ListNode* reverse(ListNode* head) { + ListNode* dummy = new ListNode(); + ListNode* curr = head; + while (curr) { + ListNode* next = curr->next; + curr->next = dummy->next; + \ No newline at end of file From 942e12ca575384f86181a0654d43174771e7cf69 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:11:15 +0530 Subject: [PATCH 26/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../readme.md | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/Solution/2130. Maximum Twin Sum of a Linked List/readme.md b/Solution/2130. Maximum Twin Sum of a Linked List/readme.md index 4c46124..922db67 100644 --- a/Solution/2130. Maximum Twin Sum of a Linked List/readme.md +++ b/Solution/2130. Maximum Twin Sum of a Linked List/readme.md @@ -1,4 +1,9 @@ + + +# [2130. Maximum Twin Sum of a Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list) + + --- comments: true difficulty: Medium @@ -9,14 +14,6 @@ tags: - Stack - Linked List - Two Pointers ---- - - - -# [2130. Maximum Twin Sum of a Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list) - -[中文文档](/solution/2100-2199/2130.Maximum%20Twin%20Sum%20of%20a%20Linked%20List/README.md) - ## Description From 966455210925e00d655cb15bd28cd7f463cd1803 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:13:33 +0530 Subject: [PATCH 27/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../readme.md | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/Solution/2130. Maximum Twin Sum of a Linked List/readme.md b/Solution/2130. Maximum Twin Sum of a Linked List/readme.md index 922db67..0ab6a2f 100644 --- a/Solution/2130. Maximum Twin Sum of a Linked List/readme.md +++ b/Solution/2130. Maximum Twin Sum of a Linked List/readme.md @@ -1,16 +1,14 @@ - - # [2130. Maximum Twin Sum of a Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list) --- -comments: true -difficulty: Medium -edit_url: https://github.com/doocs/leetcode/edit/main/solution/2100-2199/2130.Maximum%20Twin%20Sum%20of%20a%20Linked%20List/README_EN.md -rating: 1317 -source: Biweekly Contest 69 Q2 -tags: +- **comments**: true +- **difficulty**: Medium +- **edit_url**: https://github.com/doocs/leetcode/edit/main/solution/2100-2199/2130.Maximum%20Twin%20Sum%20of%20a%20Linked%20List/README_EN.md +- **rating**: 1317 +- **source**: Biweekly Contest 69 Q2 +- **tags**: - Stack - Linked List - Two Pointers From 153dfe59ed7e9a27a0dfc445d6d8c6858dd3c571 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:16:37 +0530 Subject: [PATCH 28/59] Create 104. Maximum Depth of Binary Tree.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../104. Maximum Depth of Binary Tree.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree.py diff --git a/Solution/104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree.py b/Solution/104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree.py new file mode 100644 index 0000000..e69de29 From 37aad9aa45d3adfc29e870fe3a7822684feddb37 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:16:47 +0530 Subject: [PATCH 29/59] Update 104. Maximum Depth of Binary Tree.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../104. Maximum Depth of Binary Tree.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Solution/104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree.py b/Solution/104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree.py index e69de29..bfb9230 100644 --- a/Solution/104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree.py +++ b/Solution/104. Maximum Depth of Binary Tree/104. Maximum Depth of Binary Tree.py @@ -0,0 +1,12 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + l, r = self.maxDepth(root.left), self.maxDepth(root.right) + return 1 + max(l, r) \ No newline at end of file From d2beb068dac45a9776c99f84173fe5b7b1429999 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:20:45 +0530 Subject: [PATCH 30/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../readme.md | 268 ++++++++++++++++++ 1 file changed, 268 insertions(+) create mode 100644 Solution/104. Maximum Depth of Binary Tree/readme.md diff --git a/Solution/104. Maximum Depth of Binary Tree/readme.md b/Solution/104. Maximum Depth of Binary Tree/readme.md new file mode 100644 index 0000000..43b9ad1 --- /dev/null +++ b/Solution/104. Maximum Depth of Binary Tree/readme.md @@ -0,0 +1,268 @@ +--- +comments: true +difficulty: Easy +edit_url: https://github.com/doocs/leetcode/edit/main/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/README_EN.md +tags: + - Tree + - Depth-First Search + - Breadth-First Search + - Binary Tree +--- + + + +# [104. Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree) + +[中文文档](/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/README.md) + +## Description + + + +

Given the root of a binary tree, return its maximum depth.

+ +

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

+ +

 

+

Example 1:

+ +
+Input: root = [3,9,20,null,null,15,7]
+Output: 3
+
+ +

Example 2:

+ +
+Input: root = [1,null,2]
+Output: 2
+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 104].
  • +
  • -100 <= Node.val <= 100
  • +
+ + + +## Solutions + + + +### Solution 1: Recursion + +Recursively traverse the left and right subtrees, calculate the maximum depth of the left and right subtrees, and then take the maximum value plus $1$. + +The time complexity is $O(n)$, where $n$ is the number of nodes in the binary tree. Each node is traversed only once in the recursion. + + + +#### Python3 + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxDepth(self, root: TreeNode) -> int: + if root is None: + return 0 + l, r = self.maxDepth(root.left), self.maxDepth(root.right) + return 1 + max(l, r) +``` + +#### Java + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public int maxDepth(TreeNode root) { + if (root == null) { + return 0; + } + int l = maxDepth(root.left); + int r = maxDepth(root.right); + return 1 + Math.max(l, r); + } +} +``` + +#### C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int maxDepth(TreeNode* root) { + if (!root) return 0; + int l = maxDepth(root->left), r = maxDepth(root->right); + return 1 + max(l, r); + } +}; +``` + +#### Go + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func maxDepth(root *TreeNode) int { + if root == nil { + return 0 + } + l, r := maxDepth(root.Left), maxDepth(root.Right) + return 1 + max(l, r) +} +``` + +#### TypeScript + +```ts +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function maxDepth(root: TreeNode | null): number { + if (root === null) { + return 0; + } + return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); +} +``` + +#### Rust + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None +// } +// } +// } +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + fn dfs(root: &Option>>) -> i32 { + if root.is_none() { + return 0; + } + let node = root.as_ref().unwrap().borrow(); + 1 + Self::dfs(&node.left).max(Self::dfs(&node.right)) + } + + pub fn max_depth(root: Option>>) -> i32 { + Self::dfs(&root) + } +} +``` + +#### JavaScript + +```js +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var maxDepth = function (root) { + if (!root) return 0; + const l = maxDepth(root.left); + const r = maxDepth(root.right); + return 1 + Math.max(l, r); +}; +``` + +#### C + +```c +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +#define max(a, b) (((a) > (b)) ? (a) : (b)) + +int maxDepth(struct TreeNode* root) { + if (!root) { + return 0; + } + int left = maxDepth(root->left); + int right = maxDepth(root->right); + return 1 + max(left, right); +} +``` + + + + + + \ No newline at end of file From 4a4be2700a0f8741c074c4963f6ae9fbb6d7ff59 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:21:29 +0530 Subject: [PATCH 31/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/104. Maximum Depth of Binary Tree/readme.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Solution/104. Maximum Depth of Binary Tree/readme.md b/Solution/104. Maximum Depth of Binary Tree/readme.md index 43b9ad1..9ec9ef1 100644 --- a/Solution/104. Maximum Depth of Binary Tree/readme.md +++ b/Solution/104. Maximum Depth of Binary Tree/readme.md @@ -1,3 +1,8 @@ + + + +# [104. Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree) + --- comments: true difficulty: Easy @@ -9,11 +14,6 @@ tags: - Binary Tree --- - - -# [104. Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree) - -[中文文档](/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/README.md) ## Description From b8de5a14d023ea914b4803fc532e1d76e4a067ac Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:22:35 +0530 Subject: [PATCH 32/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/104. Maximum Depth of Binary Tree/readme.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Solution/104. Maximum Depth of Binary Tree/readme.md b/Solution/104. Maximum Depth of Binary Tree/readme.md index 9ec9ef1..6d8e3df 100644 --- a/Solution/104. Maximum Depth of Binary Tree/readme.md +++ b/Solution/104. Maximum Depth of Binary Tree/readme.md @@ -4,10 +4,10 @@ # [104. Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree) --- -comments: true -difficulty: Easy -edit_url: https://github.com/doocs/leetcode/edit/main/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/README_EN.md -tags: +- **comments**: true +- **difficulty**: Easy +- **edit_url**: https://github.com/doocs/leetcode/edit/main/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/README_EN.md +- **tags**: - Tree - Depth-First Search - Breadth-First Search From d57461be4093c5ee47cedb08c1e2962761517ecc Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:24:00 +0530 Subject: [PATCH 33/59] Create 872. Leaf-Similar Trees.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/872. Leaf-Similar Trees/872. Leaf-Similar Trees.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/872. Leaf-Similar Trees/872. Leaf-Similar Trees.py diff --git a/Solution/872. Leaf-Similar Trees/872. Leaf-Similar Trees.py b/Solution/872. Leaf-Similar Trees/872. Leaf-Similar Trees.py new file mode 100644 index 0000000..e69de29 From f9a0f4876b83db88c4801ba4517fa46f17c9766e Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:25:00 +0530 Subject: [PATCH 34/59] Update 872. Leaf-Similar Trees.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../872. Leaf-Similar Trees.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Solution/872. Leaf-Similar Trees/872. Leaf-Similar Trees.py b/Solution/872. Leaf-Similar Trees/872. Leaf-Similar Trees.py index e69de29..c6aba6d 100644 --- a/Solution/872. Leaf-Similar Trees/872. Leaf-Similar Trees.py +++ b/Solution/872. Leaf-Similar Trees/872. Leaf-Similar Trees.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: + def dfs(root: Optional[TreeNode], nums: List[int]) -> None: + if root.left == root.right: + nums.append(root.val) + return + if root.left: + dfs(root.left, nums) + if root.right: + dfs(root.right, nums) + + l1, l2 = [], [] + dfs(root1, l1) + dfs(root2, l2) + return l1 == l2 \ No newline at end of file From 8214da8fc93b6e0a7bd38fbfa511f25fda264ba4 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:25:32 +0530 Subject: [PATCH 35/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/872. Leaf-Similar Trees/readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/872. Leaf-Similar Trees/readme.md diff --git a/Solution/872. Leaf-Similar Trees/readme.md b/Solution/872. Leaf-Similar Trees/readme.md new file mode 100644 index 0000000..e69de29 From 7a0c0573ad4247418bbeb8619fc2f272599d4f49 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:25:42 +0530 Subject: [PATCH 36/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/872. Leaf-Similar Trees/readme.md | 221 +++++++++++++++++++++ 1 file changed, 221 insertions(+) diff --git a/Solution/872. Leaf-Similar Trees/readme.md b/Solution/872. Leaf-Similar Trees/readme.md index e69de29..96d9ad3 100644 --- a/Solution/872. Leaf-Similar Trees/readme.md +++ b/Solution/872. Leaf-Similar Trees/readme.md @@ -0,0 +1,221 @@ +Here is the complete LeetCode-style `README.md` for **872. Leaf-Similar Trees**, following the format you've requested (similar to `doocs/leetcode`): + +--- + +```markdown +# 872. Leaf-Similar Trees + +> Difficulty: Easy +> Tags: Tree, Depth-First Search, Binary Tree +> Link: [LeetCode Problem](https://leetcode.com/problems/leaf-similar-trees) + +## Description + +Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a **leaf value sequence**. + +Two binary trees are considered **leaf-similar** if their leaf value sequences are the same. + +Return `true` if and only if the two given trees with head nodes `root1` and `root2` are leaf-similar. + +### Example 1: + +![example1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0800-0899/0872.Leaf-Similar%20Trees/images/leaf-similar-1.jpg) + +``` +Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8] +Output: true +``` + +### Example 2: + +![example2](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0800-0899/0872.Leaf-Similar%20Trees/images/leaf-similar-2.jpg) + +``` +Input: root1 = [1,2,3], root2 = [1,3,2] +Output: false +``` + +## Constraints + +- The number of nodes in each tree will be in the range `[1, 200]`. +- Both of the given trees will have values in the range `[0, 200]`. + +--- + +## Solutions + +### Approach 1: DFS + +We can perform a depth-first search (DFS) to collect the leaf values of each tree. If the leaf value sequences of both trees are the same, then the trees are leaf-similar. + +**Time Complexity:** O(n) +**Space Complexity:** O(n) + +--- + +### Python3 + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool: + def dfs(root: Optional[TreeNode], nums: List[int]) -> None: + if root.left == root.right: + nums.append(root.val) + return + if root.left: + dfs(root.left, nums) + if root.right: + dfs(root.right, nums) + + l1, l2 = [], [] + dfs(root1, l1) + dfs(root2, l2) + return l1 == l2 +``` + +--- + +### Java + +```java +class Solution { + public boolean leafSimilar(TreeNode root1, TreeNode root2) { + List l1 = new ArrayList<>(); + List l2 = new ArrayList<>(); + dfs(root1, l1); + dfs(root2, l2); + return l1.equals(l2); + } + + private void dfs(TreeNode root, List nums) { + if (root.left == root.right) { + nums.add(root.val); + return; + } + if (root.left != null) dfs(root.left, nums); + if (root.right != null) dfs(root.right, nums); + } +} +``` + +--- + +### C++ + +```cpp +class Solution { +public: + bool leafSimilar(TreeNode* root1, TreeNode* root2) { + vector l1, l2; + dfs(root1, l1); + dfs(root2, l2); + return l1 == l2; + } + + void dfs(TreeNode* root, vector& nums) { + if (root->left == root->right) { + nums.push_back(root->val); + return; + } + if (root->left) dfs(root->left, nums); + if (root->right) dfs(root->right, nums); + } +}; +``` + +--- + +### Go + +```go +func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { + l1, l2 := []int{}, []int{} + var dfs func(*TreeNode, *[]int) + dfs = func(root *TreeNode, nums *[]int) { + if root.Left == root.Right { + *nums = append(*nums, root.Val) + return + } + if root.Left != nil { + dfs(root.Left, nums) + } + if root.Right != nil { + dfs(root.Right, nums) + } + } + dfs(root1, &l1) + dfs(root2, &l2) + return reflect.DeepEqual(l1, l2) +} +``` + +--- + +### Rust + +```rust +use std::cell::RefCell; +use std::rc::Rc; + +impl Solution { + pub fn leaf_similar( + root1: Option>>, + root2: Option>>, + ) -> bool { + let mut l1 = Vec::new(); + let mut l2 = Vec::new(); + Self::dfs(&root1, &mut l1); + Self::dfs(&root2, &mut l2); + l1 == l2 + } + + fn dfs(node: &Option>>, nums: &mut Vec) { + if let Some(n) = node { + let n = n.borrow(); + if n.left.is_none() && n.right.is_none() { + nums.push(n.val); + return; + } + if n.left.is_some() { + Self::dfs(&n.left, nums); + } + if n.right.is_some() { + Self::dfs(&n.right, nums); + } + } + } +} +``` + +--- + +### JavaScript + +```javascript +var leafSimilar = function (root1, root2) { + const l1 = []; + const l2 = []; + const dfs = (root, nums) => { + if (root.left === root.right) { + nums.push(root.val); + return; + } + if (root.left) dfs(root.left, nums); + if (root.right) dfs(root.right, nums); + }; + dfs(root1, l1); + dfs(root2, l2); + return l1.join(',') === l2.join(','); +}; +``` + +--- +``` + +Let me know if you'd like a download link or the file packaged for a GitHub-style repo. \ No newline at end of file From 127fe4f54ef6282f0986bb8f38f518072b7ccf4f Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:26:47 +0530 Subject: [PATCH 37/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/872. Leaf-Similar Trees/readme.md | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/Solution/872. Leaf-Similar Trees/readme.md b/Solution/872. Leaf-Similar Trees/readme.md index 96d9ad3..61aeafa 100644 --- a/Solution/872. Leaf-Similar Trees/readme.md +++ b/Solution/872. Leaf-Similar Trees/readme.md @@ -1,13 +1,9 @@ -Here is the complete LeetCode-style `README.md` for **872. Leaf-Similar Trees**, following the format you've requested (similar to `doocs/leetcode`): ---- - -```markdown # 872. Leaf-Similar Trees -> Difficulty: Easy -> Tags: Tree, Depth-First Search, Binary Tree -> Link: [LeetCode Problem](https://leetcode.com/problems/leaf-similar-trees) +> **Difficulty**: Easy +> **Tags**: Tree, Depth-First Search, Binary Tree +> **Link**: [LeetCode Problem](https://leetcode.com/problems/leaf-similar-trees) ## Description @@ -216,6 +212,3 @@ var leafSimilar = function (root1, root2) { ``` --- -``` - -Let me know if you'd like a download link or the file packaged for a GitHub-style repo. \ No newline at end of file From 4e61cf17f90daa9954aa959d6d790ad268d3b0ff Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:28:16 +0530 Subject: [PATCH 38/59] Create 1448. Count Good Nodes in Binary Tree.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../1448. Count Good Nodes in Binary Tree.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/1448. Count Good Nodes in Binary Tree/1448. Count Good Nodes in Binary Tree.py diff --git a/Solution/1448. Count Good Nodes in Binary Tree/1448. Count Good Nodes in Binary Tree.py b/Solution/1448. Count Good Nodes in Binary Tree/1448. Count Good Nodes in Binary Tree.py new file mode 100644 index 0000000..e69de29 From 5fc0e7ae934d27712e5ea78c598e185e0d7ef534 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:29:28 +0530 Subject: [PATCH 39/59] Update 1448. Count Good Nodes in Binary Tree.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../1448. Count Good Nodes in Binary Tree.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Solution/1448. Count Good Nodes in Binary Tree/1448. Count Good Nodes in Binary Tree.py b/Solution/1448. Count Good Nodes in Binary Tree/1448. Count Good Nodes in Binary Tree.py index e69de29..98e12fd 100644 --- a/Solution/1448. Count Good Nodes in Binary Tree/1448. Count Good Nodes in Binary Tree.py +++ b/Solution/1448. Count Good Nodes in Binary Tree/1448. Count Good Nodes in Binary Tree.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def goodNodes(self, root: TreeNode) -> int: + def dfs(root: TreeNode, mx: int): + if root is None: + return + nonlocal ans + if mx <= root.val: + ans += 1 + mx = root.val + dfs(root.left, mx) + dfs(root.right, mx) + + ans = 0 + dfs(root, -1000000) + return ans \ No newline at end of file From 51cb612077b077bc7be3ec8bef92f1c5a9cc16a9 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:30:31 +0530 Subject: [PATCH 40/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/1448. Count Good Nodes in Binary Tree/readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/1448. Count Good Nodes in Binary Tree/readme.md diff --git a/Solution/1448. Count Good Nodes in Binary Tree/readme.md b/Solution/1448. Count Good Nodes in Binary Tree/readme.md new file mode 100644 index 0000000..e69de29 From 399239436697bc6c8679bc7aa95ac277255292c3 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:30:46 +0530 Subject: [PATCH 41/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../readme.md | 225 ++++++++++++++++++ 1 file changed, 225 insertions(+) diff --git a/Solution/1448. Count Good Nodes in Binary Tree/readme.md b/Solution/1448. Count Good Nodes in Binary Tree/readme.md index e69de29..639bbf9 100644 --- a/Solution/1448. Count Good Nodes in Binary Tree/readme.md +++ b/Solution/1448. Count Good Nodes in Binary Tree/readme.md @@ -0,0 +1,225 @@ +Sure! Here's the full `README.md` file for **LeetCode Problem 1448. Count Good Nodes in Binary Tree**, following the exact style you requested, like the `doocs/leetcode` GitHub repo: + +--- + +```markdown +# [1448. Count Good Nodes in Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree) + +> Difficulty: Medium +> Biweekly Contest 26 Q3 +> Tags: Tree, Depth-First Search, Breadth-First Search, Binary Tree + +## Description + +Given a binary tree `root`, a node **X** in the tree is named **good** if in the path from root to **X** there are no nodes with a value **greater than** X. + +Return the number of **good** nodes in the binary tree. + +### Example 1: + +![example1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1400-1499/1448.Count%20Good%20Nodes%20in%20Binary%20Tree/images/test_sample_1.png) + +``` +Input: root = [3,1,4,3,null,1,5] +Output: 4 +Explanation: Nodes in blue are good. +Root Node (3) is always a good node. +Node 4 -> (3,4) is the maximum value in the path starting from the root. +Node 5 -> (3,4,5) is the maximum value in the path +Node 3 -> (3,1,3) is the maximum value in the path. +``` + +### Example 2: + +![example2](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1400-1499/1448.Count%20Good%20Nodes%20in%20Binary%20Tree/images/test_sample_2.png) + +``` +Input: root = [3,3,null,4,2] +Output: 3 +Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it. +``` + +### Example 3: + +``` +Input: root = [1] +Output: 1 +Explanation: Root is considered as good. +``` + +### Constraints: + +- The number of nodes in the binary tree is in the range `[1, 10^5]`. +- Each node's value is between `[-10^4, 10^4]`. + +## Solutions + +### Python3 + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def goodNodes(self, root: TreeNode) -> int: + def dfs(root: TreeNode, mx: int): + if root is None: + return + nonlocal ans + if mx <= root.val: + ans += 1 + mx = root.val + dfs(root.left, mx) + dfs(root.right, mx) + + ans = 0 + dfs(root, -1000000) + return ans +``` + +### Java + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int ans = 0; + + public int goodNodes(TreeNode root) { + dfs(root, -100000); + return ans; + } + + private void dfs(TreeNode root, int mx) { + if (root == null) { + return; + } + if (mx <= root.val) { + ++ans; + mx = root.val; + } + dfs(root.left, mx); + dfs(root.right, mx); + } +} +``` + +### C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int goodNodes(TreeNode* root) { + int ans = 0; + function dfs = [&](TreeNode* root, int mx) { + if (!root) { + return; + } + if (mx <= root->val) { + ++ans; + mx = root->val; + } + dfs(root->left, mx); + dfs(root->right, mx); + }; + dfs(root, -1e6); + return ans; + } +}; +``` + +### Go + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func goodNodes(root *TreeNode) (ans int) { + var dfs func(*TreeNode, int) + dfs = func(root *TreeNode, mx int) { + if root == nil { + return + } + if mx <= root.Val { + ans++ + mx = root.Val + } + dfs(root.Left, mx) + dfs(root.Right, mx) + } + dfs(root, -10001) + return +} +``` + +### TypeScript + +```ts +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function goodNodes(root: TreeNode | null): number { + let ans = 0; + const dfs = (root: TreeNode | null, mx: number) => { + if (!root) { + return; + } + if (mx <= root.val) { + ++ans; + mx = root.val; + } + dfs(root.left, mx); + dfs(root.right, mx); + }; + dfs(root, -1e6); + return ans; +} +``` +``` + +--- + +Let me know if you want the Chinese version (`README.md`) or to continue with more problems in this format! \ No newline at end of file From 1b86445b97a6b1bbba6b281eef7e715e454e4863 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:31:11 +0530 Subject: [PATCH 42/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/1448. Count Good Nodes in Binary Tree/readme.md | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Solution/1448. Count Good Nodes in Binary Tree/readme.md b/Solution/1448. Count Good Nodes in Binary Tree/readme.md index 639bbf9..6e78ab8 100644 --- a/Solution/1448. Count Good Nodes in Binary Tree/readme.md +++ b/Solution/1448. Count Good Nodes in Binary Tree/readme.md @@ -1,8 +1,4 @@ -Sure! Here's the full `README.md` file for **LeetCode Problem 1448. Count Good Nodes in Binary Tree**, following the exact style you requested, like the `doocs/leetcode` GitHub repo: ---- - -```markdown # [1448. Count Good Nodes in Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree) > Difficulty: Medium @@ -220,6 +216,3 @@ function goodNodes(root: TreeNode | null): number { ``` ``` ---- - -Let me know if you want the Chinese version (`README.md`) or to continue with more problems in this format! \ No newline at end of file From 85eba4ef9d2802aff1fee5e5423950d28b543251 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:31:56 +0530 Subject: [PATCH 43/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/1448. Count Good Nodes in Binary Tree/readme.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Solution/1448. Count Good Nodes in Binary Tree/readme.md b/Solution/1448. Count Good Nodes in Binary Tree/readme.md index 6e78ab8..f207ad1 100644 --- a/Solution/1448. Count Good Nodes in Binary Tree/readme.md +++ b/Solution/1448. Count Good Nodes in Binary Tree/readme.md @@ -1,9 +1,9 @@ # [1448. Count Good Nodes in Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree) -> Difficulty: Medium -> Biweekly Contest 26 Q3 -> Tags: Tree, Depth-First Search, Breadth-First Search, Binary Tree +> **Difficulty**: Medium +> **Biweekly Contest** 26 Q3 +> **Tags**: Tree, Depth-First Search, Breadth-First Search, Binary Tree ## Description From 144b3f29ca3be66573f5c165751b6414d1c82cda Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:33:02 +0530 Subject: [PATCH 44/59] Create 437. Path Sum III.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/437. Path Sum III/437. Path Sum III.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/437. Path Sum III/437. Path Sum III.py diff --git a/Solution/437. Path Sum III/437. Path Sum III.py b/Solution/437. Path Sum III/437. Path Sum III.py new file mode 100644 index 0000000..e69de29 From 9fc52c45dd0587784d2a2e1f8b4f684c5f3c77ce Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:33:56 +0530 Subject: [PATCH 45/59] Update 437. Path Sum III.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../437. Path Sum III/437. Path Sum III.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Solution/437. Path Sum III/437. Path Sum III.py b/Solution/437. Path Sum III/437. Path Sum III.py index e69de29..73821aa 100644 --- a/Solution/437. Path Sum III/437. Path Sum III.py +++ b/Solution/437. Path Sum III/437. Path Sum III.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int: + def dfs(node, s): + if node is None: + return 0 + s += node.val + ans = cnt[s - targetSum] + cnt[s] += 1 + ans += dfs(node.left, s) + ans += dfs(node.right, s) + cnt[s] -= 1 + return ans + + cnt = Counter({0: 1}) + return dfs(root, 0) \ No newline at end of file From ae5091a4c3f961d7123e4e6c47a51fd5010396b8 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:34:35 +0530 Subject: [PATCH 46/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/437. Path Sum III/readme.md | 250 +++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 Solution/437. Path Sum III/readme.md diff --git a/Solution/437. Path Sum III/readme.md b/Solution/437. Path Sum III/readme.md new file mode 100644 index 0000000..1b7d2e4 --- /dev/null +++ b/Solution/437. Path Sum III/readme.md @@ -0,0 +1,250 @@ +Sure! Here's the complete LeetCode-style `README.md` file for **437. Path Sum III**, in the format consistent with the ones from the `doocs/leetcode` GitHub repository. + +--- + +```markdown +# 437. Path Sum III + +## Description + +Given the `root` of a binary tree and an integer `targetSum`, return *the number of paths where the sum of the values along the path equals* `targetSum`. + +The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). + +### Example 1: + +![example1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0437.Path%20Sum%20III/images/pathsum3-1-tree.jpg) + +``` +Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 +Output: 3 +Explanation: The paths that sum to 8 are shown. +``` + +### Example 2: + +``` +Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 +Output: 3 +``` + +### Constraints: + +- The number of nodes in the tree is in the range `[0, 1000]`. +- `-10⁹ <= Node.val <= 10⁹` +- `-1000 <= targetSum <= 1000` + +--- + +## Solutions + +### Solution: Prefix Sum + DFS + +We traverse the tree using depth-first search while maintaining a prefix sum and storing its frequency in a hash map. If at any point the difference between the current prefix sum and `targetSum` exists in the map, it means there is a path that sums up to the target. + +Time complexity: `O(n)` +Space complexity: `O(n)` +Where `n` is the number of nodes in the binary tree. + +--- + +### Python3 + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +from collections import Counter + +class Solution: + def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int: + def dfs(node, s): + if not node: + return 0 + s += node.val + ans = cnt[s - targetSum] + cnt[s] += 1 + ans += dfs(node.left, s) + ans += dfs(node.right, s) + cnt[s] -= 1 + return ans + + cnt = Counter({0: 1}) + return dfs(root, 0) +``` + +### Java + +```java +class Solution { + private Map cnt = new HashMap<>(); + private int targetSum; + + public int pathSum(TreeNode root, int targetSum) { + cnt.put(0L, 1); + this.targetSum = targetSum; + return dfs(root, 0); + } + + private int dfs(TreeNode node, long s) { + if (node == null) return 0; + s += node.val; + int ans = cnt.getOrDefault(s - targetSum, 0); + cnt.put(s, cnt.getOrDefault(s, 0) + 1); + ans += dfs(node.left, s) + dfs(node.right, s); + cnt.put(s, cnt.get(s) - 1); + return ans; + } +} +``` + +### C++ + +```cpp +class Solution { +public: + int pathSum(TreeNode* root, int targetSum) { + unordered_map cnt; + cnt[0] = 1; + return dfs(root, 0, targetSum, cnt); + } + + int dfs(TreeNode* node, long long s, int targetSum, unordered_map& cnt) { + if (!node) return 0; + s += node->val; + int ans = cnt[s - targetSum]; + cnt[s]++; + ans += dfs(node->left, s, targetSum, cnt); + ans += dfs(node->right, s, targetSum, cnt); + cnt[s]--; + return ans; + } +}; +``` + +### JavaScript + +```js +var pathSum = function (root, targetSum) { + const cnt = new Map(); + const dfs = (node, s) => { + if (!node) return 0; + s += node.val; + let ans = cnt.get(s - targetSum) || 0; + cnt.set(s, (cnt.get(s) || 0) + 1); + ans += dfs(node.left, s) + dfs(node.right, s); + cnt.set(s, cnt.get(s) - 1); + return ans; + }; + cnt.set(0, 1); + return dfs(root, 0); +}; +``` + +### TypeScript + +```ts +function pathSum(root: TreeNode | null, targetSum: number): number { + const cnt: Map = new Map(); + const dfs = (node: TreeNode | null, s: number): number => { + if (!node) return 0; + s += node.val; + let ans = cnt.get(s - targetSum) ?? 0; + cnt.set(s, (cnt.get(s) ?? 0) + 1); + ans += dfs(node.left, s) + dfs(node.right, s); + cnt.set(s, (cnt.get(s) ?? 0) - 1); + return ans; + }; + cnt.set(0, 1); + return dfs(root, 0); +} +``` + +### Go + +```go +func pathSum(root *TreeNode, targetSum int) int { + cnt := map[int]int{0: 1} + var dfs func(*TreeNode, int) int + dfs = func(node *TreeNode, s int) int { + if node == nil { + return 0 + } + s += node.Val + ans := cnt[s-targetSum] + cnt[s]++ + ans += dfs(node.Left, s) + dfs(node.Right, s) + cnt[s]-- + return ans + } + return dfs(root, 0) +} +``` + +### C# + +```cs +public class Solution { + public int PathSum(TreeNode root, int targetSum) { + Dictionary cnt = new Dictionary(); + + int Dfs(TreeNode node, long s) { + if (node == null) return 0; + s += node.val; + int ans = cnt.GetValueOrDefault(s - targetSum, 0); + cnt[s] = cnt.GetValueOrDefault(s, 0) + 1; + ans += Dfs(node.left, s); + ans += Dfs(node.right, s); + cnt[s]--; + return ans; + } + + cnt[0] = 1; + return Dfs(root, 0); + } +} +``` + +### Rust + +```rust +use std::rc::Rc; +use std::cell::RefCell; +use std::collections::HashMap; + +impl Solution { + pub fn path_sum(root: Option>>, target_sum: i32) -> i32 { + let mut cnt = HashMap::new(); + cnt.insert(0, 1); + + fn dfs(node: Option>>, s: i64, target: i64, cnt: &mut HashMap) -> i32 { + if let Some(n) = node { + let n = n.borrow(); + let s = s + n.val as i64; + let ans = cnt.get(&(s - target)).copied().unwrap_or(0); + *cnt.entry(s).or_insert(0) += 1; + let ans = ans + dfs(n.left.clone(), s, target, cnt) + dfs(n.right.clone(), s, target, cnt); + *cnt.get_mut(&s).unwrap() -= 1; + ans + } else { + 0 + } + } + + dfs(root, 0, target_sum as i64, &mut cnt) + } +} +``` + +--- + +**Tags:** Tree, Depth-First Search, Binary Tree +**Difficulty:** Medium +**Related Topics:** Prefix Sum, Recursion +**Link:** [437. Path Sum III](https://leetcode.com/problems/path-sum-iii) +``` + +Let me know if you want the Chinese version, or a `.md` file to download. \ No newline at end of file From 27355f69b4ae77081667e139243929bc1572de2e Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:35:28 +0530 Subject: [PATCH 47/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/437. Path Sum III/readme.md | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/Solution/437. Path Sum III/readme.md b/Solution/437. Path Sum III/readme.md index 1b7d2e4..abb28a6 100644 --- a/Solution/437. Path Sum III/readme.md +++ b/Solution/437. Path Sum III/readme.md @@ -1,10 +1,6 @@ -Sure! Here's the complete LeetCode-style `README.md` file for **437. Path Sum III**, in the format consistent with the ones from the `doocs/leetcode` GitHub repository. ---- - -```markdown # 437. Path Sum III - +--- ## Description Given the `root` of a binary tree and an integer `targetSum`, return *the number of paths where the sum of the values along the path equals* `targetSum`. @@ -245,6 +241,3 @@ impl Solution { **Difficulty:** Medium **Related Topics:** Prefix Sum, Recursion **Link:** [437. Path Sum III](https://leetcode.com/problems/path-sum-iii) -``` - -Let me know if you want the Chinese version, or a `.md` file to download. \ No newline at end of file From c32982756cb958463a9ecd8443f67d3026256c05 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:37:57 +0530 Subject: [PATCH 48/59] Create 1372. Longest ZigZag Path in a Binary Tree.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- ...2. Longest ZigZag Path in a Binary Tree.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Solution/1372. Longest ZigZag Path in a Binary Tree/1372. Longest ZigZag Path in a Binary Tree.py diff --git a/Solution/1372. Longest ZigZag Path in a Binary Tree/1372. Longest ZigZag Path in a Binary Tree.py b/Solution/1372. Longest ZigZag Path in a Binary Tree/1372. Longest ZigZag Path in a Binary Tree.py new file mode 100644 index 0000000..08c225d --- /dev/null +++ b/Solution/1372. Longest ZigZag Path in a Binary Tree/1372. Longest ZigZag Path in a Binary Tree.py @@ -0,0 +1,19 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def longestZigZag(self, root: TreeNode) -> int: + def dfs(root, l, r): + if root is None: + return + nonlocal ans + ans = max(ans, l, r) + dfs(root.left, r + 1, 0) + dfs(root.right, 0, l + 1) + + ans = 0 + dfs(root, 0, 0) + return ans \ No newline at end of file From df54adbfb5adc5b0b7b1952edbb8939b133af0eb Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:38:20 +0530 Subject: [PATCH 49/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/1372. Longest ZigZag Path in a Binary Tree/readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/1372. Longest ZigZag Path in a Binary Tree/readme.md diff --git a/Solution/1372. Longest ZigZag Path in a Binary Tree/readme.md b/Solution/1372. Longest ZigZag Path in a Binary Tree/readme.md new file mode 100644 index 0000000..e69de29 From 5326bdb4a54f1cf447f5c4da65dde2cc2e01b364 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:38:38 +0530 Subject: [PATCH 50/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../readme.md | 188 ++++++++++++++++++ 1 file changed, 188 insertions(+) diff --git a/Solution/1372. Longest ZigZag Path in a Binary Tree/readme.md b/Solution/1372. Longest ZigZag Path in a Binary Tree/readme.md index e69de29..c415b52 100644 --- a/Solution/1372. Longest ZigZag Path in a Binary Tree/readme.md +++ b/Solution/1372. Longest ZigZag Path in a Binary Tree/readme.md @@ -0,0 +1,188 @@ +Sure! Here's the full `README.md` in the LeetCode-style format, exactly like in the `doocs/leetcode` GitHub repo, for **1372. Longest ZigZag Path in a Binary Tree**: + +--- + +```markdown +# [1372. Longest ZigZag Path in a Binary Tree](https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree) + +## Description + +You are given the `root` of a binary tree. + +A ZigZag path for a binary tree is defined as follows: + +- Choose **any** node in the binary tree and a direction (right or left). +- If the current direction is right, move to the right child of the current node; otherwise, move to the left child. +- Change the direction from right to left or from left to right. +- Repeat the second and third steps until you can't move in the tree. + +The ZigZag length is defined as the number of nodes visited - 1. (A single node has a length of 0). + +Return _the longest **ZigZag** path contained in that tree_. + +## Examples + +**Example 1:** + +![example1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1300-1399/1372.Longest%20ZigZag%20Path%20in%20a%20Binary%20Tree/images/sample_1_1702.png) + +``` +Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1] +Output: 3 +Explanation: Longest ZigZag path in blue nodes (right -> left -> right). +``` + +**Example 2:** + +![example2](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1300-1399/1372.Longest%20ZigZag%20Path%20in%20a%20Binary%20Tree/images/sample_2_1702.png) + +``` +Input: root = [1,1,1,null,1,null,null,1,1,null,1] +Output: 4 +Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right). +``` + +**Example 3:** + +``` +Input: root = [1] +Output: 0 +``` + +## Constraints + +- The number of nodes in the tree is in the range `[1, 5 * 10^4]`. +- `1 <= Node.val <= 100` + +## Solutions + +### Python3 + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def longestZigZag(self, root: TreeNode) -> int: + def dfs(root, l, r): + if root is None: + return + nonlocal ans + ans = max(ans, l, r) + dfs(root.left, r + 1, 0) + dfs(root.right, 0, l + 1) + + ans = 0 + dfs(root, 0, 0) + return ans +``` + +### Java + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + private int ans; + + public int longestZigZag(TreeNode root) { + dfs(root, 0, 0); + return ans; + } + + private void dfs(TreeNode root, int l, int r) { + if (root == null) { + return; + } + ans = Math.max(ans, Math.max(l, r)); + dfs(root.left, r + 1, 0); + dfs(root.right, 0, l + 1); + } +} +``` + +### C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + int ans = 0; + + int longestZigZag(TreeNode* root) { + dfs(root, 0, 0); + return ans; + } + + void dfs(TreeNode* root, int l, int r) { + if (!root) return; + ans = max(ans, max(l, r)); + dfs(root->left, r + 1, 0); + dfs(root->right, 0, l + 1); + } +}; +``` + +### Go + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func longestZigZag(root *TreeNode) int { + ans := 0 + var dfs func(root *TreeNode, l, r int) + dfs = func(root *TreeNode, l, r int) { + if root == nil { + return + } + ans = max(ans, max(l, r)) + dfs(root.Left, r+1, 0) + dfs(root.Right, 0, l+1) + } + dfs(root, 0, 0) + return ans +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + +--- + +Let me know if you want this in other languages or with a visual diagram too! \ No newline at end of file From 6a1ab0e88202cb541c5dbe9374bdc72a64f75e2d Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:39:22 +0530 Subject: [PATCH 51/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../1372. Longest ZigZag Path in a Binary Tree/readme.md | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/Solution/1372. Longest ZigZag Path in a Binary Tree/readme.md b/Solution/1372. Longest ZigZag Path in a Binary Tree/readme.md index c415b52..06c3ffa 100644 --- a/Solution/1372. Longest ZigZag Path in a Binary Tree/readme.md +++ b/Solution/1372. Longest ZigZag Path in a Binary Tree/readme.md @@ -1,10 +1,6 @@ -Sure! Here's the full `README.md` in the LeetCode-style format, exactly like in the `doocs/leetcode` GitHub repo, for **1372. Longest ZigZag Path in a Binary Tree**: ---- - -```markdown # [1372. Longest ZigZag Path in a Binary Tree](https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree) - +--- ## Description You are given the `root` of a binary tree. @@ -183,6 +179,3 @@ func max(a, b int) int { } ``` ---- - -Let me know if you want this in other languages or with a visual diagram too! \ No newline at end of file From 9ddfb3ec18c13cdd204e6e2a33706fe0b78aea05 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:40:35 +0530 Subject: [PATCH 52/59] Create 236. Lowest Common Ancestor of a Binary Tree.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../236. Lowest Common Ancestor of a Binary Tree.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree.py diff --git a/Solution/236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree.py b/Solution/236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree.py new file mode 100644 index 0000000..e69de29 From 943b2a11acefc01004f95b0ebb76e8808862107b Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:41:39 +0530 Subject: [PATCH 53/59] Update 236. Lowest Common Ancestor of a Binary Tree.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .... Lowest Common Ancestor of a Binary Tree.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Solution/236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree.py b/Solution/236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree.py index e69de29..a6fb630 100644 --- a/Solution/236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree.py +++ b/Solution/236. Lowest Common Ancestor of a Binary Tree/236. Lowest Common Ancestor of a Binary Tree.py @@ -0,0 +1,17 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution: + def lowestCommonAncestor( + self, root: "TreeNode", p: "TreeNode", q: "TreeNode" + ) -> "TreeNode": + if root in (None, p, q): + return root + left = self.lowestCommonAncestor(root.left, p, q) + right = self.lowestCommonAncestor(root.right, p, q) + return root if left and right else (left or right) \ No newline at end of file From d95eaec50f6875954721d71df5546f47b88c22be Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:41:58 +0530 Subject: [PATCH 54/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md diff --git a/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md b/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md new file mode 100644 index 0000000..e69de29 From 88777142e67bdf6ea66d9a1e695b52b406604d00 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:42:22 +0530 Subject: [PATCH 55/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../readme.md | 239 ++++++++++++++++++ 1 file changed, 239 insertions(+) diff --git a/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md b/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md index e69de29..0d48d44 100644 --- a/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md +++ b/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md @@ -0,0 +1,239 @@ +Sure! Here's the full LeetCode-style `README.md` file for **236. Lowest Common Ancestor of a Binary Tree**, formatted just like in the `doocs/leetcode` GitHub repository. + +--- + +```markdown +--- +title: "236. Lowest Common Ancestor of a Binary Tree" +description: "Recursive DFS solution to find the lowest common ancestor of two nodes in a binary tree." +difficulty: Medium +tags: + - Tree + - Depth-First Search + - Binary Tree +--- + +## Description + +Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. + +According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): +“The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow a node to be a descendant of itself).” + +### Example 1: + +![Example1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png) + +``` +Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 +Output: 3 +Explanation: The LCA of nodes 5 and 1 is 3. +``` + +### Example 2: + +``` +Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 +Output: 5 +Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself. +``` + +### Example 3: + +``` +Input: root = [1,2], p = 1, q = 2 +Output: 1 +``` + +### Constraints: + +- The number of nodes in the tree is in the range [2, 10⁵]. +- -10⁹ <= Node.val <= 10⁹ +- All Node.val are **unique**. +- `p != q` +- `p` and `q` will exist in the tree. + +--- + +## Solutions + +### Approach: Recursion (DFS) + +We recursively search the tree: + +- If the current node is `null`, or matches `p` or `q`, return it. +- Recursively search the left and right subtrees. +- If both sides return non-null, this node is the LCA. +- Otherwise, return the non-null result from one of the sides. + +**Time Complexity:** O(n) +**Space Complexity:** O(n) + +--- + +### Code + +#### Python3 + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def lowestCommonAncestor( + self, root: "TreeNode", p: "TreeNode", q: "TreeNode" + ) -> "TreeNode": + if root in (None, p, q): + return root + left = self.lowestCommonAncestor(root.left, p, q) + right = self.lowestCommonAncestor(root.right, p, q) + return root if left and right else (left or right) +``` + +#### Java + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + if (root == null || root == p || root == q) { + return root; + } + var left = lowestCommonAncestor(root.left, p, q); + var right = lowestCommonAncestor(root.right, p, q); + if (left != null && right != null) { + return root; + } + return left == null ? right : left; + } +} +``` + +#### C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { + if (root == nullptr || root == p || root == q) { + return root; + } + auto left = lowestCommonAncestor(root->left, p, q); + auto right = lowestCommonAncestor(root->right, p, q); + if (left && right) { + return root; + } + return left ? left : right; + } +}; +``` + +#### Go + +```go +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + if root == nil || root == p || root == q { + return root + } + left := lowestCommonAncestor(root.Left, p, q) + right := lowestCommonAncestor(root.Right, p, q) + if left != nil && right != nil { + return root + } + if left != nil { + return left + } + return right +} +``` + +#### TypeScript + +```ts +function lowestCommonAncestor( + root: TreeNode | null, + p: TreeNode | null, + q: TreeNode | null, +): TreeNode | null { + if (!root || root === p || root === q) { + return root; + } + const left = lowestCommonAncestor(root.left, p, q); + const right = lowestCommonAncestor(root.right, p, q); + return left && right ? root : left || right; +} +``` + +#### Rust + +```rust +use std::cell::RefCell; +use std::rc::Rc; +impl Solution { + pub fn lowest_common_ancestor( + root: Option>>, + p: Option>>, + q: Option>>, + ) -> Option>> { + if root.is_none() || root == p || root == q { + return root; + } + let left = Self::lowest_common_ancestor( + root.as_ref().unwrap().borrow().left.clone(), + p.clone(), + q.clone(), + ); + let right = Self::lowest_common_ancestor( + root.as_ref().unwrap().borrow().right.clone(), + p.clone(), + q.clone(), + ); + if left.is_some() && right.is_some() { + return root; + } + if left.is_none() { + return right; + } + return left; + } +} +``` + +#### JavaScript + +```js +var lowestCommonAncestor = function (root, p, q) { + if (!root || root === p || root === q) { + return root; + } + const left = lowestCommonAncestor(root.left, p, q); + const right = lowestCommonAncestor(root.right, p, q); + return left && right ? root : left || right; +}; +``` + +--- +``` + +Let me know if you’d like the Chinese version or a version for any other specific language or format! \ No newline at end of file From 71463bd14c03cfa3ff7c8654bcf214d165ca8603 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:45:02 +0530 Subject: [PATCH 56/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../readme.md | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md b/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md index 0d48d44..abe8f8a 100644 --- a/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md +++ b/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md @@ -1,13 +1,8 @@ -Sure! Here's the full LeetCode-style `README.md` file for **236. Lowest Common Ancestor of a Binary Tree**, formatted just like in the `doocs/leetcode` GitHub repository. ---- - -```markdown ---- -title: "236. Lowest Common Ancestor of a Binary Tree" -description: "Recursive DFS solution to find the lowest common ancestor of two nodes in a binary tree." -difficulty: Medium -tags: +# 236. Lowest Common Ancestor of a Binary Tree +**Description**: "Recursive DFS solution to find the lowest common ancestor of two nodes in a binary tree." +- **difficulty**: Medium +- **tags**: - Tree - Depth-First Search - Binary Tree @@ -233,7 +228,3 @@ var lowestCommonAncestor = function (root, p, q) { }; ``` ---- -``` - -Let me know if you’d like the Chinese version or a version for any other specific language or format! \ No newline at end of file From 5d1df5d481828c395ff23a1b80d0755c8758788a Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:46:41 +0530 Subject: [PATCH 57/59] Update readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md b/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md index abe8f8a..318ec6a 100644 --- a/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md +++ b/Solution/236. Lowest Common Ancestor of a Binary Tree/readme.md @@ -2,7 +2,7 @@ # 236. Lowest Common Ancestor of a Binary Tree **Description**: "Recursive DFS solution to find the lowest common ancestor of two nodes in a binary tree." - **difficulty**: Medium -- **tags**: +tags: - Tree - Depth-First Search - Binary Tree From a46ebdeb1557f46315a6bbcf2d374254938c82a1 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:49:45 +0530 Subject: [PATCH 58/59] Create 199. Binary Tree Right Side View.py Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../199. Binary Tree Right Side View.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Solution/199. Binary Tree Right Side View/199. Binary Tree Right Side View.py diff --git a/Solution/199. Binary Tree Right Side View/199. Binary Tree Right Side View.py b/Solution/199. Binary Tree Right Side View/199. Binary Tree Right Side View.py new file mode 100644 index 0000000..77875b5 --- /dev/null +++ b/Solution/199. Binary Tree Right Side View/199. Binary Tree Right Side View.py @@ -0,0 +1,21 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def rightSideView(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + if root is None: + return ans + q = deque([root]) + while q: + ans.append(q[0].val) + for _ in range(len(q)): + node = q.popleft() + if node.right: + q.append(node.right) + if node.left: + q.append(node.left) + return ans \ No newline at end of file From b2760cce88501522c547af6152e64f2de77a3407 Mon Sep 17 00:00:00 2001 From: Antim Pal <134076504+iamAntimPal@users.noreply.github.com> Date: Sun, 13 Apr 2025 18:56:26 +0530 Subject: [PATCH 59/59] Create readme.md Co-Authored-By: Antim-IWP <203163676+Antim-IWP@users.noreply.github.com> Co-Authored-By: Shiwangi Srivastava <174641070+IamShiwangi@users.noreply.github.com> --- .../readme.md | 331 ++++++++++++++++++ 1 file changed, 331 insertions(+) create mode 100644 Solution/199. Binary Tree Right Side View/readme.md diff --git a/Solution/199. Binary Tree Right Side View/readme.md b/Solution/199. Binary Tree Right Side View/readme.md new file mode 100644 index 0000000..3a557a7 --- /dev/null +++ b/Solution/199. Binary Tree Right Side View/readme.md @@ -0,0 +1,331 @@ + + + +# [199. Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view) + +- **comments**: true +- **difficulty**: Medium + +- **tags**: + - Tree + - Depth-First Search + - Breadth-First Search + - Binary Tree +--- + +## Description + + + +

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

+ +

 

+

Example 1:

+ +
+

Input: root = [1,2,3,null,5,null,4]

+ +

Output: [1,3,4]

+ +

Explanation:

+ +

+
+ +

Example 2:

+ +
+

Input: root = [1,2,3,4,null,null,null,5]

+ +

Output: [1,3,4,5]

+ +

Explanation:

+ +

+
+ +

Example 3:

+ +
+

Input: root = [1,null,3]

+ +

Output: [1,3]

+
+ +

Example 4:

+ +
+

Input: root = []

+ +

Output: []

+
+ +

 

+

Constraints:

+ +
    +
  • The number of nodes in the tree is in the range [0, 100].
  • +
  • -100 <= Node.val <= 100
  • +
+ + + +## Solutions + + + +### Solution 1: BFS + +We can use breadth-first search (BFS) and define a queue $\textit{q}$ to store the nodes. We start by putting the root node into the queue. Each time, we take out all the nodes of the current level from the queue. For the current node, we first check if the right subtree exists; if it does, we put the right subtree into the queue. Then, we check if the left subtree exists; if it does, we put the left subtree into the queue. This way, the first node taken out from the queue each time is the rightmost node of that level. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. + + + +#### Python3 + +```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def rightSideView(self, root: Optional[TreeNode]) -> List[int]: + ans = [] + if root is None: + return ans + q = deque([root]) + while q: + ans.append(q[0].val) + for _ in range(len(q)): + node = q.popleft() + if node.right: + q.append(node.right) + if node.left: + q.append(node.left) + return ans +``` + +#### Java + +```java +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public List rightSideView(TreeNode root) { + List ans = new ArrayList<>(); + if (root == null) { + return ans; + } + Deque q = new ArrayDeque<>(); + q.offer(root); + while (!q.isEmpty()) { + ans.add(q.peekFirst().val); + for (int k = q.size(); k > 0; --k) { + TreeNode node = q.poll(); + if (node.right != null) { + q.offer(node.right); + } + if (node.left != null) { + q.offer(node.left); + } + } + } + return ans; + } +} +``` + +#### C++ + +```cpp +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +public: + vector rightSideView(TreeNode* root) { + vector ans; + if (!root) { + return ans; + } + queue q{{root}}; + while (q.size()) { + ans.push_back(q.front()->val); + for (int k = q.size(); k; --k) { + auto node = q.front(); + q.pop(); + if (node->right) { + q.push(node->right); + } + if (node->left) { + q.push(node->left); + } + } + } + return ans; + } +}; +``` + +#### Go + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func rightSideView(root *TreeNode) (ans []int) { + if root == nil { + return + } + q := []*TreeNode{root} + for len(q) > 0 { + ans = append(ans, q[0].Val) + for k := len(q); k > 0; k-- { + node := q[0] + q = q[1:] + if node.Right != nil { + q = append(q, node.Right) + } + if node.Left != nil { + q = append(q, node.Left) + } + } + } + return +} +``` + +#### TypeScript + +```ts +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function rightSideView(root: TreeNode | null): number[] { + const ans: number[] = []; + if (!root) { + return ans; + } + const q: TreeNode[] = [root]; + while (q.length > 0) { + ans.push(q[0].val); + const nq: TreeNode[] = []; + for (const { left, right } of q) { + if (right) { + nq.push(right); + } + if (left) { + nq.push(left); + } + } + q.length = 0; + q.push(...nq); + } + return ans; +} +``` + +#### Rust + +```rust +// Definition for a binary tree node. +// #[derive(Debug, PartialEq, Eq)] +// pub struct TreeNode { +// pub val: i32, +// pub left: Option>>, +// pub right: Option>>, +// } +// impl TreeNode { +// #[inline] +// pub fn new(val: i32) -> Self { +// TreeNode { +// val, +// left: None, +// right: None, +// } +// } +// } + +use std::collections::VecDeque; + +impl Solution { + pub fn right_side_view(root: Option>>) -> Vec { + let mut ans = Vec::new(); + if root.is_none() { + return ans; + } + let mut queue = VecDeque::new(); + queue.push_back(root); + while !queue.is_empty() { + let len = queue.len(); + ans.push(queue.front().unwrap().borrow().val); + for _ in 0..len { + let node = queue.pop_front().unwrap(); + if node.borrow().right.is_some() { + queue.push_back(node.borrow().right.clone()); + } + if node.borrow().left.is_some() { + queue.push_back(node.borrow().left.clone()); + } + } + } + ans + } +} +``` + + + +## Explanation + +To solve this problem, we can use a breadth-first search (BFS) approach. The idea is to traverse the tree level by level and collect the first node that is visible from the right side at each level. This can be achieved by using a queue to store the nodes of the tree and processing each level one by one. At each level, we add the first node to our result list since it represents the rightmost node at that level. This ensures that the nodes we collect are in the correct order. + +### Complexity Analysis +- **Time Complexity**: O(n), where n is the number of nodes in the tree. Each node is visited exactly once during the BFS traversal. +- **Space Complexity**: O(n), where n is the maximum number of nodes at any level in the tree, which can be at most the number of leaf nodes in the tree. + + + +