Software Engineer | 50+ LeetCode Problems Solved | Go Enthusiast
Check out my profile @tigonguyen
Each solution is documented with:
- Problem Description with LeetCode Link
- Clear Intuition & Implementation Approach
- Complexity Analysis
This is the multi-page printable view of this section. Click here to print.
Software Engineer | 50+ LeetCode Problems Solved | Go Enthusiast
Check out my profile @tigonguyen
Each solution is documented with:
Collection of LeetCode solutions categorized by fundamental data structures. Each solution demonstrates the effective use of specific data structures to solve algorithmic problems.
Given an array of integers nums
and an integer target
, return indices of the two numbers in nums
such that they add up to target
.
Constraints:
Example:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]
For each number in the array, we need its complement (target - number) to form the target sum. Instead of searching for this complement repeatedly, we can use a hash map for O(1) lookups.
func twoSum(nums []int, target int) []int {
seen := make(map[int]int)
for i, num := range nums {
complement := target - num
if j, exists := seen[complement]; exists {
return []int{j, i}
}
seen[num] = i
}
return nil
}
Given the root
of a binary tree, imagine yourself standing on the right side of it. Return the values of the nodes you can see ordered from top to bottom.
Constraints:
[0, 100]
-100 ≤ Node.val ≤ 100
Example:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Explanation: The nodes visible from the right side are 1, 3, and 4.
When viewing a binary tree from the right side, we want to see the rightmost node at each level. Using a queue for level-order traversal (BFS), we can capture the last node at each level to build our right-side view.
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rightSideView(root *TreeNode) []int {
if root == nil {
return []int{}
}
result := []int{}
queue := []*TreeNode{root}
for len(queue) > 0 {
levelSize := len(queue)
for i := 0; i < levelSize; i++ {
node := queue[0]
queue = queue[1:]
// If it's the last node in current level, add to result
if i == levelSize-1 {
result = append(result, node.Val)
}
// Add children to queue
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
}
return result
}
Collection of LeetCode solutions categorized by algorithmic approaches and techniques. Each solution showcases different problem-solving strategies and optimization methods.