LeetCode 2292: Products With Three or More Orders in Two Consecutive Years Solution

Master LeetCode problem 2292 (Products With Three or More Orders in Two Consecutive Years), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2292. Products With Three or More Orders in Two Consecutive Years

Medium

Problem Explanation

Explanation:

To solve this problem, we can iterate through the input list of orders and keep track of the count of orders for each product in consecutive years. We can use a hashmap to store the count of orders for each product in each year. If a product has three or more orders in two consecutive years, we add it to the result list. Finally, we return the list of products that satisfy the given condition.

  • Time complexity: O(n), where n is the number of orders
  • Space complexity: O(n), to store the counts of orders for each product :

Solution Code

import java.util.*;

class Solution {
    public List<Integer> productsWithThreeOrMoreOrders(int[] orders) {
        Map<Integer, Integer> countMap = new HashMap<>();
        List<Integer> result = new ArrayList<>();
        
        for (int i = 0; i < orders.length; i += 2) {
            int productId = orders[i];
            int year = orders[i + 1];
            
            int count = countMap.getOrDefault(productId, 0);
            if (year == 1) {
                count = 0;
            }
            count++;
            countMap.put(productId, count);
            
            if (count >= 3) {
                result.add(productId);
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2292 (Products With Three or More Orders in Two Consecutive Years)?

This page provides optimized solutions for LeetCode problem 2292 (Products With Three or More Orders in Two Consecutive Years) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2292 (Products With Three or More Orders in Two Consecutive Years)?

The time complexity for LeetCode 2292 (Products With Three or More Orders in Two Consecutive Years) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2292 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2292 in Java, C++, or Python.

Back to LeetCode Solutions