#3751

Total Waviness of Numbers in Range I

Medium
MathDynamic ProgrammingEnumerationDynamic ProgrammingArray
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)

We can optimize by directly calculating waviness without converting numbers to strings repeatedly. Instead, we analyze digits mathematically.

⚙️

Algorithm

3 steps
  1. 1Step 1: Loop through each number from num1 to num2.
  2. 2Step 2: For each number, extract digits and check for peaks and valleys using arithmetic comparisons.
  3. 3Step 3: Sum the waviness counts for each number.
solution.py18 lines
1def total_waviness(num1, num2):
2    total = 0
3    for num in range(num1, num2 + 1):
4        if num < 100:
5            continue
6        waviness = 0
7        prev_digit = num % 10
8        num //= 10
9        curr_digit = num % 10
10        while num > 0:
11            next_digit = num % 10
12            if (curr_digit > prev_digit and curr_digit > next_digit) or (curr_digit < prev_digit and curr_digit < next_digit):
13                waviness += 1
14            prev_digit = curr_digit
15            curr_digit = next_digit
16            num //= 10
17        total += waviness
18    return total

Complexity note: The outer loop runs for each number in the range, and the inner loop processes digits in constant time, leading to O(n) complexity.

  • 1Waviness is only defined for numbers with 3 or more digits.
  • 2Peaks and valleys are determined by comparing adjacent digits.

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