Find the majority element, which appears more than half the time Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Perm-Missing-Elem: 100% functional score, but only 60% performanceDetermining the existence of string IntersectionsFind the dominator in an array of integersJavaScript : Search highest ID in JSON-structure. Increment & return itFind the most frequent element in a sequence without copying elementsReconstruct a string, given a list of subsequence tripletsReturn a sorted ordering of courses such that we can finish all coursesHash table solution to twoSumSum of a sublistFind the elements that appear only once

Can we see the USA flag on the Moon from Earth?

Dating a Former Employee

The logistics of corpse disposal

Does Amorayim read berayta in Gemara rather than recite it

Why am I getting the error "non-boolean type specified in a context where a condition is expected" for this request?

A binary hook-length formula?

How does debian/ubuntu knows a package has a updated version

Why was the term "discrete" used in discrete logarithm?

What would be the ideal power source for a cybernetic eye?

Why are both D and D# fitting into my E minor key?

porting install scripts : can rpm replace apt?

Is it true that "carbohydrates are of no use for the basal metabolic need"?

Should I use a zero-interest credit card for a large one-time purchase?

What is Wonderstone and are there any references to it pre-1982?

Is the Standard Deduction better than Itemized when both are the same amount?

What does an IRS interview request entail when called in to verify expenses for a sole proprietor small business?

How to bypass password on Windows XP account?

Deactivate Gutenberg tipps forever - not Gutenberg

Apollo command module space walk?

Why do people hide their license plates in the EU?

Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?

Ring Automorphisms that fix 1.

Tht Aain’t Right... #2

Can an alien society believe that their star system is the universe?



Find the majority element, which appears more than half the time



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Perm-Missing-Elem: 100% functional score, but only 60% performanceDetermining the existence of string IntersectionsFind the dominator in an array of integersJavaScript : Search highest ID in JSON-structure. Increment & return itFind the most frequent element in a sequence without copying elementsReconstruct a string, given a list of subsequence tripletsReturn a sorted ordering of courses such that we can finish all coursesHash table solution to twoSumSum of a sublistFind the elements that appear only once



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








10












$begingroup$


The task:




Given a list of elements, find the majority element, which appears
more than half the time (> floor(len(lst) / 2.0)).



You can assume that such element exists.



For example, given [1, 2, 1, 1, 3, 4, 0], return 1.




My solution:



const lst = [1, 2, 1, 1, 3, 4, 0];
const findMajorityElem = lst => lst.reduce((acc, x) => acc.major[1] < acc[x]) acc.major = [x, acc[x]];
return acc;
, major: null).major[0];

console.log(findMajorityElem(lst));









share|improve this question











$endgroup$







  • 5




    $begingroup$
    In the example [1, 2, 1, 1, 3, 4, 0], 1 appears 3 times, floor(len(lst) / 2.0)) is 3, and since 3 is not more than 3, therefore 1 is not the majority element, and the example list doesn't have a majority element.
    $endgroup$
    – janos
    Apr 1 at 16:47











  • $begingroup$
    @janos the example is inaccurate. However it explicitly says I can assume that there exists a majority element
    $endgroup$
    – thadeuszlay
    Apr 1 at 16:54

















10












$begingroup$


The task:




Given a list of elements, find the majority element, which appears
more than half the time (> floor(len(lst) / 2.0)).



You can assume that such element exists.



For example, given [1, 2, 1, 1, 3, 4, 0], return 1.




My solution:



const lst = [1, 2, 1, 1, 3, 4, 0];
const findMajorityElem = lst => lst.reduce((acc, x) => acc.major[1] < acc[x]) acc.major = [x, acc[x]];
return acc;
, major: null).major[0];

console.log(findMajorityElem(lst));









share|improve this question











$endgroup$







  • 5




    $begingroup$
    In the example [1, 2, 1, 1, 3, 4, 0], 1 appears 3 times, floor(len(lst) / 2.0)) is 3, and since 3 is not more than 3, therefore 1 is not the majority element, and the example list doesn't have a majority element.
    $endgroup$
    – janos
    Apr 1 at 16:47











  • $begingroup$
    @janos the example is inaccurate. However it explicitly says I can assume that there exists a majority element
    $endgroup$
    – thadeuszlay
    Apr 1 at 16:54













10












10








10





