Workspace Power Of Two
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Power of Two visualizer

Return 1 if target is two raised to a nonnegative integer power and 0 otherwise. The values list is unused.

EXECUTION LAB

Return 1 if target is two raised to a nonnegative integer power and 0 otherwise. The values list is unused.

Input and constraints
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
if (target <= 0):
return 0
remaining = (target & (target - 1))
if (remaining == 0):
return 1
return 0

Visualizer

Step 1 of 3

Empty array

Reject a nonpositive target before inspecting bits

Reject a nonpositive target before inspecting bits.

Variable watch

target 16

Step explanation

Reject a nonpositive target before inspecting bits.

comparisons 0reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(1) for fixed-width inputs time · O(1) space

Worked explanation

A binary shelf label for a power of two lights exactly one switch.

Guided solution

A positive power of two has exactly one set bit. Clearing that bit produces zero.

O(1) for fixed-width inputs time · O(1) auxiliary space

Examples

Worked example · {"values":[],"target":16} ⇒ 1

Edge case 1 · {"values":[],"target":0} ⇒ 0

Edge case 2 · {"values":[],"target":12} ⇒ 0

Edge case 3 · {"values":[],"target":-2} ⇒ 0

Progressive hints

Hint 1A binary shelf label for a power of two lights exactly one switch.
Hint 2A positive power of two has exactly one set bit. Clearing that bit produces zero.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Zero also satisfies the mask equality and needs a separate positivity test.

Interview follow-up

How would you recognize a power of four?

Continue learning

Practice related DSA questions in the same topic.