Next Lexicographic Ordering Plus Left-to-Right Calculator
Arrays & HashingAuto-graded · 19 test casesLast updated
Rearrange an array in place into its next lexicographic ordering, and evaluate a parenthesis-free arithmetic string with truncating division, both in linear time.
Next Ordering and Quick Calculator
Write one function that solves two independent tasks and returns both results.
Task 1: Advance the ordering
You get a list of integers arr. Rearrange it in place so that it becomes the next arrangement in lexicographic (dictionary) order.
- Compare two arrangements element by element, from the left. The first position where they differ decides which one is larger.
- If
arris already the largest possible arrangement of its values, rearrange it into the smallest one, which is ascending order. - The list may contain repeated values. The "next" arrangement is the smallest arrangement that is strictly greater than the current one. If no strictly greater arrangement exists (for example
[2, 2, 2], or a list of length 0 or 1), wrap around to the ascending arrangement, which may be the list itself.
Aim for O(n) time and O(1) extra space.
Task 2: Evaluate the formula
You get a string formula that contains non-negative integers, the operators +, -, *, /, and optional spaces. There are no parentheses.
*and/take precedence over+and-.- Operators of equal precedence are applied from left to right.
/is integer division that truncates toward zero.- A string that is empty or contains only spaces evaluates to
0. - The formula is always valid, and no division by zero occurs.
- Spaces may appear anywhere between tokens, including at the start and end, and they never split a number.
Aim for O(n) time and O(1) extra space.
Return value
Return a dictionary with two keys:
"permutation": the rearranged list from Task 1 (the same list object, modified in place)."value": the integer result from Task 2.
Constraints
0 <= len(arr) <= 10^4arrcontains integers, and duplicates are allowed.0 <= len(formula) <= 10^5- All numbers in
formulaare non-negative integers, and every intermediate and final result fits in a 64-bit signed integer. formulacontains only digits, spaces, and the characters+ - * /.
Examples
Example 1
Input: next_order_and_calc([1, 2, 3], '3 + 4 * 2 / 2')
Output: {'permutation': [1, 3, 2], 'value': 7}
Example 2
Input: next_order_and_calc([3, 2, 1], '10 - 3 * 2')
Output: {'permutation': [1, 2, 3], 'value': 4}
Example 3
Input: next_order_and_calc([1, 3, 2], '7 / 2 + 5')
Output: {'permutation': [2, 1, 3], 'value': 8}
Example 4
Input: next_order_and_calc([1, 2, 3, 4], '100 / 3 * 2 - 7')
Output: {'permutation': [1, 2, 4, 3], 'value': 59}
Hints
Hint 1
For the ordering task, scan from the right to find the last position whose value is strictly smaller than its right neighbour. Everything to the right of it is already in non-increasing order.
Hint 2
Swap that pivot with the rightmost element that is strictly greater than it, then reverse the part after the pivot. If no pivot exists, the reverse covers the whole list.
Hint 3
For the calculator, keep a running total of finished terms plus the current term. When you read an operator, `*` and `/` modify the current term, while `+` and `-` commit it and start a new one. Handle truncation toward zero by dividing absolute values and fixing the sign.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Task 1: next ordering
Approach.
- Scan from the right to find the pivot: the largest index
iwitharr[i] < arr[i+1]. The suffix afteriis non-increasing, so it is already the largest arrangement of its elements. - If a pivot exists, scan from the right for the first element strictly greater than
arr[i]and swap the two. Because the suffix is non-increasing, this is the smallest suffix value that exceeds the pivot. - Reverse everything after the pivot. After the swap the suffix is still non-increasing, so reversing makes it ascending, which is its smallest arrangement.
If no pivot exists, the whole list is non-increasing. The reverse in step 3 then covers the entire list and produces the ascending ordering, so no special case is needed.
Why it is correct.
- No rearrangement of the suffix alone can give a larger list, so the pivot is the rightmost position that can grow.
- Raising the pivot by the smallest possible amount (the next larger suffix value) and then arranging the rest as small as possible gives the smallest strictly greater arrangement.
- The comparisons are non-strict in the pivot search (
>=) and strict in the successor search (<=is skipped). This makes duplicates work. For example,[1, 5, 1]becomes[5, 1, 1], and[2, 2, 2]stays unchanged.
Task 2: calculator
Approach. Any parenthesis-free formula is a signed sum of terms, and each term is a left-to-right chain of * and /. Keep three scalars:
total: the sum of completed terms.term: the current term, still open to*and/.number: the integer currently being read.
When a number ends, apply the operator that preceded it:
+: addtermtototal, then start a new term withnumber.-: addtermtototal, then start a new term with-number.*: multiplytermbynumber./: dividetermbynumber, truncating toward zero. Divide the absolute values and negate the quotient if the signs differ, because Python's//floors.
Loop one index past the end of the string so that a sentinel flushes the last number. Skip spaces. After the loop, add the final term to total. Starting with operation = '+' and term = 0 makes the first number behave like 0 + number, and an empty string yields 0.
Why it is correct. Every + or - ends a term, so committing there is exactly the precedence rule. Folding * and / into the current term, in order, gives left-to-right associativity. Negating a term at a - is safe for division because truncation toward zero is symmetric, so -(a / b) equals (-a) / b under truncation.
Complexity
- Time: O(n + m), where
n = len(arr)andm = len(formula). Each part uses a constant number of linear passes. - Space: O(1) extra. The list is modified in place and the calculator keeps only a few scalars.
Reference solution
from typing import Dict, List
def next_order_and_calc(arr: List[int], formula: str) -> Dict[str, object]:
# ---- Task 1: next lexicographic ordering, in place ----
n = len(arr)
i = n - 2
while i >= 0 and arr[i] >= arr[i + 1]:
i -= 1
if i >= 0:
j = n - 1
while arr[j] <= arr[i]:
j -= 1
arr[i], arr[j] = arr[j], arr[i]
left, right = i + 1, n - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
# ---- Task 2: evaluate the formula ----
total = 0
term = 0
number = 0
operation = '+'
length = len(formula)
def apply(previous: str, value: int) -> None:
nonlocal total, term
if previous == '+':
total += term
term = value
elif previous == '-':
total += term
term = -value
elif previous == '*':
term *= value
else:
quotient = abs(term) // abs(value)
if (term < 0) != (value < 0):
quotient = -quotient
term = quotient
for index in range(length + 1):
if index < length and formula[index].isdigit():
number = number * 10 + ord(formula[index]) - ord('0')
elif index < length and formula[index].isspace():
continue
else:
apply(operation, number)
number = 0
if index < length:
operation = formula[index]
total += term
return {'permutation': arr, 'value': total}