LeetCode - 1. Two Sum - Brute Force Approach

Visualization

Algorithm Steps

  1. Given an array of numbers nums and a target.
  2. For each element at index i from 0 to n-2 (where n is the array length), iterate over every element with index j from i+1 to n-1.
  3. For each pair (i, j), calculate the sum of nums[i] and nums[j].
  4. If the sum equals the target, return the indices [i, j].

Solution Program in Different Programming Languages Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums) - 1):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]