THN Interview Prep

66. Plus One

At a Glance

  • Topic: math-geometry
  • Pattern: Math simulation (grade-school carry)
  • Difficulty: Easy
  • Companies: Google, Amazon, Microsoft, Apple, Meta
  • Frequency: High
  • LeetCode: 66

Problem (one-liner)

Given a non-empty array of digits representing a non-negative integer (most significant digit first), return the digits of that integer plus one, also as a digit array.

Recognition Cues

  • "Digits of large integer" without bigint
  • Single increment — propagate carry from the right
  • All 9s causes length increase

Diagram

At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.

Loading diagram…

Approaches

  • Brute force — parse to big integer — disallowed / awkward in many languages.
  • Better — carry from least significant (last index) leftward — O(digits) time / O(1) extra if in-place allowed or O(digits) for new slice.

Optimal Solution

Go

package main

func plusOne(digits []int) []int {
	carry := 1
	for index := len(digits) - 1; index >= 0 && carry > 0; index-- {
		sum := digits[index] + carry
		digits[index] = sum % 10
		carry = sum / 10
	}
	if carry > 0 {
		return append([]int{carry}, digits...)
	}
	return digits
}

JavaScript

function plusOne(digits) {
	const result = [...digits];
	let carry = 1;
	for (let index = result.length - 1; index >= 0 && carry > 0; index--) {
		const sum = result[index] + carry;
		result[index] = sum % 10;
		carry = Math.floor(sum / 10);
	}
	if (carry > 0) {
		result.unshift(carry);
	}
	return result;
}

Walkthrough

Input: digits = [1, 2, 9]

index (from right)digit + carrynew digitcarry out
29+1=1001
12+1=330
stop

Result: [1, 3, 0].

Edge Cases

  • [9][1, 0]
  • [0][1] per definition (no leading zeros except zero itself)

Pitfalls

  • Prepending new digit when carry survives past index 0
  • Mutating shared input when tests expect copy

Similar Problems

Variants

  • Add arbitrary small integer k with carry.
  • Big-endian binary increment.

Mind-Map Tags

#carry #digits #simulation #array #math

Last updated on

Spotted something unclear or wrong on this page?

On this page