$begingroup$


The task:




Given a list of elements, find the majority element, which appears
more than half the time (> floor(len(lst) / 2.0)).



You can assume that such element exists.



For example, given [1, 2, 1, 1, 3, 4, 0], return 1.




My solution:



const lst = [1, 2, 1, 1, 3, 4, 0];
const findMajorityElem = lst => lst.reduce((acc, x) => acc.major[1] < acc[x]) acc.major = [x, acc[x]];
return acc;
, major: null).major[0];

console.log(findMajorityElem(lst));









share|improve this question











$endgroup$




The task:




Given a list of elements, find the majority element, which appears
more than half the time (> floor(len(lst) / 2.0)).



You can assume that such element exists.



For example, given [1, 2, 1, 1, 3, 4, 0], return 1.




My solution:



const lst = [1, 2, 1, 1, 3, 4, 0];
const findMajorityElem = lst => lst.reduce((acc, x) => acc.major[1] < acc[x]) acc.major = [x, acc[x]];
return acc;
, major: null).major[0];

console.log(findMajorityElem(lst));






javascript algorithm programming-challenge functional-programming






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 1 at 12:08







thadeuszlay

















asked Apr 1 at 12:00









thadeuszlaythadeuszlay

941616




941616







  • 5




    $begingroup$
    In the example [1, 2, 1, 1, 3, 4, 0], 1 appears 3 times, floor(len(lst) / 2.0)) is 3, and since 3 is not more than 3, therefore 1 is not the majority element, and the example list doesn't have a majority element.
    $endgroup$
    – janos
    Apr 1 at 16:47











  • $begingroup$
    @janos the example is inaccurate. However it explicitly says I can assume that there exists a majority element
    $endgroup$
    – thadeuszlay
    Apr 1 at 16:54












  • 5




    $begingroup$
    In the example [1, 2, 1, 1, 3, 4, 0], 1 appears 3 times, floor(len(lst) / 2.0)) is 3, and since 3 is not more than 3, therefore 1 is not the majority element, and the example list doesn't have a majority element.
    $endgroup$
    – janos
    Apr 1 at 16:47











  • $begingroup$
    @janos the example is inaccurate. However it explicitly says I can assume that there exists a majority element
    $endgroup$
    – thadeuszlay
    Apr 1 at 16:54







5




5




$begingroup$
In the example [1, 2, 1, 1, 3, 4, 0], 1 appears 3 times, floor(len(lst) / 2.0)) is 3, and since 3 is not more than 3, therefore 1 is not the majority element, and the example list doesn't have a majority element.
$endgroup$
– janos
Apr 1 at 16:47





$begingroup$
In the example [1, 2, 1, 1, 3, 4, 0], 1 appears 3 times, floor(len(lst) / 2.0)) is 3, and since 3 is not more than 3, therefore 1 is not the majority element, and the example list doesn't have a majority element.
$endgroup$
– janos
Apr 1 at 16:47













$begingroup$
@janos the example is inaccurate. However it explicitly says I can assume that there exists a majority element
$endgroup$
– thadeuszlay
Apr 1 at 16:54




$begingroup$
@janos the example is inaccurate. However it explicitly says I can assume that there exists a majority element
$endgroup$
– thadeuszlay
Apr 1 at 16:54










3 Answers
3






active

oldest

votes


















14












$begingroup$

If it is known that a majority element exists, then the efficient algorithm to use is the Boyer-Moore majority vote algorithm, which requires only O(1) space.






share|improve this answer









