FastPrepDetect Duplicate Trace IDs in a Linked List

Detect Duplicate Trace IDs in a Linked List

Google logoGoogle● MediumINTERNONSITE INTERVIEW
Learn

Problem statement

You are given a finite acyclic singly linked list through three parallel inputs:

  • traceIds[i] is the case-sensitive trace ID stored at node i.
  • next[i] is the index of node i's successor, or -1 when i is the tail.
  • head is the first node index, or -1 for an empty list.

Return true if two different reachable nodes have exactly the same trace ID. Otherwise, return false.

Do not modify traceIds or next. Your final solution must use O(1) auxiliary space; O(n^2) time is acceptable.

Function

hasDuplicateTraceId(traceIds: String[], next: int[], head: int) → boolean

Examples

Example 1

traceIds = ["ingest","index","ingest"]next = [1,2,-1]head = 0return = true

Nodes 0 and 2 both store ingest.

Example 2

traceIds = ["root","api","db"]next = [2,-1,1]head = 0return = false

The traversal order is root -> db -> api, and every trace ID is distinct.

Example 3

traceIds = ["Trace-1","trace-1"]next = [1,-1]head = 0return = false

Trace ID comparison is case-sensitive, so the two values are different.

Constraints

  • 0 <= traceIds.length = next.length <= 2000.
  • When the arrays are empty, head == -1. Otherwise, 0 <= head < traceIds.length.
  • Every next[i] is -1 or a valid node index.
  • Following next from head visits every represented node exactly once and ends at -1.
  • Each trace ID contains between 1 and 32 case-sensitive printable ASCII characters.
  • Do not use a map, set, or another auxiliary collection whose size grows with the list.

More Google problems

See Google hiring insights
public boolean hasDuplicateTraceId(String[] traceIds, int[] next, int head) {
  // Write your code here.
}
traceIds["ingest","index","ingest"]
next[1,2,-1]
head0
expectedtrue
Checking account…