Amazon is working on a new hashing approach that takes in the original string and a seed number.
Engineers decided that the seed can be generated from the same input string by counting the number of times a reverse of a substring of length k makes the new string lexicographically smaller. You are deployed with the task of developing a service that takes in a string s and an integer k, and returns the number of ways to reverse any substring of length k such that the resulting string is strictly lexicographically smaller than the original string.
Note:
- A substring is a contiguous sequence of characters within a string. For example, the string
"zon"is a substring of"amazon","zone", etc., but is not a substring of"zoin","zozo", etc. - A string
ais lexicographically smaller than stringbifa[i] < b[i]at the first index whereaandbdiffer. For example,"amazon"is lexicographically smaller than"amozan". - Reversing a substring that produces a string equal to the original (for example, a palindromic substring) is not counted, since the result must be strictly smaller than the original string.
Function Description:
- Complete the function
countNumWaysin the editor. countNumWayshas the following parameters:String s: the original stringint k: the algorithm parameter
Returns:
int: the number of possible ways to perform the operation such that the resulting string is strictly lexicographically smaller than the original string.
Examples
01 Β· Example 1
s = "amazon" k = 3 return = 1

Consider all substrings of length k = 3. The possible ways to perform the operation are:
(1) Reverse "ama" -> "amazon": unsuccessful (lexicographically equal).
(2) Reverse "maz" -> "azamon": unsuccessful (lexicographically greater).
(3) Reverse "azo" -> "amozan": unsuccessful (lexicographically greater).
(4) Reverse "zon" -> "amanoz": successful (lexicographically smaller).
Only one way is possible, so return 1.
02 Β· Example 2
s = "ababa" k = 2 return = 2
There are the possible ways for k = 2:
(1) ababa --> baaba: unsuccessful, lexicographically greater thanthe original string.
(2) ababa --> aabba: successfully, lexicographically smaller than the original string.
(3) ababa --> abbaa: unsuccessfully, lexicographically greater.
(4) ababa --> abaab: successfully, lexicographically smaller.
Constraints
2 <= |s| <= 1061 <= k <= min(|s|, 20)sconsists of lowercase English letters.
More Amazon problems
- Closest Version DateONSITE INTERVIEW Β· Seen Jul 2026
- Maximum Concurrent Processes (Bar Raiser Round)ONSITE INTERVIEW Β· Seen Jul 2026
- Maximum Product New RatingOA Β· Seen Jul 2026
- Permutation SorterOA Β· Seen Jul 2026
- Get Distinct Pairs (Also apply to AS intern)Seen Jul 2026
- Maximum Final ValueSeen Jul 2026
- Minimum Delivery Center InconvenienceOA Β· Seen Jun 2026
- Unfulfilled Customers by Inventory PriorityOA Β· Seen Jun 2026
public int countNumWays(String s, int k) {
// write your code here
}
s"amazon"
k3
expected1
checking account