$endgroup$








  • 2




    $begingroup$
    That's a little deceptive... it's $Omega(log n)$ space in terms of bit complexity.
    $endgroup$
    – Charles
    Apr 1 at 20:44






  • 2




    $begingroup$
    @Charles Why would you want to break it down in terms of bits?
    $endgroup$
    – 200_success
    Apr 2 at 1:18






  • 1




    $begingroup$
    I think the question should be, why hide the size of the space requirements? Calling O(1) is, IMO, deceptive: it makes it sound like a fixed amount of space suffices for arbitrarily large arrays, but the larger the array the larger the numbers you need to store, and the larger the numbers the larger the space they take up. Sure, only logarithmically so, but then let's call it logarithmic space, not constant space. It's only constant space in the sense that you use a constant number of words when the words themselves grow logarithmically, but then you're being tricky and hiding the real size.
    $endgroup$
    – Charles
    Apr 2 at 1:59






  • 1




    $begingroup$
    @Charles I don't understand why there's necessarily a correlation between the size of the array and the size of the values within it. To me those are completely orthogonal concerns. It also doesn't seem particularly relevant here anyway, since Javascript's numbers are fixed-size.
    $endgroup$
    – Kyle
    Apr 2 at 2:31






  • 1




    $begingroup$
    @Charles I don’t think that’s entirely fair. Unlike algorithms and structures that meaningfully depend on bit width (radix sort, van Emde Boas trees, ...), this one only has a dependence on it in that it needs to store an array index and an array element (an offline version can also get away with storing two indices instead). That is, it needs as much space as an array access, and you generally want to count this as O(1). Yes, that means you’re counting words, not bits, but that’s the standard cost model, and it makes perfect sense outside of specialized applications.
    $endgroup$
    – Alex Shpilkin
    Apr 2 at 14:17


















3












$begingroup$

@200_success's suggestion seems like the right play here.



That said, I thought it was worth pointing out a couple small improvements to your approach:




  • major need only be the element itself (since you can look up its value in the accumulator)

  • Since you tagged this functional-programming, you can use expressions everywhere, and avoid the if statement.

Revised code:



const findMajorityElem = lst => lst.reduce((acc, x) => 0
acc.major = acc[x] <= maxCnt ? acc.major : x
return acc
, major: null).major


And just for fun, again based on your tag, here's a single-expression solution in Ramda. Again, I don't recommend actually using this given that Boyer-Moore exists:



pipe(
groupBy(identity),
map(length),
toPairs,
converge( reduce(maxBy(last)), [head, identity] ),
head,
parseInt
)(lst)


You can try it here






share|improve this answer









