#627

Swap Sex of Employees

Easy
DatabaseCASE statements in SQLUpdate operations in databases
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a single SQL update statement with a CASE expression to swap the values of 'sex' in one go. This is efficient and concise, avoiding multiple iterations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a single UPDATE statement.
  2. 2Step 2: Utilize a CASE statement to check the value of 'sex'.
  3. 3Step 3: Set 'sex' to 'f' if it is currently 'm', and to 'm' if it is currently 'f'.
  4. 4Step 4: Execute the update statement.
solution.py1 lines
1UPDATE Salary SET sex = CASE WHEN sex = 'm' THEN 'f' ELSE 'm' END;

Complexity note: The complexity remains O(n) because we still need to update each record in the table, but we do it in a single pass with one statement.

  • 1Using a single update statement with CASE is more efficient than iterating through records multiple times.
  • 2Understanding SQL syntax and functions like CASE can significantly simplify your queries.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.