LeetCode 2399: Check Distances Between Same Letters Solution
Master LeetCode problem 2399 (Check Distances Between Same Letters), a easy 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.
2399. Check Distances Between Same Letters
Problem Explanation
Explanation
To solve this problem, we need to iterate over the given string s, calculate the distances between the two occurrences of each letter, and check if these distances match the values given in the distance array. We can do this by keeping track of the indices of each letter in a hashmap or an array.
- Create a hashmap or an array to store the indices of each letter in the string
s. - Iterate over the string
sand update the indices in the hashmap or array. - For each letter, calculate the distance between the two occurrences and compare it with the value in the
distancearray. - If any calculated distance does not match the value in the
distancearray, return false. Otherwise, return true at the end.
- Time complexity: O(n), where n is the length of the input string
s. - Space complexity: O(1) since the hashmap or array used to store indices has a fixed size of 26.
Solution Code
class Solution {
public boolean isWellSpacedString(String s, int[] distance) {
Map<Character, Integer> indices = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (indices.containsKey(ch)) {
if (distance[ch - 'a'] != i - indices.get(ch) - 1) {
return false;
}
} else {
indices.put(ch, i);
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2399 (Check Distances Between Same Letters)?
This page provides optimized solutions for LeetCode problem 2399 (Check Distances Between Same Letters) 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 2399 (Check Distances Between Same Letters)?
The time complexity for LeetCode 2399 (Check Distances Between Same Letters) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2399 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2399 in Java, C++, or Python.