DSA for Devs
Login

Inputs

Array / Products

poster

Price: $15

pot

Price: $8

decorative light

Price: $22

plant

Price: $10

vase

Price: $18

frame

Price: $12

Sum / Budget

Budget:

$27

Algo

const findTwoSum = (items: Product[], budget: number): Product[] => {
  const itemMap = new Map(); // Initialize an empty map to store the price as key and product as value

  for (let i = 0; i < items.length; i++) {
    const currentProduct = items[i]; // Get the current product from the items array
    const complement = budget - currentProduct.price; // Calculate the complement needed to reach the budget

    if (itemMap.has(complement)) {
      // Check if the complement exists in the map
      return [itemMap.get(complement), currentProduct]; // If found, return the pair of products
    }

    itemMap.set(currentProduct.price, currentProduct); // Add the current product to the map with its price as the key
  }

  return []; // If no pair is found, return an empty array
};

Calculation

Memory

Map

looking for complement

current index

0

Outputs