Algos and Solutions Flashcards
(6 cards)
Given a list of integers, identify all the duplicate values in the list. Assume that the list can contain both positive and negative numbers, and the order of the list does not matter. A number is considered a duplicate if it appears more than once in the list. Return a list of the duplicate numbers.
Use a set to track seen elements
Use another set to track duplicates
As we loop:
* If number not in seen, add it
* If number in seen, add to duplicates
You are given a list of integers called numbers. Write a function to return any subset of numbers where the elements sum to zero and that does not contain the number 0.
If there are no combinations of elements that sum to zero, return an empty list.
Subset Sum Problem
First, remove all zeroes from the input list (they can’t be part of the result).
Then, generate all non-empty subsets.
For each subset, check if the sum is 0.
If yes, return that subset.
If none found, return [].
Given a list of integers, find the index at which the sum of the left half of the list is equal to the right half.
If there is no index where this condition is satisfied return -1.
Prefix Sum Problem
Get the total sum of the list.
Initialize left_sum = 0
Iterate through the list.
At each index:
*Right sum = total - left_sum - current value.
*If left_sum == right sum → return current index.
*Update left_sum += current value
If loop ends without return → return -1.
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
integer manipulation problem
Use modulus (x % 10) to get the last digit.
Use integer division (x // 10) to drop the last digit.
Use a variable like reversed_x = 0 to build the result:
*reversed_x = reversed_x * 10 + last_digit
Before updating, check if this would cause overflow.
You are given an N-dimensional array (a nested list) and your task is to convert it into a 1D array. The N-dimensional array can have any number of nested lists and each nested list can contain any number of elements. The elements in the nested lists are integers. Write a function that takes an N-dimensional array as input and returns a 1D array.
recursion/iteration problem
Traverse each element in the input list.
If the element is an integer, add it to the output list.
If the element is a list, recursively flatten it and add its elements to the output list.
Repeat until all elements have been processed.