Check if it is possible to get back to 12 O-clock only by adding or subtracting given seconds in Python

Suppose we have an array of n different second values. We have to check whether it is possible to start from 12 O'clock and go back to 12 by only adding or subtracting the given seconds or not. We can use all given seconds exactly once, we can either add seconds or subtract it.

So, if the input is like seconds = [40,90,50], then the output will be True as we can add 40, then subtract 90, then again add 50 to get back to 12 O'clock.

Algorithm

To solve this, we will follow these steps ?

  • Generate all possible combinations of addition and subtraction for the given seconds
  • For each combination, calculate the total time difference
  • Check if the total difference is divisible by (24 * 60 = 1440) seconds
  • If any combination results in a multiple of 1440 seconds, return True

Implementation

We use bit manipulation to generate all possible combinations. Each bit represents whether to add (1) or subtract (0) a particular second value ?

def solve(seconds):
    size = 2**len(seconds)
    for c in range(size):
        add = 0
        for j in range(len(seconds)):
            if c & (1 << j):
                add += seconds[j]
            else:
                add -= seconds[j]
        if add % (24 * 60) == 0:
            return True
    return False

seconds = [40, 90, 50]
print(solve(seconds))
True

How It Works

The algorithm generates all 2^n combinations where n is the number of seconds. For each combination:

  • If bit j is set, we add seconds[j]
  • If bit j is not set, we subtract seconds[j]
  • We check if the final sum is divisible by 1440 (24 hours * 60 minutes)

Example Walkthrough

For seconds = [40, 90, 50], one valid combination is ?

# Add 40, subtract 90, add 50
result = 40 - 90 + 50
print(f"Result: {result}")
print(f"Divisible by 1440: {result % 1440 == 0}")
Result: 0
Divisible by 1440: True

Time Complexity

The time complexity is O(2^n * n) where n is the number of seconds, as we check all 2^n combinations and for each combination, we iterate through n elements.

Conclusion

This solution uses bit manipulation to generate all possible combinations of adding and subtracting seconds. It returns True if any combination results in a time difference that brings us back to 12 O'clock (divisible by 1440 seconds).

Updated on: 2026-03-25T15:10:42+05:30

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements