Created
April 25, 2025 21:22
-
-
Save rahulbakshee/58e259ce80f9a1ce9d09f6da64a17bf6 to your computer and use it in GitHub Desktop.
Google Interview Question - connected components given sorted array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
https://leetcode.com/discuss/post/6686960/google-swe2-phone-screen-rejected-by-ano-ek6t/ | |
π Company: Google | |
π Round: Phone Screen | |
π§ Role: SDE-2 | |
ποΈ Experience: 2 YOE | |
π§ͺ Question: Graph Connectivity via Value Proximity | |
Prompt: Given a sorted array arr of size N, and an integer diff, | |
construct an undirected graph where each node represents an index. | |
Connect nodes i and j if |arr[i] - arr[j]| <= diff. | |
You are given a list of queries [u, v]. Return a list of booleans | |
indicating whether there is a path between u and v. | |
Example: | |
arr = [1, 2, 3, 6] | |
diff = 2 | |
queries = [[0, 2], [1, 3]] | |
Output: [True, False] | |
""" | |
# time:O(n+Q), space:O(n) | |
def isConnected(arr,diff,queries): | |
n = len(arr) | |
components = [0] * n | |
comp_ID = 0 | |
# 1 - build graph | |
for i in range(1, n): | |
if arr[i] - arr[i-1] <= diff: | |
components[i] = comp_ID | |
else: | |
comp_ID += 1 | |
components[i] = comp_ID | |
return [components[u] == components[v] for u,v in queries] | |
arr = [1, 2, 3, 6] | |
diff = 2 | |
queries = [[0, 2], [1, 3]] | |
print(isConnected(arr, diff, queries)) #[True, False] | |
arr = [1, 3, 4, 6] | |
diff = 2 | |
queries = [[0, 2], [1, 3]] | |
print(isConnected(arr, diff, queries)) #[True, True] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment