KarmSakha
Help

Career Advice

Algorithm Practice: Maximum Subarray, Tie Rules and Boundary Tests

Reviewed: 9 October 2026. The exercises, expected outputs and practice record below are original illustrative material. They are not a company question bank, evidence of a timed interview or a promise of hiring success. Use the language and assistance rules in your actual assessment invitation.

Make practice produce evidence you can inspect

Algorithm practice is more useful when you can explain a contract, reproduce a failure and show why a repair addresses it. A list of completed problems does not independently establish that you understand edge cases. Start with a bounded task, write expected outputs before running code and revisit a changed requirement.

Microsoft's technical-interview guidance discusses clarifying a problem, planning, coding, testing and explaining complexity. Its employer-specific instructions are not a universal Indian interview process. The exercise below is original preparation material with its own declared rules, rather than a Microsoft interview question or official solution.

Choose the practice language you are allowed to use and can explain accurately. This example uses Python. It does not imply that every employer accepts Python, permits external tools or expects this particular algorithm. Check the actual brief before carrying practice assumptions into an assessment.

Keep preparing

Continue with Sarkari Resume Templates₹299 — coaching के एक महीने से काफ़ी सस्ता / far cheaper than a month of coaching
₹299
Buy this eBook

Original task: maximum sum of a nonempty contiguous slice

The exercise accepts one nonempty list containing exact built-in Python integers. Reject a different container type, integer subclasses, Boolean elements and non-integer elements. Negative integers are allowed. The result is a tuple containing the maximum sum, the inclusive start index and the inclusive end index of a nonempty contiguous slice. Do not change the input.

If more than one slice has the same maximum sum, prefer the smaller start index. If the start is also the same, prefer the smaller end index. These tie rules are explicit exercise choices, not requirements of every maximum-subarray problem. An empty slice is not allowed; its zero sum cannot replace a valid negative result.

For [-2, -3, 4, -1, -2, 1, 5, -3], the expected result is (7, 2, 6). Indices 2 through 6 contain [4, -1, -2, 1, 5], which sum to 7. The elements must be adjacent; selecting all positive elements from arbitrary positions would answer a different problem.

Begin with failures that reveal the contract

A tempting shortcut is to initialise the best sum to zero and return zero for an all-negative input. For [-5, -2, -7], that violates the nonempty requirement. The correct result is (-2, 1, 1), representing the single middle element. Zero is not the sum of a permitted slice in that case.

Another error is to report a correct sum with unrelated indices. Tests must check the complete tuple and recompute the sum of the indicated slice. For the all-negative example, a result of (-2, 0, 0) would be wrong because index 0 contains −5. A printed maximum alone would conceal that defect.

The tie rule also changes expected outputs. For [0, 0], all nonempty slices sum to zero. The required result is (0, 0, 0): earliest start, then earliest end. Replacing an equally good result on every iteration would incorrectly extend the reported end to index 1.

Use a running slice ending at each position

At position i, compare starting a new slice at that element with extending the best running slice from the preceding position. If starting is strictly better, restart there. On equality, extend so the earlier start remains available. Compare the resulting running sum with the best overall sum, updating only for a strict improvement.

Initialise both running and best values from the first element. That gives a real nonempty candidate even when every element is negative. Keep the running start separate from the best start and end; a later restart should not overwrite the indices belonging to an earlier best result.

The implementation uses short names and two-space indentation so the complete excerpt remains readable on a narrow screen. Here xs is the input, cur is the best running sum ending at the current position, s is its start, and best, lo, hi describe the best overall result.

def max_slice(xs):
  if type(xs) != list:
    raise TypeError
  if not xs:
    raise ValueError
  for x in xs:
    if type(x) != int:
      raise TypeError
  cur = xs[0]
  best = cur
  s = 0
  lo = 0
  hi = 0
  n = len(xs)
  for i in range(1,n):
    v = cur+xs[i]
    if xs[i] > v:
      cur = xs[i]
      s = i
    else:
      cur = v
    if cur > best:
      best = cur
      lo = s
      hi = i
  return best,lo,hi

