Member-only story

Leetcode 1487: Making File Names Unique

Pierre-Marie Poitevin
2 min readJun 24, 2020

--

In this Leetcode problem, we try to name files in a file system in a unique way using a particular algorithm:

Problem statement

Solution

A couple of ideas to obtain the solution:

  1. Maintain next map String to Integer that stores the next smallest (potential) positive number to use for the particular String key.
  2. Maintain a set of strings used of all the strings used so far. We use it to make sure every string added is unique.
  3. We create array res to store the results to return.
  4. For each new name, we check if the key is used, then if needed check what needs to be appended, then we append it and add it to res, maintaining all the data structures at the same time.

Here is the full code:

class Solution {
public String[] getFolderNames(String[] names) {
int n = names.length;
// Next free int for prefix
Map<String, Integer> next = new HashMap<>();
// Exact set of used names
Set<String> used = new HashSet<>();
// Result to return
String[] res = new String[n];
for (int i = 0; i < n; i++) {
String name = names[i];
if (used.contains(name)) {
if (!next.containsKey(name)) {
next.put(name, 1)…

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet