Brute Force
Intuition
For each element in the array, compute the product of every other element by iterating through the entire array and skipping the current index. This is the most direct approach: for every position i, multiply all elements except the one at i. While simple, this requires a nested loop and results in quadratic time complexity.
Algorithm
- Create a result array of the same length as the input.
- For each index i, iterate through the array and multiply all elements where the index is not equal to i.
- Store the computed product in result[i].
- Return the result array.
O(n^2)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> result(n, 1);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j) {
result[i] *= nums[j];
}
}
}
return result;
}
};class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = 1;
for (int j = 0; j < n; j++) {
if (i != j) {
result[i] *= nums[j];
}
}
}
return result;
}
}def productExceptSelf(nums: list[int]) -> list[int]:
n = len(nums)
result = [1] * n
for i in range(n):
for j in range(n):
if i != j:
result[i] *= nums[j]
return resultfunc productExceptSelf(nums []int) []int {
n := len(nums)
result := make([]int, n)
for i := 0; i < n; i++ {
result[i] = 1
for j := 0; j < n; j++ {
if i != j {
result[i] *= nums[j]
}
}
}
return result
}