title: Alternating Digit Sum
slug: alternating-digit-sum
difficulty: easy
leetcode_id: 2544
leetcode_url: https://leetcode.com/problems/alternating-digit-sum/
categories:
  - math
patterns:
  - slug: greedy
    is_optimal: true

function_signature: "def alternate_digit_sum(n: int) -> int:"

test_cases:
  visible:
    - input: { n: 521 }
      expected: 4
    - input: { n: 111 }
      expected: 1
    - input: { n: 886996 }
      expected: 0
  hidden:
    - input: { n: 1 }
      expected: 1
    - input: { n: 10 }
      expected: 1
    - input: { n: 99 }
      expected: 0
    - input: { n: 12345 }
      expected: 3
    - input: { n: 54321 }
      expected: 3

description: |
  You are given a positive integer `n`. Each digit of `n` has a sign according to the following rules:

  - The **most significant digit** is assigned a **positive** sign.
  - Each other digit has an opposite sign to its adjacent digits.

  Return *the sum of all digits with their corresponding sign*.

constraints: |
  - `1 <= n <= 10^9`

examples:
  - input: "n = 521"
    output: "4"
    explanation: "(+5) + (-2) + (+1) = 4."
  - input: "n = 111"
    output: "1"
    explanation: "(+1) + (-1) + (+1) = 1."
  - input: "n = 886996"
    output: "0"
    explanation: "(+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0."

explanation:
  intuition: |
    Imagine you have a row of people standing in a line, and they alternate between facing forward (+) and backward (-). The first person always faces forward.

    The **core insight** is that the first digit (most significant) is always positive, and the sign alternates from there. Think of it like a zigzag pattern: `+`, `-`, `+`, `-`, and so on.

    The challenge is that we receive the number as an integer, not as a string of digits. We have two main approaches:

    1. **Convert to string**: Easy to iterate left-to-right, directly accessing each digit
    2. **Use modulo arithmetic**: Extract digits from right-to-left using `% 10` and `// 10`

    The string approach is more intuitive since we process digits in the natural reading order (left-to-right), making it easy to assign the correct sign starting from positive.

  approach: |
    We solve this using a **String Conversion Approach**:

    **Step 1: Convert the number to a string**

    - Convert `n` to a string to easily access each digit
    - This allows left-to-right traversal, matching the problem's sign assignment order

    &nbsp;

    **Step 2: Initialise tracking variables**

    - `total`: Set to `0` to accumulate our alternating sum
    - `sign`: Set to `1` (positive) since the first digit is always positive

    &nbsp;

    **Step 3: Iterate through each digit**

    - For each character in the string:
      - Convert the character back to an integer
      - Multiply by the current sign and add to total
      - Flip the sign: multiply by `-1`

    &nbsp;

    **Step 4: Return the result**

    - Return `total` after processing all digits

    &nbsp;

    This approach works because we process digits in their natural order (most significant first), allowing us to easily assign alternating signs starting with positive.

  common_pitfalls:
    - title: Processing Digits Right-to-Left
      description: |
        Using modulo (`% 10`) extracts digits from right-to-left (least significant first). This means you'd process `521` as `1, 2, 5`.

        The problem states the **most significant digit** (leftmost) is positive. If you process right-to-left, you need to track whether the total number of digits is odd or even to determine the correct starting sign.

        For example, `521` has 3 digits (odd), so the rightmost digit gets `+` sign when processed right-to-left. But `5210` has 4 digits (even), so the rightmost would get `-` sign.

        Converting to a string and processing left-to-right avoids this complexity entirely.
      wrong_approach: "Using % 10 without adjusting for digit count"
      correct_approach: "Convert to string for natural left-to-right processing"

    - title: Forgetting to Flip the Sign
      description: |
        A common mistake is incrementing or using a counter to determine the sign instead of simply flipping it.

        Using `sign = -sign` or `sign *= -1` on each iteration is cleaner and less error-prone than checking if the index is odd or even.
      wrong_approach: "Using if-else or modulo on index"
      correct_approach: "Flip sign each iteration with sign *= -1"

    - title: Integer Overflow (Not Applicable in Python)
      description: |
        In languages like C++ or Java, you might worry about overflow when handling numbers up to `10^9`. However, in Python, integers have arbitrary precision, so this isn't a concern.

        Even the sum of alternating digits for the maximum input can't exceed the input value itself, so overflow isn't an issue in any language for this problem.

  key_takeaways:
    - "**String conversion simplifies digit access**: When you need left-to-right digit processing, converting to string is often cleaner than modulo arithmetic"
    - "**Sign flipping pattern**: Alternating signs can be elegantly handled by multiplying by `-1` each iteration"
    - "**Right-to-left vs left-to-right**: Modulo gives digits in reverse order; consider which direction your problem needs"
    - "**Similar problems**: This pattern appears in problems involving alternating operations or checkerboard-like patterns"

  time_complexity: "O(d) where d is the number of digits in `n`. We process each digit exactly once. Since `n <= 10^9`, we have at most 10 digits, making this effectively O(1)."
  space_complexity: "O(d) for the string representation of the number. With at most 10 digits, this is effectively O(1)."

solutions:
  - approach_name: String Conversion
    is_optimal: true
    code: |
      def alternate_digit_sum(n: int) -> int:
          # Convert to string for easy left-to-right access
          digits = str(n)
          total = 0
          # First digit is always positive
          sign = 1

          for char in digits:
              # Convert character to integer and apply sign
              total += sign * int(char)
              # Flip sign for next digit
              sign *= -1

          return total
    explanation: |
      **Time Complexity:** O(d) where d is the number of digits (at most 10 for n <= 10^9).

      **Space Complexity:** O(d) for the string representation.

      We convert the number to a string and iterate left-to-right, applying alternating signs starting with positive. The sign flips after each digit.

  - approach_name: Mathematical (Right-to-Left)
    is_optimal: false
    code: |
      def alternate_digit_sum(n: int) -> int:
          total = 0
          # Sign for the LAST digit (will be adjusted based on digit count)
          sign = 1

          while n > 0:
              # Extract the last digit
              digit = n % 10
              # Add with current sign
              total += sign * digit
              # Flip sign for next digit (going right-to-left)
              sign *= -1
              # Remove the last digit
              n //= 10

          # After the loop, sign has been flipped one extra time
          # If sign is now -1, we had an odd number of digits (correct)
          # If sign is now +1, we had an even number of digits (need to negate)
          # Equivalently: multiply by -sign to correct the orientation
          return total * -sign
    explanation: |
      **Time Complexity:** O(d) where d is the number of digits.

      **Space Complexity:** O(1) - no string allocation needed.

      This approach extracts digits right-to-left using modulo. The tricky part is that we process in reverse order, so we need to adjust the final sign based on whether we had an odd or even number of digits. The `* -sign` at the end corrects for this.

      While this uses O(1) space, it's less intuitive than the string approach due to the sign correction logic.
