Detect Duplicate Trace IDs in a Linked List
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 nodei.next[i]is the index of nodei's successor, or-1wheniis the tail.headis the first node index, or-1for 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) → booleanExamples
Example 1
traceIds = ["ingest","index","ingest"]next = [1,2,-1]head = 0return = trueNodes 0 and 2 both store ingest.
Example 2
traceIds = ["root","api","db"]next = [2,-1,1]head = 0return = falseThe traversal order is root -> db -> api, and every trace ID is distinct.
Example 3
traceIds = ["Trace-1","trace-1"]next = [1,-1]head = 0return = falseTrace 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-1or a valid node index. - Following
nextfromheadvisits every represented node exactly once and ends at-1. - Each trace ID contains between
1and32case-sensitive printable ASCII characters. - Do not use a map, set, or another auxiliary collection whose size grows with the list.