You're working with a Genders database table that contains user information including their gender identity. This table has an interesting property: it contains exactly equal numbers of users with genders 'female', 'male', and 'other'.
Your mission: Rearrange the table rows to create a specific alternating pattern where the genders cycle through 'female' → 'other' → 'male' repeatedly. Additionally, within each gender group, the user_id values should be sorted in ascending order.
| Column Name | Type |
|---|---|
| user_id | int |
| gender | varchar |
Example: If you have 6 users (2 female, 2 male, 2 other), your result should show: Female(smallest ID) → Other(smallest ID) → Male(smallest ID) → Female(largest ID) → Other(largest ID) → Male(largest ID)
This creates a beautiful, organized pattern that's both gender-balanced and ID-ordered! 🎯
Input & Output
Visualization
Time & Space Complexity
ROW_NUMBER() requires sorting within each gender group, and final ORDER BY - overall O(n log n)
Result set storage and temporary space for window function processing
Constraints
- The table contains equal numbers of 'female', 'male', and 'other' genders
- 1 ≤ user_id ≤ 106
- 3 ≤ total rows ≤ 104 (and divisible by 3)
- Gender values are exactly 'female', 'male', 'other'
- user_id is unique (primary key constraint)