Longest Perfect Anagrams
Learn this problemProblem statement
Developers at Amazon continuously develop algorithms to ensure the security of users' accounts through strong passwords.
One such algorithm is based upon the concept of perfect anagrams.
- A string
xis an anagram ofyif it is possible to rearrange the letters inxto gety. For example, "bat" and "tab" are anagrams, 'bats' and 'tab' are not. - Two strings
aandbare said to be perfect anagrams ifaandbare anagrams of each other andais not equal tob.
For example,
Given a string s, find the maximum length of two of its substrings that are perfect anagrams. If no such substrings exist, return -1.
Note: A substring is a contiguous subsegment of a string. For example, "xy" is a substring of "xyz" but "xz" is not.
Function
longestPerfectAnagrams(s: String) → int
Complete the function longestPerfectAnagrams in the editor.
longestPerfectAnagrams has the following parameter:
string s: a string
Returns
int: the length of the longest substring pair which are perfect anagrams or -1 if no such pair exists.
Examples
Example 1
s = "abcacb"return = 4
The string s = "abcacbab",
- Pairs of substrings such as ("ca", "ac"), ("abc", "acb"), ("bca", "acb"), ("bcac", "cacb"), etc. are perfect anagrams.
- Among these, the longest are ("bcac", "cacb").
It can be proven that no two substrings of length greater than 4 in the given string are perfect anagrams. Return 4.
Example 2
s = "cabcab"return = 3Example 3
s = "aabbcc"return = -1Constraints
- 1 ≤ |s| ≤ 10^5
- string
scontains lowercase English characters only.
More Amazon problems
- Secure Maximum DeliveriesOA · Seen Jul 2026
- Find Median from Data StreamONSITE INTERVIEW · Seen Jul 2026
- Handwritten SigmoidPHONE SCREEN · Seen Jul 2026
- Handwritten SoftmaxPHONE SCREEN · Seen Jul 2026
- Koko Eating BananasONSITE INTERVIEW · Seen Jul 2026
- Loyal Customers Across Two DaysONSITE INTERVIEW · Seen Jul 2026
- Maximum System Memory CapacityOA · Seen Jul 2026
- Package Delivery SystemOA · Seen Jul 2026