Algos Flashcards

1
Q

Given an integer, convert it to a Roman numeral

A

class Solution:
def intToRoman(self, num: int) -> str:
# Creating Dictionary for Lookup
num_map = {
1: “I”,
5: “V”, 4: “IV”,
10: “X”, 9: “IX”,
50: “L”, 40: “XL”,
100: “C”, 90: “XC”,
500: “D”, 400: “CD”,
1000: “M”, 900: “CM”,
}

    # Result Variable
    r = ''
    
    
    for n in [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]:
        # If n in list then add the roman value to result variable
        while n <= num:
            r += num_map[n]
            num-=n
    return r
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

2sum (unordered): Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

A

func twoSum(nums []int, target int) []int {
// Space: O(n)
s := make(map[int]int)

// Time: O(n)
for idx, num := range nums {
    // Time: O(1)
    if pos, ok := s[target-num]; ok {
        return []int{pos, idx}
    }
    s[num] = idx
}
return []int{} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

2sum (ordered): Given a sorted array of unique integers and a target integer, return true if there exists a pair of numbers that sum to target, false otherwise. This problem is similar to Two Sum.

Strategy: 2 pointers

A

func checkForTarget(nums []int, target int) bool {
left := 0
right := len(nums) - 1

for left < right {
	curr := nums[left] + nums[right]
	if curr == target {
		return true
	}
	if curr > target {
		right -= 1
	} else {
		left += 1
	}
}

return false }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Best time to buy and sell stock:

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0

Strategy: two pointers

A

class Solution:
def maxProfit(self, prices):
buy = prices[0]
profit = 0
for i in range(1, len(prices)):
if prices[i] < buy:
buy = prices[i]
elif prices[i] - buy > profit:
profit = prices[i] - buy
return profit

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

A

public class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] res = new int[n];
res[0] = 1;
for (int i = 1; i < n; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = n - 1; i >= 0; i–) {
res[i] *= right;
right *= nums[i];
}
return res;
}

OUTPUT:
Outside) Result array: [1 1 2 6]
3)Result array: [1 1 2 6]
Right: 4
2)Result array: [1 1 8 6]
Right: 12
1)Result array: [1 12 8 6]
Right: 24
0)Result array: [24 12 8 6]
Right: 24
[24 12 8 6]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Given an integer array nums, find the subarray with the largest sum, and return its sum.

Strategy: Sliding window

A

func maxSubArray(nums []int) int {
cur := nums[0]
ans := nums[0]

// Iterate through each element starting from the second one
for i := 1; i < len(nums); i++ {
    // Update cur to be the maximum of either nums[i]+cur or nums[i]
    cur = max(nums[i]+cur, nums[i])
    // Update ans to be the maximum of ans and cur
    ans = max(ans, cur)
}

return ans  // Return the maximum sum subarray }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Given an integer array nums, find a
subarray that has the largest product, and return the product.

Strategy: Sliding window

A

class Solution:
def maxProduct(self, nums: List[int]) -> int:
curMax, curMin = 1, 1
res = nums[0]

    for n in nums:
        vals = (n, n * curMax, n * curMin)
        curMax, curMin = max(vals), min(vals)
		
        res = max(res, curMax)
        
    return res
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Find Minimum in Rotated Sorted Array:

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:

[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], …, a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], …, a[n-2]].

Given the sorted rotated array nums of unique elements, return the minimum element of this array.

You must write an algorithm that runs in O(log n) time.

A

func findMin(nums []int) int {
left, right := 0, len(nums)-1
for left < right {
mid := (left + right) / 2
if nums[mid] > nums[right] {
left = mid + 1
} else {
right = mid
}
}

return nums[left] }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Search in Rotated Sorted Array:
There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

You must write an algorithm with O(log n) runtime complexity.

A

func search(nums []int, target int) int {
low, high := 0, len(nums) - 1

for low <= high {
    mid := (low + high) / 2

    if nums[mid] == target {
        return mid
    }

    if nums[low] <= nums[mid] {
        if nums[low] <= target && target < nums[mid] {
            high = mid - 1
        } else {
            low = mid + 1
        }
    } else {
        if nums[mid] < target && target <= nums[high] {
            low = mid + 1
        } else {
            high = mid - 1
        }
    }
}

return -1 }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly