Skip to main content

Final Prices With a Special Discount in a Shop – LeetCode Solution Explained

When tackling coding problems, it's important to understand the problem thoroughly and work through solutions step-by-step. In this blog, we will explore the LeetCode problem "1475 Final Prices With a Special Discount in a Shop". We'll walk through the problem statement, approach it with a beginner-friendly brute force solution, and analyze its time and space complexity. Finally, we'll discuss any possible optimizations to improve efficiency.


Problem Statement

You are given an integer array prices where prices[i] represents the price of the ith item in a shop. There is a special discount rule:

  • If you buy the ith item, you receive a discount equal to prices[j], where j is the smallest index such that j > i and prices[j] <= prices[i].

  • If no such j exists, you get no discount for that item.

Your task is to return a new array answer, where answer[i] is the final price you pay for the ith item after applying the discount.

Examples

Example 1:

Input: prices = [8, 4, 6, 2, 3]
Output: [4, 2, 4, 2, 3]

Explanation:

  • For prices[0] = 8, the discount is prices[1] = 4, so the final price is 8 - 4 = 4.

  • For prices[1] = 4, the discount is prices[3] = 2, so the final price is 4 - 2 = 2.

  • For prices[2] = 6, the discount is prices[3] = 2, so the final price is 6 - 2 = 4.

  • For prices[3] = 2 and prices[4] = 3, no discount applies.

Example 2:

Input: prices = [1, 2, 3, 4, 5]
Output: [1, 2, 3, 4, 5]

Explanation: In this case, no item has a valid discount available.

Example 3:

Input: prices = [10, 1, 1, 6]
Output: [9, 0, 1, 6]

Explanation:

  • For prices[0] = 10, the discount is prices[1] = 1, so the final price is 10 - 1 = 9.

  • For prices[1] = 1, the discount is prices[2] = 1, so the final price is 1 - 1 = 0.

  • For prices[2] = 1 and prices[3] = 6, no discount applies.


Approach 1: Brute Force Solution

The most intuitive way to solve this problem is by using two nested loops. For each item in the array, we look for the first eligible discount in the remaining items.

Algorithm

  1. Loop through each price in the array using index i.

  2. For each i, iterate through the subsequent prices (from i+1 to the end) using index j.

  3. If you find a price prices[j] such that prices[j] <= prices[i], apply the discount and break the inner loop.

  4. If no such j exists, the price remains unchanged.

  5. Return the modified prices array.

Code Implementation (CPP)

class Solution {
public:
    vector<int> finalPrices(vector<int>& prices) {
        for (int i = 0; i < prices.size(); i++) {
            for (int j = i + 1; j < prices.size(); j++) {
                if (prices[j] <= prices[i]) {
                    prices[i] = prices[i] - prices[j];
                    break;
                }
            }
        }
        return prices;
    }
};

Time Complexity

  • Outer loop: Runs n times (for each price).

  • Inner loop: In the worst case, it runs up to n-i-1 times.

Space Complexity

  • The solution uses no additional data structures.


Optimized Approach: Using a Stack

While the brute force solution works, it’s inefficient for large inputs. We can optimize it using a monotonic stack, which allows us to keep track of potential discounts more efficiently.

Algorithm

  1. Use a stack to store indices of prices in decreasing order.

  2. Traverse the prices array from left to right.

  3. For each price, check the top of the stack:

    • If the current price is less than or equal to the price at the top index, calculate the discount and update the array.

    • Pop the top index from the stack.

  4. Push the current index onto the stack.

  5. Return the modified prices array.

Code Implementation

class Solution {
public:
    vector<int> finalPrices(vector<int>& prices) {
        stack<int> st;
        for (int i = 0; i < prices.size(); i++) {
            while (!st.empty() && prices[st.top()] >= prices[i]) {
                int idx = st.top();
                st.pop();
                prices[idx] -= prices[i];
            }
            st.push(i);
        }
        return prices;
    }
};

Time Complexity

  • Each element is pushed onto the stack once and popped once.

  • O(n)

Space Complexity

  • The stack stores indices, which in the worst case can grow to .

  • O(n)


Comparison of Approaches

Approach
Notes
Brute Force ->Simple but inefficient
Stack Optimization ->Efficient for larger datasets

This problem highlights the power of monotonic stacks in optimizing problems that involve comparisons across array elements. By practicing this approach, you’ll develop skills applicable to many similar problems.

Popular posts from this blog

Maximum Difference Between Even and Odd Frequency | LeetCode

We are given a string consisting of lowercase English letters. Our task is to find the maximum difference between the frequency of two characters in the string such that: One of the characters has an even frequency . The other character has an odd frequency . The difference is calculated as:  odd_frequency - even_frequency We need to return the maximum possible difference between the odd and even frequencies. Example Walkthrough Let's take a couple of examples to better understand the problem: Example 1: Input:  s = "aaaaabbc" Frequencies: 'a' → 5 (odd) 'b' → 2 (even) 'c' → 1 (odd) Here, the maximum odd frequency is 5 (for 'a') and the maximum even frequency is 2 (for 'b'). Therefore, the result is: maxOdd - maxEven = 5 - 2 = 3 Example 2: Input:  s = "abcabcab" Frequencies: 'a' → 3 (odd) 'b' → 2 (even) 'c' → 2 (even) The maximum odd frequency is 3 (for 'a') and the maximum even fr...

Top 10 Beginner-Friendly LeetCode Questions and Their Solutions

If you're new to solving coding problems on LeetCode, it can feel overwhelming. Where do you start? Which problems are suitable for beginners? Don’t worry! In this blog post, I’ll guide you through   10 beginner-friendly LeetCode questions   that are perfect for getting started on your coding journey. These problems will help you build confidence, improve your problem-solving skills, and lay a solid foundation in data structures and algorithms. Why Start with Beginner-Friendly Problems? Before diving into advanced topics like dynamic programming or graph theory, it’s essential to: Build a strong foundation in basic programming concepts. Understand how to approach a coding problem methodically. Gain familiarity with LeetCode’s platform and its problem structure. The following problems are simple yet impactful, designed to introduce you to common techniques like loops, arrays, strings, and basic math operations. 10 Beginner-Friendly LeetCode Problems 1.  Two Sum (Easy) Prob...

Count Mentions Per User | Leetcode | Problem Explanation and Solution Approaches

Tracking mentions in messages is a common task in communication-based applications. This blog post breaks down a complex problem, "Count Mentions Per User," and walks through how to solve it efficiently with a clear understanding of all rules and constraints. Problem Statement You are given: An integer numberOfUsers representing the total number of users. An array events where each element is of size n x 3 and describes either a "MESSAGE" or an "OFFLINE" event. Each event can be one of the following types: MESSAGE Event : ["MESSAGE", "timestamp", "mentions_string"] Indicates that users are mentioned in a message at a specific timestamp. The mentions_string can contain: id<number> : Mentions a specific user (e.g., id0 , id1 ). ALL : Mentions all users (online or offline). HERE : Mentions only users who are online at the time. OFFLINE Event : ["OFFLINE", "timestamp", "id<number>"] In...