The validation pass checks every element before calculating the result. The function reads from the list and maintains scalar state; it never sorts, removes or replaces input elements. Rejecting invalid input is part of this supplied practice contract. A different interview brief may guarantee valid input instead.

Trace the full fixture

PositionRunning and best state after that position
0: −2Running −2 from 0; best −2 at 0–0.
1: −3Starting −3 beats extending to −5. Running −3 from 1; best remains −2 at 0–0.
2: 4Starting 4 beats extending to 1. Running 4 from 2; best 4 at 2–2.
3: −1Extend to 3 from 2; best remains 4 at 2–2.
4: −2Extend to 1 from 2; best remains 4 at 2–2.
5: 1Extend to 2 from 2; best remains 4 at 2–2.
6: 5Extend to 7 from 2; best becomes 7 at 2–6.
7: −3Extend to 4 from 2; best remains 7 at 2–6.

At each position, any contiguous slice ending there either starts there or extends a slice ending at the previous position. Retaining the best such previous sum is enough to make that comparison. The equality decisions preserve the stated start preference; retaining an earlier overall best on equality preserves the end preference as scanning advances.

Under a bounded-size integer arithmetic assumption, validation and the main scan take O(n) time. Additional algorithm state is O(1); the output tuple has three values. Python's arbitrarily large integers mean arithmetic cost can depend on bit length, so the stated linear-time analysis does not claim constant-cost arithmetic for every possible integer size.

Build an independent test oracle

For small inputs, enumerate every permitted slice, calculate each sum and rank candidates by highest sum, then smallest start and smallest end. That slower enumeration provides expected results independently of the running-sum implementation. Check that the returned indices are valid and that the indicated slice has the returned sum.

Useful explicit fixtures include [5] returning (5, 0, 0), [-5, -2, -7] returning (-2, 1, 1), [0, 0] returning (0, 0, 0) and [1, -1, 1] returning (1, 0, 0). The last case preserves the earlier, shorter winning slice rather than replacing it with the equal-sum slice 0–2.

Include invalid cases such as [], [True], [1, 2.5] and a tuple container. If the contract excludes subclasses, test those too. Preserve a copy of each valid input and compare it afterwards. An expected-output table is a test plan until code is actually executed; do not describe planned cases as a passed run.

Practise a changed requirement separately

Suppose the revised task allows an empty slice and requires an explicit empty representation when it wins. For an all-negative list, zero may then become the correct sum, but you must agree how the empty indices are represented and how ties involving zero are handled. The current function intentionally implements the original nonempty contract and does not implement that variant.

Similarly, asking for every maximum-sum slice changes the output and storage demands. The current function returns one chosen tuple. Do not claim that its constant additional state can directly store an arbitrarily large collection of tied slices. Identify the revised output before proposing a different implementation.

Keep a practice record that describes actual work

Record the contract, a failing input, its expected output, the observed result and the exact repair you made. Re-run relevant cases after changing code or assumptions. A meaningful note might explain that an all-negative index defect was reproduced and repaired; it should not turn that exercise into a fabricated company interview or production achievement.

For a different pointer-based task, see the coding interview guide. For discussing service-level concurrency, use the system design guide. Keep algorithm correctness separate from system availability and from behavioural interview storytelling.

Frequently asked questions

Why does the function not return zero for all-negative inputs?

The supplied contract requires a nonempty slice. The largest permitted sum is therefore the least negative element or another actual nonempty slice, rather than an invented empty result.

Must I use this exact tie policy?

No. Clarify the task's required policy. This example states one policy so its complete outputs can be checked consistently.

Does solving more problems guarantee interview success?

No such outcome follows here. Use practice to produce evidence of reasoning, implementation and testing under the actual role's requirements.

Related guides

Ask KarmSakha AI