Arrange Table by Gender - Problem

You are given a table Genders with the following structure:

Column NameType
user_idint
gendervarchar

The user_id is the primary key for this table. The gender column contains values 'female', 'male', or 'other'. The table has an equal number of rows for each gender type.

Task: Rearrange the table so that rows alternate between 'female', 'other', and 'male' in that exact order. Within each gender group, the user_id values should be sorted in ascending order.

The final result should show the pattern: female, other, male, female, other, male, and so on.

Table Schema

Genders
Column Name Type Description
user_id PK int Unique identifier for each user
gender varchar Gender type: 'female', 'male', or 'other'
Primary Key: user_id
Note: Contains equal number of rows for each gender type

Input & Output

Example 1 — Basic Alternating Pattern
Input Table:
user_id gender
1 male
2 other
3 female
4 female
5 other
6 male
Output:
user_id gender
3 female
2 other
1 male
4 female
5 other
6 male
💡 Note:

The table is rearranged to alternate between female, other, and male. Within each gender group, users are ordered by user_id ascending. The first occurrence of each gender (user_id 3=female, 2=other, 1=male) comes first, followed by the second occurrence of each gender.

Example 2 — Sequential User IDs
Input Table:
user_id gender
1 female
2 male
3 other
4 female
5 male
6 other
Output:
user_id gender
1 female
3 other
2 male
4 female
6 other
5 male
💡 Note:

Even with sequential user IDs, the alternating pattern is maintained. Female users (1,4), other users (3,6), and male users (2,5) are arranged in the repeating pattern of female-other-male.

Constraints

  • 1 ≤ user_id ≤ 1000
  • gender is one of 'female', 'male', or 'other'
  • The table contains an equal number of 'female', 'male', and 'other' rows

Visualization

Tap to expand
Arrange Table by Gender - Alternating PatternInput: Mixed Orderuser_idgender1male2other3female4female5other6maleROW_NUMBER+ ORDER BYALTERNATINGPattern Logic:1st: female2nd: other3rd: maleOutput: Alternatinguser_idgender3female2other1male4female5other6male
Understanding the Visualization
1
Input
Mixed gender order in table
2
Rank
ROW_NUMBER within each gender group
3
Alternate
Female-Other-Male repeating pattern
Key Takeaway
🎯 Key Insight: Use window functions to rank within groups, then create alternating patterns with strategic ORDER BY clauses
Asked in
Amazon 15 Microsoft 12 Google 8
24.5K Views
Medium Frequency
~12 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen