You are given two independent coding problems. For each problem, provide an implementation and analyze the time and space complexity.
Problem 1: Find a string in a grid
Given an m x n grid of characters and a target string word, determine whether word can be formed by a path in the grid.
Rules:
-
The path may start from any cell.
-
Each next character must come from a horizontally or vertically adjacent cell.
-
A grid cell may be used at most once in the same path.
-
Return
true
if such a path exists; otherwise return
false
.
Example:
grid = [
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED"
Output: true
Problem 2: Longest substring with all unique characters
Given a string s, return the length of the longest contiguous substring that contains no repeated characters.
Example:
s = "abcabcbb"
Output: 3
Explanation: One longest valid substring is "abc".
After solving it with the common linear-time approach, also describe or implement an alternative linear-time solution that does not explicitly maintain a sliding window by repeatedly moving a left boundary pointer. For example, you may maintain the last index of each character and a dynamic programming value representing the length of the longest valid substring ending at the current position.