CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jun 2003
    Location
    Armenia, Yerevan
    Posts
    720

    The most frequent element in a list (the mode)

    I'd be thankful if someone enlighten me how to solve this problem in most efficient manner both in terms of speed and memory consumption.
    Example: [4,5,6,7,12,6,8,9,4,6,8,4,97,4] the answer is 4, the only solution that occured to me is to hold counters in a hash table and pick the maximum element. However, there could some circumstances where this could be inefficient, so I wonder if some straightforward method is available.

    Thanks beforehand and regards.
    Last edited by AvDav; June 16th, 2010 at 04:42 PM.

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: The most frequent element in a list (the mode)

    The cases when your proposed solution becomes inefficient is when the hash table performance degrades to O(n^2). So, you can design the hash function(s) to avoid this, or you could use a balanced binary tree instead of a hash table, thus accepting slightly slower average case performance as a trade off for better worse case performance.

    Alternatively, you could sort the list, and then go through the elements in a single pass to count them. This will result in performance similiar to the use of a balanced binary tree.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Jun 2003
    Location
    Armenia, Yerevan
    Posts
    720

    Re: The most frequent element in a list (the mode)

    Quote Originally Posted by laserlight View Post
    Alternatively, you could sort the list, and then go through the elements in a single pass to count them. This will result in performance similiar to the use of a balanced binary tree.
    Thanks, I nearly got the idea, however am not sure how to identify the most lengthy subsequence in a sorted list in order to outline the element, could you please explain in detail?

  4. #4
    Join Date
    May 2009
    Posts
    2,413

    Re: The most frequent element in a list (the mode)

    Quote Originally Posted by AvDav View Post
    Thanks, I nearly got the idea, however am not sure how to identify the most lengthy subsequence in a sorted list in order to outline the element, could you please explain in detail?
    In a sorted list equal elements are grouped next to each other. You search the list once sequencially looking for the largest group of equal elements.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured