Track a Value Through Compound Assignments
Solve this ProblemEasy10 min
Topics
BasicsOperators
Companies
TCSInfosysWipro
Starting from
x, apply these updates in order — add k, multiply by 2, subtract 3, divide by 2 (keeping only the whole part), take the remainder after dividing by 7 — and return the value of x after each of the five steps.
The assignment operatorAssignment OperatorThe = sign in code. It evaluates the right side and stores the result in the variable on the left; it is not an equation. replaces a variable's value with a new one. Compound assignmentCompound AssignmentShorthand such as x += 3, which means x = x + 3. Every arithmetic operator has one: +=, -=, *=, /=, %=. operators combine an arithmetic step with that replacement. Recording x after each step makes it visible that every update builds on the result of the previous one.
Test Case 1:
Input:x = 5, k = 3
Output:[8,16,13,6,6]
Explanation:5 + 3 = 8, doubled 16, minus 3 is 13, halved (whole part) 6, and 6 % 7 = 6.
Test Case 2:
Input:x = 1, k = 1
Output:[2,4,1,0,0]
Explanation:2, 4, 1, then 1 / 2 keeps only the whole part 0, and 0 % 7 = 0.
Constraints
- ◆
1 ≤ x ≤ 1000 - ◆
1 ≤ k ≤ 1000
Try the Dry Run
Approach & Solutions
Spelled-Out AssignmentsGood
Apply the five updates in order — add k, double, subtract 3, halve (keeping the whole part), take the remainder by 7 — each written in full as x = x <op> value, and record x after every step. The right-hand side always reads the old x; the result then replaces it.
Time
O(1)Space
O(1)Java
class Solution {
public int[] assignmentTrace(int x, int k) {
int[] trace = new int[5];
x = x + k;
trace[0] = x;
x = x * 2;
trace[1] = x;
x = x - 3;
trace[2] = x;
x = x / 2;
trace[3] = x;
x = x % 7;
trace[4] = x;
return trace;
}
}Compound Assignment OperatorsOptimal
Use the shorthand forms: x += k, x *= 2, x -= 3, x /= 2 and x %= 7. Each one means "x = x <op> value" and is shorter and harder to mistype. Python writes the whole-number halving as //=. JavaScript has no integer /=, so it keeps Math.floor for that step.
Time
O(1)Space
O(1)Java
class Solution {
public int[] assignmentTrace(int x, int k) {
int[] trace = new int[5];
x += k;
trace[0] = x;
x *= 2;
trace[1] = x;
x -= 3;
trace[2] = x;
x /= 2;
trace[3] = x;
x %= 7;
trace[4] = x;
return trace;
}
}