LeetCode 3328: Find Cities in Each State II Solution
Master LeetCode problem 3328 (Find Cities in Each State II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3328. Find Cities in Each State II
Problem Explanation
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:
- Create a HashMap to store the count of cities for each state.
- Iterate through the list of cities and update the count of cities for each state in the HashMap.
- 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.
:
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3328 (Find Cities in Each State II)?
This page provides optimized solutions for LeetCode problem 3328 (Find Cities in Each State II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3328 (Find Cities in Each State II)?
The time complexity for LeetCode 3328 (Find Cities in Each State II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3328 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3328 in Java, C++, or Python.