Leetcode 2451. Odd String Difference
You are given an array of strings words
. Each string contains lower-case English letters of equal length. A string s
is considered odd if and only if the difference between the ASCII values of every two consecutive characters is an odd value. Return the odd string from the array words
. There will be exactly one string in the input list which meets the criteria.
words
array?words
array?Let’s assume from the statement that there is always exactly one string that meets the condition.
words
array:
Here is the implementation of the given problem in Java:
public class Solution {
public String oddString(String[] words) {
for (String word : words) {
boolean isOdd = true; // flag to check if all differences are odd
for (int i = 0; i < word.length() - 1; i++) {
int diff = Math.abs(word.charAt(i) - word.charAt(i + 1));
if (diff % 2 == 0) {
isOdd = false; // found an even difference
break;
}
}
if (isOdd) {
return word; // return the odd string
}
}
return ""; // Default case, should not be reached
}
}
The time complexity of this solution can be analyzed as follows:
n
be the number of words in the words
array.m
be the length of each word.The solution involves:
O(n)
).O(m)
).Thus, the overall time complexity is O(n * m)
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?