Amazon Coding Question – Solved

8 Live
Company's software team utilizes several algorithms to maintain data integrity, one of which targets the encoding of symmetrical names. Symmetrical names are unique in that they read identically in both directions, similar to palindromes in language parlance. The chief aim of the algorithm is to rearrange the characters in the original symmetrical name according to these criteria: - The rearranged name is a reshuffled version of the original symmetrical name. - The restructured name should be symmetrical as well. - This restructured name should be lexicographically smallest among all its symmetric permutations. Given an initial symmetrical name that contains only lowercase English characters, compute the encoded name. A string s is considered to be lexicographically smaller than the string t of the same length if the first character in s that differs from that in t is smaller, For example, "abcd" is lexicographically smaller than "abdc" but larger than "abad" Note that the output encoded name could match the original name if it's already the smallest lexicographically. Example The original string is letters = "babab". This can be reversed to give "abbba", which is a symmetric rearrangement of the original symmetrical name and is the smallest possible reverse order, It satisfies all the requirements so return the string abbba.

Asked in: Amazon

Image of the Question

Question Image

All Testcases Passed ✔



Passcode Image

Solution


def getEncodedName(letters):
    # Write your code here
    h = {}
    for i in letters:
// ... rest of solution available after purchase

🔒 Please login to view the solution

Explanation


```
To approach this problem, the key is to understand the structural and lexical constraints involved in forming the final string. You are given a symmetrical name, which is effectively a palindrome — a string that reads the same forward and backward. The task is to find a rearrangement (a permutation) of the original string that is also a palindrome, but it must be the **lexicographically smallest** among all such valid rearrangements.

Begin by analyzing what makes a string symmetrical or palindromic. A string is palindromic if the characters at mirrored positions from the center are the same. For even-length strings, all characters must occur an even number of times to mirror exactly. For odd-length strings, only one character can occur an odd number of times (this character will be placed in the center), and all others must occur evenly to mirror around it.

This observation gives us a fundamental constraint for building a valid symmetric rearrangement: the frequency of characters determines whether a symmetric form is possible and how it can be structured. Since you're given that the input is already a symmetrical string, you can safely assume that at least one symmetric permutation is possible — you don’t need to validate this condition explicitly.

Now shift your focus to constructing the **lexicographically smallest** symmetric rearrangement. To do this optimally, think of the palindrome as being built in two parts: the left half and the right half, with possibly a middle character for odd-length strings. Since the palindrome must mirror itself, the right half is just the reverse of the left half.

The lexicographically smallest string is one where the characters at the lowest indices are the smallest possible. So your strategy should be to construct the left half using the smallest characters available first. You should aim to build the smallest possible left half using sorted characters, such that their mirrored pairings can complete the palindrome.

Here’s a step-by-step direction to structure your thinking:

1. **Character Frequency Count**: Count how many times each character appears in the input string. This count determines how many of each character you can place in the symmetric result.

2. **Build the Left Half**: For each character in alphabetical order (from 'a' to 'z'), take half of its count (i.e., floor of count/2) and append that many instances to a new string — this forms the left half of the resulting palindrome. You're effectively distributing the characters as evenly as possible while ensuring symmetry and prioritizing smaller letters to maintain lexicographic minimality.

3. **Determine the Middle Character**: If the original string length is odd, exactly one character must have an odd count. This character will be placed in the center of the palindrome. During your frequency count, you can identify this character and remember it.

4. **Construct the Final Result**: Once the left half and the middle character (if any) are determined, construct the right half as the reverse of the left half. Concatenate the left half, middle character (if it exists), and right half to get the final result.

This construction guarantees symmetry and, because you built the left half using the smallest available characters first, it is also lexicographically smallest among all valid symmetric permutations.

Let’s revisit why this works:
- Symmetry is ensured by mirroring the left half to form the right half.
- Lexicographical minimality is achieved by always choosing the smallest available characters first for the left half.
- Validity (existence of such a symmetric arrangement) is guaranteed by the problem’s assumption that the original string is already symmetric.

Edge considerations:
- If all characters occur an even number of times, the middle character will be empty, and the palindrome will have even length.
- If there are multiple characters with odd counts, only one can be used in the middle — but again, the problem guarantees a valid symmetric rearrangement, so you don't need to resolve conflicts.
- The final output can be the same as the input if the input is already the smallest lexicographically valid symmetric form.

In summary, the optimal solution follows a frequency-driven, greedy character placement strategy: count frequencies, build the left half with the smallest letters, assign a middle character if necessary, and mirror the left to form the right. This ensures the resulting string is symmetric and lexicographically smallest.
```


Related Questions