LeetCode 2399: Check Distances Between Same Letters
LeetCode 2399 Solution 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
s
and 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
distance
array. - If any calculated distance does not match the value in the
distance
array, 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.
LeetCode 2399 Solutions in Java, C++, Python
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;
}
}
Interactive Code Editor for LeetCode 2399
Improve Your LeetCode 2399 Solution
Use the editor below to refine the provided solution for LeetCode 2399. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...