00:00

Problem Statement

Input/Output Examples

Visual Explanation

The first pass writes the left products into the result array. The second pass walks backwards with a single running right product and multiplies it in, so no second array is needed.

Approaches

The prefix-suffix method is linear without division. The brute force multiplies all other elements for every position.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of elements. The main approach makes two passes and uses only the output array; the brute force multiplies n - 1 values for each position.

Interview Tips and Recommended Approach

  • Explain why division is avoided. One zero makes "total / arr[i]" undefined at that position.
  • Reuse the output array. Storing the left products there gives O(1) extra space.
  • Watch for overflow. Use long if the products can be large.
  • Recognise the pattern. Prefix and suffix passes solve many "everything except i" questions.

Recommended Approach: Prefix and Suffix Products

Why: it runs in linear time without division, handles zeros naturally and uses no memory beyond the output.