简体   繁体   中英

Find first distinct string

I was having an interview for an internship. Interviewer asked following question.

Given a stream of Strings, find the first distinct string(not repeated in stream).

For ex : "abc","xyz","abcd","abc"

ans is "abc","abc","abc","xyz"

I told the approach with map and sets, but the time complexity is O(nlogn) assuming String's hash value is calculated in O(1). He constantly kept emphasizing to do better and told that the expected complexity is O(n). I could not come up with solution and I was rejected. Please help me with an appraoch.

It can be solved with trie and queue.

for string in text:
    if string not in trie:
        insert_in_trie(string)
        insert_in_queue(string)
    else:
        if not queue.empty():
            queue.pop()

    if queue.empty():
        print("No distinct character")
    else:
        print(queue.front())

Overall complexity will O(total length of strings) because insertion, deletion and peek in queue and trie will be O(length of string).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM