Skip to main content

Button with Longest Push Time - LeetCode Solution

Image


In this blog post, we will solve the LeetCode question "Button with Longest Push Time" step by step. We'll start with a brute-force approach, optimize it, and then provide implementations in C++, Java, and Python. Let's also analyze the time complexity and space complexity for each approach.

Problem Description

You are given a 2D array events where:

  • events[i] = [indexi, timei] represents that the button at indexi was pressed at timei.

The array is sorted in increasing order of time.

Objective: Find the index of the button that took the longest time to press. If multiple buttons have the same longest time, return the button with the smallest index.

Example 1:

Input:

[[1,2],[2,5],[3,9],[1,15]]

Output:

1

Explanation:

  • Button 1: Time = 2 (first button press).

  • Button 2: Time = 5 - 2 = 3.

  • Button 3: Time = 9 - 5 = 4.

  • Button 1: Time = 15 - 9 = 6.

The longest press time is 6, which belongs to button 1.

Example 2:

Input:

[[10,5],[1,7]]

Output:

10

Explanation:

  • Button 10: Time = 5.

  • Button 1: Time = 7 - 5 = 2.

The longest press time is 5, which belongs to button 10.

Constraints:

  • 1 <= events.length <= 1000

  • 1 <= indexi, timei <= 10^5

  • The input is sorted by timei.


Brute-Force Approach

Algorithm:

  1. Iterate through the events array.

  2. For each event, calculate the time difference between consecutive button presses.

  3. Keep track of the button with the longest press time. In case of a tie, pick the button with the smallest index.

Code Implementation (Brute-Force)

C++ Code

#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int buttonWithLongestTime(vector<vector<int>>& events) {
        int longestTime = events[0][1];
        int longestButton = events[0][0];

        for (int i = 1; i < events.size(); i++) {
            int duration = events[i][1] - events[i - 1][1];

            if (duration > longestTime || (duration == longestTime && events[i][0] < longestButton)) {
                longestTime = duration;
                longestButton = events[i][0];
            }
        }

        return longestButton;
    }
};

Java Code

class Solution {
    public int buttonWithLongestTime(int[][] events) {
        int longestTime = events[0][1];
        int longestButton = events[0][0];

        for (int i = 1; i < events.length; i++) {
            int duration = events[i][1] - events[i - 1][1];

            if (duration > longestTime || (duration == longestTime && events[i][0] < longestButton)) {
                longestTime = duration;
                longestButton = events[i][0];
            }
        }

        return longestButton;
    }
}

Python Code

def buttonWithLongestTime(events):
    longest_time = events[0][1]
    longest_button = events[0][0]

    for i in range(1, len(events)):
        duration = events[i][1] - events[i - 1][1]

        if duration > longest_time or (duration == longest_time and events[i][0] < longest_button):
            longest_time = duration
            longest_button = events[i][0]

    return longest_button

Complexity Analysis

  • Time Complexity:

    • O(n): We iterate through the events array once.

  • Space Complexity:

    • O(1): No extra space is used apart from variables.


Optimized Approach

Since the brute-force solution is already efficient with O(n) complexity, we don't need further optimization. However, we can ensure the solution is clean and concise while maintaining clarity.

Key Points:

  • One Pass: Iterate through the array and update longestTime and longestButton during the iteration.

  • Tie-Breaking: Use conditions to handle ties when multiple buttons have the same press duration.

The code implementations above are already optimized for the given constraints.



In this problem, we learned how to calculate the button with the longest press time by iterating through the sorted events array. The solution is straightforward and operates in O(n) time, making it optimal for the input size.

Tags

  • LeetCode

  • Data Structures and Algorithms

  • Array Problems

  • Time Complexity O(n)

  • Space Complexity O(1)

  • Programming Interview Questions


Tips for Interviews

  1. Explain Your Approach: Clearly explain how you calculated the press durations and handled ties.

  2. Edge Cases: Mention handling edge cases like single-element arrays.

  3. Justify Complexity: Ensure the interviewer understands why your solution is O(n).


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...

Maximize Amount After Two Days of Conversions | Leetcode Question

When tackling the problem of maximizing the amount of currency after two days of conversions, we encounter an interesting graph-based problem that involves working with exchange rates between various currencies. In this article, we will explore this problem in detail, starting with the brute force approach and refining it to an optimized solution. Problem Explanation You are given a string initialCurrency (the starting currency), along with four arrays: pairs1 and rates1 : Represent exchange rates between currency pairs on Day 1. pairs2 and rates2 : Represent exchange rates between currency pairs on Day 2. The task is to maximize the amount of initialCurrency you can have after performing any number of conversions on both days. You can make conversions using Day 1 rates and then further conversions using Day 2 rates. Key Insights: Conversion rates are valid (no contradictions). Each currency can be converted back to its counterpart at a reciprocal rate (e.g., if USD -> EUR = 2....