Problem · Hash Table

Implement uniq: Unique Lines

Learn this problem
MediumVantaONSITE INTERVIEW

Problem statement

You are implementing the core behavior of a uniq-style command. Given the lines of a file in order, return only the first occurrence of each distinct line while preserving the original order of first appearance.

The interview follow-up may ask how to handle files too large to fit in memory. For this function, implement the in-memory version over the provided array of lines.

Function

getUniqueLines(lines: String[]) → String[]

Examples

Example 1

lines = ["apple", "banana", "apple", "carrot", "banana"]return = ["apple", "banana", "carrot"]

Only the first occurrence of each distinct line is kept.

Example 2

lines = ["", "x", "", "X"]return = ["", "x", "X"]

Empty strings are valid lines, and comparison is case-sensitive.

Constraints

  • Preserve the order of first appearance.
  • Line comparison is exact and case-sensitive.
  • The base function may use memory proportional to the number of distinct lines.
drafts saved locally
public String[] getUniqueLines(String[] lines) {
  // write your code here
}
lines["apple", "banana", "apple", "carrot", "banana"]
expected["apple", "banana", "carrot"]
checking account