Array-based problems on platforms like LeetCode often require advanced problem-solving techniques. Let's explore some challenging problems along with their solutions in Go.
Problem 1: Two Sum
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to the target
.
Solution:
func twoSum(nums []int, target int) []int {
numMap := make(map[int]int)
for i, num := range nums {
complement := target - num
if index, ok := numMap[complement]; ok {
return []int{index, i}
}
numMap[num] = i
}
return nil
}
Problem 2: Maximum Subarray
Given an integer array nums
, find the contiguous subarray (containing at least one number) that has the largest sum and return its sum.
Solution:
func maxSubArray(nums []int) int {
maxSum, currentSum := nums[0], nums[0]
for i := 1; i < len(nums); i++ {
currentSum = max(nums[i], currentSum+nums[i])
maxSum = max(maxSum, currentSum)
}
return maxSum
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
Problem 3: Product of Array Except for Self
Given an integer array nums
, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Solution:
func productExceptSelf(nums []int) []int {
length := len(nums)
left, right := make([]int, length), make([]int, length)
left[0], right[length-1] = 1, 1
for i := 1; i < length; i++ {
left[i] = left[i-1] * nums[i-1]
right[length-i-1] = right[length-i] * nums[length-i]
}
for i := 0; i < length; i++ {
left[i] *= right[i]
}
return left
}
Problem 4: Rotate Array
Given an array, rotate the array to the right by k
steps, where k
is non-negative.
Solution:
func rotate(nums []int, k int) {
k %= len(nums)
reverse(nums)
reverse(nums[:k])
reverse(nums[k:])
}
func reverse(nums []int) {
left, right := 0, len(nums)-1
for left < right {
nums[left], nums[right] = nums[right], nums[left]
left++
right--
}
}
Problem 5: Set Matrix Zeroes
Given an m x n
matrix, if an element is 0
, set its entire row and column to 0
. Do it in place.
Solution:
func setZeroes(matrix [][]int) {
m, n := len(matrix), len(matrix[0])
rows, cols := make(map[int]bool), make(map[int]bool)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if matrix[i][j] == 0 {
rows[i] = true
cols[j] = true
}
}
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if rows[i] || cols[j] {
matrix[i][j] = 0
}
}
}
}
Conclusion
LeetCode problems often challenge developers to employ advanced problem-solving skills using arrays in Go. These solutions showcase efficient approaches to tackle diverse array-related problems. Practicing these problems enhances problem-solving abilities and strengthens proficiency in handling arrays in Go, preparing developers to solve a wide array of computational challenges effectively.
I hope this helps, you!!
More such articles:
https://www.youtube.com/@maheshwarligade