Ice Cream Parlor

  • + 0 comments

    JavaScript solution with comments:

    function icecreamParlor(m, arr) {
        // Write your code here
        let ansArr = []; // Initialize an empty array to store the result
    
        for (let i = 0; i < arr.length; i++) { // Loop through each element in the array
            let canBreak = false; // Initialize a flag to indicate if a pair is found for the current element
            let flavorA = arr[i]; // Get the current element as flavorA
    
            for (let j = i + 1; j < arr.length; j++) { // Iterate through the remaining elements in the array
                let flavorB = arr[j]; // Get the next element as flavorB
    
                if (flavorA + flavorB === m) { // Check if the sum of flavorA and flavorB equals m
                    canBreak = true; // Set the flag to true as a pair is found
                    ansArr.push(i + 1, j + 1); // Add the indices (1-based) of the pair to the ansArr
                    break; // Exit the inner loop since a pair is found
                }
            }
    
            if (canBreak) { // Check if a pair is found
                break; // Exit the outer loop since a pair is found
            }
        }
    
        return ansArr; // Return the ansArr with the indices of the pair
    }