1. Custom Comparator Sort
Intuition
Create a lookup array rank where rank[c] stores the 0-indexed position of character c in order. For any character not present in order, assign rank 26 (default infinity). Then convert string s to an array of characters and sort it comparing their mapped ranks.
When to apply: When code brevity is preferred or when alphabet size is large and dynamic.
Algorithm
- Initialize an array
rankof size 26 with default value 26. - For each character
order[i], setrank[order[i] - 'a'] = i. - Sort the characters of
susing the comparator:rank[a - 'a'] - rank[b - 'a']. - Join and return the sorted characters as a string.
Custom Comparator Sort
2 of 2 questions left todayObservation: Build priority map from order: 'c' is 0, 'b' is 1, 'a' is 2
Observation: Build priority map from order: 'c' is 0, 'b' is 1, 'a' is 2.
Decision: Sort characters of s using custom comparator rank[a] - rank[b]. Since 'a' has higher rank (comes later) than 'b', swap them.
Invariant: Custom comparator ordering mirrors indices in order.
#include <iostream>#include <string>#include <vector>#include <algorithm> class Solution {public: std::string customSortString(std::string order, std::string s) { std::vector<int> rank(26, 26); for (int i = 0; i < (int)order.size(); ++i) { rank[order[i] - 'a'] = i; } std::sort(s.begin(), s.end(), [&](char a, char b) { return rank[a - 'a'] < rank[b - 'a']; }); return s; }}; int main() { Solution sol; std::cout << sol.customSortString("cba", "abcd") << std::endl; // "cbad" return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Sorting an N-length string with comparison sort takes O(N log N) time. - Space complexity:
O(N) for character conversion array / comparator stack
Why Brute Force Doesn't Scale:
Counting frequencies via a 26-size array eliminates sorting comparisons entirely.
Pre-allocating a StringBuilder/string buffer of size s.length prevents reallocation during construction.