LeetCode-Feedback / LeetCode-Feedback

661 stars 314 forks source link

Fastest runtime solution does not work on all testcases. #23528

Closed blyiu closed 3 weeks ago

blyiu commented 3 weeks ago

LeetCode Username

orb1t

Problem Number, Title, and Link

  1. Majority Element https://leetcode.com/problems/majority-element/

Bug Category

Missing test case (Incorrect/Inefficient Code getting accepted because of missing test cases)

Bug Description

The provided "most efficient code" returns 4 on the following array, when the correct number should be 1 (1 is the majority element). int[] foo = {1, 2, 1, 3, 1, 2, 1, 3, 4, 4, 4}

Language Used for Code

Java

Code used for Submit/Run operation

class Solution {
    public int majorityElement(int[] nums) {
        return majorityElement(nums, 0, nums[0]);
    }

    private int majorityElement(int[] nums, int index, int num) {
        int curCount = 0;
        for (int i = index; i < nums.length; i++) {
            if (nums[i] == num) {
                curCount++;
            } else {
                curCount--;
            }
            if (curCount < 0) {
                return majorityElement(nums, i, nums[i]);
            }
        }
        return num;
    }
}

Expected behavior

Should return 1, but returns 4.

Screenshots

No response

Additional context

No response

sangam9170 commented 3 weeks ago

// The majority element in an array is defined as the element that occurs more than n/2 times, // where n is the total number of elements. In the given test case {1, 2, 1, 3, 1, 2, 1, 3, 4, 4, 4}, // there is no element that satisfies this condition, making this test case invalid for the task // of finding a majority element. // // Additionally, the code has a critical flaw: it assumes that a majority element always exists. // It returns the element that ends up being the majority candidate at the end of the traversal, // but this candidate may not actually appear more than n/2 times in the array. // As a result, the code can produce incorrect results for arrays that do not contain a true majority element.

blyiu commented 3 weeks ago

Oh shoot right I totally forgot about the > n/2 requirement!