$endgroup$




















    1












    $begingroup$

    If the number exists, it should be done like this and shorter.



    let result =
    [2,3,4,5,1,1,1,2,2,22,2,2,2,2,2,2,2,2,1,1,33,3,2,1,1,1,1,2,2,2,2,2].reduce( (a ,b) =>
    console.log(a)
    return a.length == null ? ( a != b ? [] : a.concat(b)):
    a.length == 0 ? [b] :
    a[a.length-1] == b ? a.concat(b) :
    a.slice(0,a.length-2) ;
    )[0]

    console.log(result) //2





    share|improve this answer











    $endgroup$








    • 1




      $begingroup$
      Welcome to Code Review! and shorter is a bit short on what deserves improvement in the code in the question and why the way proposed is better.
      $endgroup$
      – greybeard
      Apr 2 at 5:42










    • $begingroup$
      Shorter means in Javascript, you may write in a neater way. It’s an implementation of voter algorithm. Just compare the last element in result with a new element, if they are different, just cancel them. Then the final survived element will be the result. Time is o(n) and if in-place space is o(1).
      $endgroup$
      – E.Coms
      Apr 2 at 11:41











    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216648%2ffind-the-majority-element-which-appears-more-than-half-the-time%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    14












    $begingroup$

    If it is known that a majority element exists, then the efficient algorithm to use is the Boyer-Moore majority vote algorithm, which requires only O(1) space.






    share|improve this answer









    $endgroup$








    • 2




      $begingroup$
      That's a little deceptive... it's $Omega(log n)$ space in terms of bit complexity.
      $endgroup$
      – Charles
      Apr 1 at 20:44






    • 2




      $begingroup$
      @Charles Why would you want to break it down in terms of bits?
      $endgroup$
      – 200_success
      Apr 2 at 1:18






    • 1




      $begingroup$
      I think the question should be, why hide the size of the space requirements? Calling O(1) is, IMO, deceptive: it makes it sound like a fixed amount of space suffices for arbitrarily large arrays, but the larger the array the larger the numbers you need to store, and the larger the numbers the larger the space they take up. Sure, only logarithmically so, but then let's call it logarithmic space, not constant space. It's only constant space in the sense that you use a constant number of words when the words themselves grow logarithmically, but then you're being tricky and hiding the real size.
      $endgroup$
      – Charles
      Apr 2 at 1:59






    • 1




      $begingroup$
      @Charles I don't understand why there's necessarily a correlation between the size of the array and the size of the values within it. To me those are completely orthogonal concerns. It also doesn't seem particularly relevant here anyway, since Javascript's numbers are fixed-size.
      $endgroup$
      – Kyle
      Apr 2 at 2:31






    • 1




      $begingroup$
      @Charles I don’t think that’s entirely fair. Unlike algorithms and structures that meaningfully depend on bit width (radix sort, van Emde Boas trees, ...), this one only has a dependence on it in that it needs to store an array index and an array element (an offline version can also get away with storing two indices instead). That is, it needs as much space as an array access, and you generally want to count this as O(1). Yes, that means you’re counting words, not bits, but that’s the standard cost model, and it makes perfect sense outside of specialized applications.
      $endgroup$
      – Alex Shpilkin
      Apr 2 at 14:17















    14












    $begingroup$

    If it is known that a majority element exists, then the efficient algorithm to use is the Boyer-Moore majority vote algorithm, which requires only O(1) space.






    share|improve this answer









    $endgroup$








    • 2




      $begingroup$
      That's a little deceptive... it's $Omega(log n)$ space in terms of bit complexity.
      $endgroup$
      – Charles
      Apr 1 at 20:44






    • 2




      $begingroup$
      @Charles Why would you want to break it down in terms of bits?
      $endgroup$
      – 200_success
      Apr 2 at 1:18






    • 1




      $begingroup$
      I think the question should be, why hide the size of the space requirements? Calling O(1) is, IMO, deceptive: it makes it sound like a fixed amount of space suffices for arbitrarily large arrays, but the larger the array the larger the numbers you need to store, and the larger the numbers the larger the space they take up. Sure, only logarithmically so, but then let's call it logarithmic space, not constant space. It's only constant space in the sense that you use a constant number of words when the words themselves grow logarithmically, but then you're being tricky and hiding the real size.
      $endgroup$
      – Charles
      Apr 2 at 1:59






    • 1




      $begingroup$
      @Charles I don't understand why there's necessarily a correlation between the size of the array and the size of the values within it. To me those are completely orthogonal concerns. It also doesn't seem particularly relevant here anyway, since Javascript's numbers are fixed-size.
      $endgroup$
      – Kyle
      Apr 2 at 2:31






    • 1




      $begingroup$
      @Charles I don’t think that’s entirely fair. Unlike algorithms and structures that meaningfully depend on bit width (radix sort, van Emde Boas trees, ...), this one only has a dependence on it in that it needs to store an array index and an array element (an offline version can also get away with storing two indices instead). That is, it needs as much space as an array access, and you generally want to count this as O(1). Yes, that means you’re counting words, not bits, but that’s the standard cost model, and it makes perfect sense outside of specialized applications.
      $endgroup$
      – Alex Shpilkin
      Apr 2 at 14:17













    14












    14








    14





    $begingroup$

    If it is known that a majority element exists, then the efficient algorithm to use is the Boyer-Moore majority vote algorithm, which requires only O(1) space.






    share|improve this answer









    $endgroup$



    If it is known that a majority element exists, then the efficient algorithm to use is the Boyer-Moore majority vote algorithm, which requires only O(1) space.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Apr 1 at 12:38









    200_success200_success

    131k17157422




    131k17157422







    • 2




      $begingroup$
      That's a little deceptive... it's $Omega(log n)$ space in terms of bit complexity.
      $endgroup$
      – Charles
      Apr 1 at 20:44






    • 2




      $begingroup$
      @Charles Why would you want to break it down in terms of bits?
      $endgroup$
      – 200_success
      Apr 2 at 1:18






    • 1




      $begingroup$
      I think the question should be, why hide the size of the space requirements? Calling O(1) is, IMO, deceptive: it makes it sound like a fixed amount of space suffices for arbitrarily large arrays, but the larger the array the larger the numbers you need to store, and the larger the numbers the larger the space they take up. Sure, only logarithmically so, but then let's call it logarithmic space, not constant space. It's only constant space in the sense that you use a constant number of words when the words themselves grow logarithmically, but then you're being tricky and hiding the real size.
      $endgroup$
      – Charles
      Apr 2 at 1:59






    • 1




      $begingroup$
      @Charles I don't understand why there's necessarily a correlation between the size of the array and the size of the values within it. To me those are completely orthogonal concerns. It also doesn't seem particularly relevant here anyway, since Javascript's numbers are fixed-size.
      $endgroup$
      – Kyle
      Apr 2 at 2:31






    • 1




      $begingroup$
      @Charles I don’t think that’s entirely fair. Unlike algorithms and structures that meaningfully depend on bit width (radix sort, van Emde Boas trees, ...), this one only has a dependence on it in that it needs to store an array index and an array element (an offline version can also get away with storing two indices instead). That is, it needs as much space as an array access, and you generally want to count this as O(1). Yes, that means you’re counting words, not bits, but that’s the standard cost model, and it makes perfect sense outside of specialized applications.
      $endgroup$
      – Alex Shpilkin
      Apr 2 at 14:17












    • 2




      $begingroup$
      That's a little deceptive... it's $Omega(log n)$ space in terms of bit complexity.
      $endgroup$
      – Charles
      Apr 1 at 20:44






    • 2




      $begingroup$
      @Charles Why would you want to break it down in terms of bits?
      $endgroup$
      – 200_success
      Apr 2 at 1:18






    • 1




      $begingroup$
      I think the question should be, why hide the size of the space requirements? Calling O(1) is, IMO, deceptive: it makes it sound like a fixed amount of space suffices for arbitrarily large arrays, but the larger the array the larger the numbers you need to store, and the larger the numbers the larger the space they take up. Sure, only logarithmically so, but then let's call it logarithmic space, not constant space. It's only constant space in the sense that you use a constant number of words when the words themselves grow logarithmically, but then you're being tricky and hiding the real size.
      $endgroup$
      – Charles
      Apr 2 at 1:59






    • 1




      $begingroup$
      @Charles I don't understand why there's necessarily a correlation between the size of the array and the size of the values within it. To me those are completely orthogonal concerns. It also doesn't seem particularly relevant here anyway, since Javascript's numbers are fixed-size.
      $endgroup$
      – Kyle
      Apr 2 at 2:31






    • 1




      $begingroup$
      @Charles I don’t think that’s entirely fair. Unlike algorithms and structures that meaningfully depend on bit width (radix sort, van Emde Boas trees, ...), this one only has a dependence on it in that it needs to store an array index and an array element (an offline version can also get away with storing two indices instead). That is, it needs as much space as an array access, and you generally want to count this as O(1). Yes, that means you’re counting words, not bits, but that’s the standard cost model, and it makes perfect sense outside of specialized applications.
      $endgroup$
      – Alex Shpilkin
      Apr 2 at 14:17







    2




    2




    $begingroup$
    That's a little deceptive... it's $Omega(log n)$ space in terms of bit complexity.
    $endgroup$
    – Charles
    Apr 1 at 20:44




    $begingroup$
    That's a little deceptive... it's $Omega(log n)$ space in terms of bit complexity.
    $endgroup$
    – Charles
    Apr 1 at 20:44




    2




    2




    $begingroup$
    @Charles Why would you want to break it down in terms of bits?
    $endgroup$
    – 200_success
    Apr 2 at 1:18




    $begingroup$
    @Charles Why would you want to break it down in terms of bits?
    $endgroup$
    – 200_success
    Apr 2 at 1:18




    1




    1




    $begingroup$
    I think the question should be, why hide the size of the space requirements? Calling O(1) is, IMO, deceptive: it makes it sound like a fixed amount of space suffices for arbitrarily large arrays, but the larger the array the larger the numbers you need to store, and the larger the numbers the larger the space they take up. Sure, only logarithmically so, but then let's call it logarithmic space, not constant space. It's only constant space in the sense that you use a constant number of words when the words themselves grow logarithmically, but then you're being tricky and hiding the real size.
    $endgroup$
    – Charles
    Apr 2 at 1:59




    $begingroup$
    I think the question should be, why hide the size of the space requirements? Calling O(1) is, IMO, deceptive: it makes it sound like a fixed amount of space suffices for arbitrarily large arrays, but the larger the array the larger the numbers you need to store, and the larger the numbers the larger the space they take up. Sure, only logarithmically so, but then let's call it logarithmic space, not constant space. It's only constant space in the sense that you use a constant number of words when the words themselves grow logarithmically, but then you're being tricky and hiding the real size.
    $endgroup$
    – Charles
    Apr 2 at 1:59




    1




    1




    $begingroup$
    @Charles I don't understand why there's necessarily a correlation between the size of the array and the size of the values within it. To me those are completely orthogonal concerns. It also doesn't seem particularly relevant here anyway, since Javascript's numbers are fixed-size.
    $endgroup$
    – Kyle
    Apr 2 at 2:31




    $begingroup$
    @Charles I don't understand why there's necessarily a correlation between the size of the array and the size of the values within it. To me those are completely orthogonal concerns. It also doesn't seem particularly relevant here anyway, since Javascript's numbers are fixed-size.
    $endgroup$
    – Kyle
    Apr 2 at 2:31




    1




    1




    $begingroup$
    @Charles I don’t think that’s entirely fair. Unlike algorithms and structures that meaningfully depend on bit width (radix sort, van Emde Boas trees, ...), this one only has a dependence on it in that it needs to store an array index and an array element (an offline version can also get away with storing two indices instead). That is, it needs as much space as an array access, and you generally want to count this as O(1). Yes, that means you’re counting words, not bits, but that’s the standard cost model, and it makes perfect sense outside of specialized applications.
    $endgroup$
    – Alex Shpilkin
    Apr 2 at 14:17




    $begingroup$
    @Charles I don’t think that’s entirely fair. Unlike algorithms and structures that meaningfully depend on bit width (radix sort, van Emde Boas trees, ...), this one only has a dependence on it in that it needs to store an array index and an array element (an offline version can also get away with storing two indices instead). That is, it needs as much space as an array access, and you generally want to count this as O(1). Yes, that means you’re counting words, not bits, but that’s the standard cost model, and it makes perfect sense outside of specialized applications.
    $endgroup$
    – Alex Shpilkin
    Apr 2 at 14:17













    3












    $begingroup$

    @200_success's suggestion seems like the right play here.



    That said, I thought it was worth pointing out a couple small improvements to your approach:




    • major need only be the element itself (since you can look up its value in the accumulator)

    • Since you tagged this functional-programming, you can use expressions everywhere, and avoid the if statement.

    Revised code:



    const findMajorityElem = lst => lst.reduce((acc, x) => 0
    acc.major = acc[x] <= maxCnt ? acc.major : x
    return acc
    , major: null).major


    And just for fun, again based on your tag, here's a single-expression solution in Ramda. Again, I don't recommend actually using this given that Boyer-Moore exists:



    pipe(
    groupBy(identity),
    map(length),
    toPairs,
    converge( reduce(maxBy(last)), [head, identity] ),
    head,
    parseInt
    )(lst)


    You can try it here






    share|improve this answer









    $endgroup$

















      3












      $begingroup$

      @200_success's suggestion seems like the right play here.



      That said, I thought it was worth pointing out a couple small improvements to your approach:




      • major need only be the element itself (since you can look up its value in the accumulator)

      • Since you tagged this functional-programming, you can use expressions everywhere, and avoid the if statement.

      Revised code:



      const findMajorityElem = lst => lst.reduce((acc, x) => 0
      acc.major = acc[x] <= maxCnt ? acc.major : x
      return acc
      , major: null).major


      And just for fun, again based on your tag, here's a single-expression solution in Ramda. Again, I don't recommend actually using this given that Boyer-Moore exists:



      pipe(
      groupBy(identity),
      map(length),
      toPairs,
      converge( reduce(maxBy(last)), [head, identity] ),
      head,
      parseInt
      )(lst)


      You can try it here






      share|improve this answer









      $endgroup$















        3












        3








        3





        $begingroup$

        @200_success's suggestion seems like the right play here.



        That said, I thought it was worth pointing out a couple small improvements to your approach:




        • major need only be the element itself (since you can look up its value in the accumulator)

        • Since you tagged this functional-programming, you can use expressions everywhere, and avoid the if statement.

        Revised code:



        const findMajorityElem = lst => lst.reduce((acc, x) => 0
        acc.major = acc[x] <= maxCnt ? acc.major : x
        return acc
        , major: null).major


        And just for fun, again based on your tag, here's a single-expression solution in Ramda. Again, I don't recommend actually using this given that Boyer-Moore exists:



        pipe(
        groupBy(identity),
        map(length),
        toPairs,
        converge( reduce(maxBy(last)), [head, identity] ),
        head,
        parseInt
        )(lst)


        You can try it here






        share|improve this answer









        $endgroup$



        @200_success's suggestion seems like the right play here.



        That said, I thought it was worth pointing out a couple small improvements to your approach:




        • major need only be the element itself (since you can look up its value in the accumulator)

        • Since you tagged this functional-programming, you can use expressions everywhere, and avoid the if statement.

        Revised code:



        const findMajorityElem = lst => lst.reduce((acc, x) => 0
        acc.major = acc[x] <= maxCnt ? acc.major : x
        return acc
        , major: null).major


        And just for fun, again based on your tag, here's a single-expression solution in Ramda. Again, I don't recommend actually using this given that Boyer-Moore exists:



        pipe(
        groupBy(identity),
        map(length),
        toPairs,
        converge( reduce(maxBy(last)), [head, identity] ),
        head,
        parseInt
        )(lst)


        You can try it here







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Apr 1 at 13:03









        JonahJonah

        3,521718




        3,521718





















            1












            $begingroup$

            If the number exists, it should be done like this and shorter.



            let result =
            [2,3,4,5,1,1,1,2,2,22,2,2,2,2,2,2,2,2,1,1,33,3,2,1,1,1,1,2,2,2,2,2].reduce( (a ,b) =>
            console.log(a)
            return a.length == null ? ( a != b ? [] : a.concat(b)):
            a.length == 0 ? [b] :
            a[a.length-1] == b ? a.concat(b) :
            a.slice(0,a.length-2) ;
            )[0]

            console.log(result) //2





            share|improve this answer











            $endgroup$








            • 1




              $begingroup$
              Welcome to Code Review! and shorter is a bit short on what deserves improvement in the code in the question and why the way proposed is better.
              $endgroup$
              – greybeard
              Apr 2 at 5:42










            • $begingroup$
              Shorter means in Javascript, you may write in a neater way. It’s an implementation of voter algorithm. Just compare the last element in result with a new element, if they are different, just cancel them. Then the final survived element will be the result. Time is o(n) and if in-place space is o(1).
              $endgroup$
              – E.Coms
              Apr 2 at 11:41















            1












            $begingroup$

            If the number exists, it should be done like this and shorter.



            let result =
            [2,3,4,5,1,1,1,2,2,22,2,2,2,2,2,2,2,2,1,1,33,3,2,1,1,1,1,2,2,2,2,2].reduce( (a ,b) =>
            console.log(a)
            return a.length == null ? ( a != b ? [] : a.concat(b)):
            a.length == 0 ? [b] :
            a[a.length-1] == b ? a.concat(b) :
            a.slice(0,a.length-2) ;
            )[0]

            console.log(result) //2





            share|improve this answer











            $endgroup$








            • 1




              $begingroup$
              Welcome to Code Review! and shorter is a bit short on what deserves improvement in the code in the question and why the way proposed is better.
              $endgroup$
              – greybeard
              Apr 2 at 5:42










            • $begingroup$
              Shorter means in Javascript, you may write in a neater way. It’s an implementation of voter algorithm. Just compare the last element in result with a new element, if they are different, just cancel them. Then the final survived element will be the result. Time is o(n) and if in-place space is o(1).
              $endgroup$
              – E.Coms
              Apr 2 at 11:41













            1












            1








            1





            $begingroup$

            If the number exists, it should be done like this and shorter.



            let result =
            [2,3,4,5,1,1,1,2,2,22,2,2,2,2,2,2,2,2,1,1,33,3,2,1,1,1,1,2,2,2,2,2].reduce( (a ,b) =>
            console.log(a)
            return a.length == null ? ( a != b ? [] : a.concat(b)):
            a.length == 0 ? [b] :
            a[a.length-1] == b ? a.concat(b) :
            a.slice(0,a.length-2) ;
            )[0]

            console.log(result) //2





            share|improve this answer











            $endgroup$



            If the number exists, it should be done like this and shorter.



            let result =
            [2,3,4,5,1,1,1,2,2,22,2,2,2,2,2,2,2,2,1,1,33,3,2,1,1,1,1,2,2,2,2,2].reduce( (a ,b) =>
            console.log(a)
            return a.length == null ? ( a != b ? [] : a.concat(b)):
            a.length == 0 ? [b] :
            a[a.length-1] == b ? a.concat(b) :
            a.slice(0,a.length-2) ;
            )[0]

            console.log(result) //2






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 2 at 0:37

























            answered Apr 2 at 0:27









            E.ComsE.Coms

            1113




            1113







            • 1




              $begingroup$
              Welcome to Code Review! and shorter is a bit short on what deserves improvement in the code in the question and why the way proposed is better.
              $endgroup$
              – greybeard
              Apr 2 at 5:42










            • $begingroup$
              Shorter means in Javascript, you may write in a neater way. It’s an implementation of voter algorithm. Just compare the last element in result with a new element, if they are different, just cancel them. Then the final survived element will be the result. Time is o(n) and if in-place space is o(1).
              $endgroup$
              – E.Coms
              Apr 2 at 11:41












            • 1




              $begingroup$
              Welcome to Code Review! and shorter is a bit short on what deserves improvement in the code in the question and why the way proposed is better.
              $endgroup$
              – greybeard
              Apr 2 at 5:42










            • $begingroup$
              Shorter means in Javascript, you may write in a neater way. It’s an implementation of voter algorithm. Just compare the last element in result with a new element, if they are different, just cancel them. Then the final survived element will be the result. Time is o(n) and if in-place space is o(1).
              $endgroup$
              – E.Coms
              Apr 2 at 11:41







            1




            1




            $begingroup$
            Welcome to Code Review! and shorter is a bit short on what deserves improvement in the code in the question and why the way proposed is better.
            $endgroup$
            – greybeard
            Apr 2 at 5:42




            $begingroup$
            Welcome to Code Review! and shorter is a bit short on what deserves improvement in the code in the question and why the way proposed is better.
            $endgroup$
            – greybeard
            Apr 2 at 5:42












            $begingroup$
            Shorter means in Javascript, you may write in a neater way. It’s an implementation of voter algorithm. Just compare the last element in result with a new element, if they are different, just cancel them. Then the final survived element will be the result. Time is o(n) and if in-place space is o(1).
            $endgroup$
            – E.Coms
            Apr 2 at 11:41




            $begingroup$
            Shorter means in Javascript, you may write in a neater way. It’s an implementation of voter algorithm. Just compare the last element in result with a new element, if they are different, just cancel them. Then the final survived element will be the result. Time is o(n) and if in-place space is o(1).
            $endgroup$
            – E.Coms
            Apr 2 at 11:41

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216648%2ffind-the-majority-element-which-appears-more-than-half-the-time%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Is flight data recorder erased after every flight?When are black boxes used?What protects the location beacon (pinger) of a flight data recorder?Is there anywhere I can pick up raw flight data recorder information?Who legally owns the Flight Data Recorder?Constructing flight recorder dataWhy are FDRs and CVRs still two separate physical devices?What are the data elements shown on the GE235 flight data recorder (FDR) plot?Are CVR and FDR reset after every flight?What is the format of data stored by a Flight Data Recorder?How much data is stored in the flight data recorder per hour in a typical flight of an A380?Is a smart flight data recorder possible?

            Is there a general name for the setup in which payoffs are not known exactly but players try to influence each other's perception of the payoffs?Osborne, Nash equilibria and the correctness of beliefsIs there a name for this family of games (Binomial games?)?Perfect Bayesian EquilibriumCalculating mixed strategy equilibrium in battle of sexesPure Strategy SPNEIs there a commitment mechanism which allows players to achieve pareto optimal solutions?Extensive Form GamesAn $n$-player prisoner's dilemma where a coalition of 2 players is better off defectingTit-For-Stat Strategy Best RepliesPotential solutions of the $n$-player Prisoner's Dilemma

            Which is better: GPT or RelGAN for text generation?2019 Community Moderator ElectionWhat is the difference between TextGAN and LM for text generation?GANs (generative adversarial networks) possible for text as well?Generator loss not decreasing- text to image synthesisChoosing a right algorithm for template-based text generationHow should I format input and output for text generation with LSTMsGumbel Softmax vs Vanilla Softmax for GAN trainingWhich neural network to choose for classification from text/speech?NLP text autoencoder that generates text in poetic meterWhat is the interpretation of the expectation notation in the GAN formulation?What is the difference between TextGAN and LM for text generation?How to prepare the data for text generation task