Question bank › Backtracking
Dsa Backtracking Hard

Grocery Bag Combinations

You are given a list of grocery items with their respective weights and a maximum weight limit for your grocery bag. Your task is to calculate all possible combinations of items that you can carry without exceeding the weight limit. The output should list all unique combinations in lexicographically sorted order. Input Format: - The first line contains the integer `n`, the number of items (1 ≤ n ≤ 20). - The second line contains `n` integers representing the weights of these items (1 ≤ weight ≤ 10). - The third line contains a single integer representing the weight limit of the grocery bag (1 ≤ limit ≤ 50). Output Format: - Print each combination on a new line in lexicographical order. Each combination must be represented by the indices of the items in the input list (1-based index). If there are no valid combinations, print "No valid combinations". Example: Input: 4 1 2 3 4 5 Output: 1 2 1 3 1 4 2 3 1 2 4 1 3 4 2 4 3 4 1 2 3

Key concepts

backtrackingcombinationssearch

Practise this out loud — free

Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.

🎙 Practise this question now
Part of InterviewLab's verified interview question bank. We show the prompt and concepts to practise with — never a copy-paste solution.