**124: Binary Tree Maximum Path Sum**
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the root of a binary tree, return the maximum path sum of any non-empty path.
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self.max_sum = float('-inf')
def dfs(node):
if not node:
return 0
# Recursively get max gain from left and right
left_gain = max(dfs(node.left), 0) # only take positive gains
right_gain = max(dfs(node.right), 0)
# Path that passes through this node (might be best)
current_max_path = node.val + left_gain + right_gain
# Update the global max_sum if needed
self.max_sum = max(self.max_sum, current_max_path)
# Return max gain extendable to parent
return node.val + max(left_gain, right_gain)
dfs(root)
return self.max_sum
| Metric | Value |
|---|---|
| Time | O(n) |
| Space | O(h) (stack) |
**3: Longest Substring Without Repeating Characters** ❗MEDIUM
Given a string s, find the length of the longest substring without duplicate characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
char_set = set()
left = 0
max_length = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_length = max(max_length, right - left + 1)
return max_length
| Metric | Complexity |
|---|---|
| Time | O(n) |
| Space | O(min(n, m)) |
set() to keep track of seen chars**8: String to Integer (atoi)** ❗ MEDIUM
Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s) is as follows:
" ").'-' or '+', assuming positivity if neither present.[-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than 231 should be rounded to 231, and integers greater than 231 - 1 should be rounded to 231 - 1.Return the integer as the final result.
Example 1:
Input: s = "42"
Output: 42
Explanation:
The underlined characters are what is read in and the caret is the current reader position.
Step 1: "42" (no characters read because there is no leading whitespace)
^
Step 2: "42" (no characters read because there is neither a '-' nor '+')
^
Step 3: "42" ("42" is read in)
^
Example 2:
Input: s = " -042"
Output: -42
Explanation:
Step 1: "-042" (leading whitespace is read and ignored)
^
Step 2: "-042" ('-' is read, so the result should be negative)
^
Step 3: " -042" ("042" is read in, leading zeros ignored in the result)
^
Example 3:
Input: s = "1337c0d3"
Output: 1337
Explanation:
Step 1: "1337c0d3" (no characters read because there is no leading whitespace)
^
Step 2: "1337c0d3" (no characters read because there is neither a '-' nor '+')
^
Step 3: "1337c0d3" ("1337" is read in; reading stops because the next character is a non-digit)
^
Example 4:
Input: s = "0-1"
Output: 0
Explanation:
Step 1: "0-1" (no characters read because there is no leading whitespace)
^
Step 2: "0-1" (no characters read because there is neither a '-' nor '+')
^
Step 3: "0-1" ("0" is read in; reading stops because the next character is a non-digit)
^
Example 5:
Input: s = "words and 987"
Output: 0
Explanation:
Reading stops at the first non-digit character 'w'.
class Solution:
def myAtoi(self, s: str) -> int:
i = 0
n = len(s)
sign = 1
result = 0
# Step 1: Skip leading spaces
while i < n and s[i] == ' ':
i += 1
# Step 2: Check for sign
if i < n and (s[i] == '+' or s[i] == '-'):
if s[i] == '-':
sign = -1
i += 1
# Step 3: Read digits
while i < n and s[i].isdigit():
digit = int(s[i])
result = result * 10 + digit
i += 1
# Step 4: Apply sign
result *= sign
# Step 5: Clamp to 32-bit signed integer range
INT_MIN = -2**31
INT_MAX = 2**31 - 1
if result < INT_MIN:
return INT_MIN
if result > INT_MAX:
return INT_MAX
return result
| Metric | Complexity |
|---|---|
| Time | O(n) (one pass through the string) |
| Space | O(1) (constant extra space) |
.isdigit()result = result * 10 + digit