Compare Prefix and Postfix Increment and Decrement

Solve this Problem
Easy10 min
Topics
Companies
Given an integer x, run a = x++, b = ++x, c = x-- and d = --x in that order and return [a, b, c, d, x]. Increment and decrementIncrement / DecrementThe ++ and -- operators, which add or subtract 1 from a variable in place. operators change a variable by one, but where you put them matters. In prefixPrefix (++x)The variable is changed first and the expression gives the new value. form the change happens before the value is used; in postfixPostfix (x++)The expression gives the current value, and the variable is changed afterwards. form it happens after. Python has no ++ or --, so its solutions use the expanded form, which is also the clearest way to see what the operators do.

Test Case 1:

Input:x = 5
Output:[5,7,7,5,5]
Explanation:a = x++ keeps 5; b = ++x sees 7; c = x-- keeps 7; d = --x sees 5; x ends where it started.

Test Case 2:

Input:x = -3
Output:[-3,-1,-1,-3,-3]
Explanation:The same pattern works for negative numbers.

Constraints

  • ◆-1000 ≤ x ≤ 1000

Try the Dry Run

Approach & Solutions

Expanded AssignmentsGood

Write out what each operator does as two separate statements. Postfix (x++, x--): copy the current value first, then change x. Prefix (++x, --x): change x first, then copy the new value. Python has no ++ or --, so this expanded form is how Python always writes it.

TimeO(1)
SpaceO(1)
class Solution { public int[] incrementTrace(int x) { int a = x; x = x + 1; x = x + 1; int b = x; int c = x; x = x - 1; x = x - 1; int d = x; return new int[] {a, b, c, d, x}; } }
Prefix and Postfix OperatorsOptimal

Use the operators directly: a = x++, b = ++x, c = x--, d = --x. The position of ++ or -- decides whether the variable receives the value before or after the change. Python has no such operators, so its code stays the same as the expanded version.

TimeO(1)
SpaceO(1)
class Solution { public int[] incrementTrace(int x) { int a = x++; int b = ++x; int c = x--; int d = --x; return new int[] {a, b, c, d, x}; } }

Related Problems