LeetCode 3328: Find Cities in Each State II

Database

Problem Description

Explanation:

Given a list of cities and their corresponding states, we need to find the count of cities in each state and return the result in lexicographically sorted order.

Algorithmic Idea:

  1. Create a HashMap to store the count of cities for each state.
  2. Iterate through the list of cities and update the count of cities for each state in the HashMap.
  3. Finally, sort the HashMap by state names in lexicographical order and return the result.

Time Complexity:

The time complexity for this solution is O(nlogn), where n is the number of cities.

Space Complexity:

The space complexity for this solution is O(n) to store the count of cities for each state.

:

Solutions

import java.util.*;

class Solution {
    public List<String> findCities(List<String> cities) {
        Map<String, Integer> stateCityCount = new HashMap<>();
        List<String> result = new ArrayList<>();

        for (String city : cities) {
            String[] parts = city.split(",");
            String state = parts[1].trim();
            stateCityCount.put(state, stateCityCount.getOrDefault(state, 0) + 1);
        }

        List<String> sortedStates = new ArrayList<>(stateCityCount.keySet());
        Collections.sort(sortedStates);

        for (String state : sortedStates) {
            result.add(state + ": " + stateCityCount.get(state));
        }

        return result;
    }
}

Loading editor...