Input: s = "geeksforgeeks"
Output: ['e', 4], ['g', 2], ['k', 2], ['s', 2]
Explanation: Characters e, g, k, and s appear more than once. Their counts are shown in order of first occurrence.
Input: s = "programming"
Output: ['r', 2], ['g', 2], ['m', 2]
Explanation: Only r, g, and m are duplicates. Output lists them with their counts.
Input: s = "mississippi"
Output: ['i', 4], ['s', 4], ['p', 2]
Explanation: Characters i, s, and p have multiple occurrences. The output reflects that with count and order preserved.
The idea is to group same characters together by sorting the string first. This makes it easier to count consecutive duplicates in one pass. As we traverse the sorted string, we increment a counter for each matching character, and only print those with count > 1. Sorting helps eliminate the need for extra space like maps or arrays, making the logic clean and space-efficient.
Output['e', 4], ['g', 2], ['k', 2], ['s', 2],
The idea is to count how many times each character appears using a hash map, which allows for efficient lookups and updates. The thought process is that repeated characters will have a count > 1, and we can detect them in a single pass. Hashing ensures we achieve O(n) time by avoiding nested comparisons or sorting. This method is optimal for large strings where frequency tracking is more efficient than sorting-based grouping.
The auxiliary space requirement of this solution is O(ALPHABET_SIZE). For lower case characters, the value of ALPHABET_SIZE is 26 which is a constant.
Output['g', 2], ['e', 4], ['k', 2], ['s', 2],