Organized by oavoservice: Two common questions covering "Linear Scan String Processing" and "Social Graph Shortest Path".
Question 1: String Replace without Built-in Function
Problem
Given string s, pattern pat, replacement rep, return a new string where all occurrences of pat in s are replaced by rep, without using built-in replace.
Idea (Two Pointers / Sliding Window)
Manually implement "left-to-right matching":
- Scan
swith indexi. - If
s[i:i+len(pat)] == pat, appendrepandi += len(pat). - Otherwise append
s[i]andi += 1.
Python Implementation
def replace_without_builtin(s: str, pat: str, rep: str) -> str:
if pat == "":
return s
out = []
i = 0
m = len(pat)
while i < len(s):
if i + m <= len(s) and s[i:i+m] == pat:
out.append(rep)
i += m
else:
out.append(s[i])
i += 1
return "".join(out)
Interview Questions
- Overlapping matches? (Standard replace semantics are non-overlapping, greedy left-to-right).
- Complexity? (Worst case
O(n*m), KMP can improve to linear).
Question 2: LinkedIn Connection Distance
Problem
Given an undirected graph of user connections and two users src and dst, find the shortest distance (min edges) between them.
- Return
-1if unreachable.
Idea (BFS Shortest Path)
Standard BFS for unweighted graph shortest path:
- Start BFS from
src, distance 0. - Expand neighbors, first time hitting
dstgives shortest distance.
Python Template
from collections import deque
from typing import Dict, List
def connection_distance(graph: Dict[str, List[str]], src: str, dst: str) -> int:
if src == dst:
return 0
if src not in graph or dst not in graph:
return -1
q = deque([src])
dist = {src: 0}
while q:
u = q.popleft()
for v in graph.get(u, []):
if v in dist:
continue
dist[v] = dist[u] + 1
if v == dst:
return dist[v]
q.append(v)
return -1
Interview Questions
- Large graph? (Bi-directional BFS / Limit depth).
- Return path? (Store parent pointers).
If preparing for LinkedIn VO/OA, oavoservice trains you to quickly implement and explain these fundamental questions and extensions.
Need real interview questions? Contact WeChat Coding0201 immediately to get real questions.