30 Day Risk-Free Guarantee:
100% money back if you're unsatisfied.
Book (308 Pages):
  • 150 Programming Interview Questions and Solutions
  • Five Proven Approaches to Solving Tough Algorithm Questions
  • Ten Mistakes Candidates Make -- And How to Avoid Them
  • Steps to Prepare for Behavioral and Technical Questions
  • Interview War Stories: A View from the Interviewer's Side
  • Book Preview and More Info

Video (One Hour):
  • Watch CareerCup's founder perform a totally unscripted technical interview of a candidate.
  • Overview of what interviewers look for in software engineering jobs.
  • Technical questions with white-boarding coding where the candidate does well - and struggles.
  • Interviewer reviews with what went well and poorly.
  • Video Preview and More Info

Resume Review (24 - 48hr)
  • Get your resume reviewed by a trained engineering interviewer. More Info
All Products / Services


Express Prep Package (Book)
$29.99 for e-book | $32.45 for paperback
Buy E-Book Buy on Amazon


Standard Prep Package (E-Book & Video)
Emailed Instantly | $39.99
Buy Standard

Elite Prep Package (E-Book, Video & Resume)
Emailed Instantly | $99.99
Buy Elite
 



In an array there is one element which repeats more than n/2 times...find the number in 0(n) time and 0(1) space

33


Anonymous on May 31, 2010 |Edit | Edit

find the median element using the quick select algo.

cirus on June 01, 2010 |Edit | Edit

Qsort takes O(NlogN). Can you explain your logic.

Anonymous on June 01, 2010 |Edit | Edit

(Different anonymous) quickSELECT. It's O(n) time but Omega(n) space.

hemant on June 01, 2010 |Edit | Edit

Array space already given as input is used in 2quick select so we can say that no extra space is used so space complexity is constant.

Anonymous on June 01, 2010 |Edit | Edit

Well, OK, but there's a solution that doesn't modify the input.

Prateek on June 01, 2010 |Edit | Edit

taylor.thursday.com/classes/cs307/2/Majority%20Element.pdf

gevorgk on June 01, 2010 |Edit | Edit


//returns -1 if not found
int maxRepeatedElement(int arr[], int size)
{
if( size <= 0)
return -1;

int count = 0;
int elem;

for (int i = 0; i < size; ++i)
{
if (count == 0)
{
elem = arr[i];
count = 1;
}
else if (elem == arr[i])
{
++count;
}
else
{
--count;
}
}

count = 0;
for(int i = 0; i < size; ++i)
{
if (arr[i] == elem)
{
++count;
}
}

if (count > size/2)
{
return elem;
}

return -1;
}

gurha.pallav on June 01, 2010 |Edit | Edit

Hi,

This is pretty good. But was wondering is it possible to solve it in the space complexity of O(1) as now its O(2).

-Pallav

gevorgk on June 01, 2010 |Edit | Edit

You make me cry :))))
O(1) means space which doesn't depend on input size.
And I don't know what is O(2) :))))

netappreject on June 01, 2010 |Edit | Edit

abe gadhe gevorgk tera logic nai samajh aaya...

gevorgk on June 01, 2010 |Edit | Edit

Nice language. What about english ?

Anonymous on June 01, 2010 |Edit | Edit

@gevorgk
awesome work man!!!!
don't worry what netappreject has said. when such people don't have any point to make this is what they do...

@netappreject
There is better way to say this....Please be nice to people who are sharing their knowledge and helping you...

Anonymous on June 01, 2010 |Edit | Edit

O(2) is a nonstandard way to say O(1). Pallav, if using two ints bothers you, just pack them both into a long.

Anonymous on June 01, 2010 |Edit | Edit

@gevorgk - Can you also pls explain, your thinking process - how you approach the problem and devise the solution - I assume here you approached it as the number which occurred more than n/2 has to either alternate starting from 1st position (e.g. 1 2 1 4 1 5 1) or has to occur consecutively atleast 1 (e.g. 5 4 1 1 6 1 1)

Anonymous on June 01, 2010 |Edit | Edit

If the element is repeated more than n/2 times, than it definitely occurs consecutively atleast once...

Anonymous on June 01, 2010 |Edit | Edit

I doubt he came up with the algorithm because the code looks very similar to the algorithm in taylor.thursday.com pdf. But if he came up with it great!

Nitin on June 03, 2010 |Edit | Edit

This solution has a flaw.
If numbers are in this form
1, 20, 2, 20, 3, 20, 4, 20 ...
Then this solution doesn't work.
Because it never get a chance to store 20 in elem.

Nitin on June 03, 2010 |Edit | Edit

if the code is modified a little bit like mentioned below.
......
else
{
--count;
--i;
}
........
Then things work fine.
Ya But then I don't know what will be the complexity.
In worst case It probably comes out to be O(n+n/2), i.e. O(3n/2), i.e. O(n).
Please comment on it.
Please point out if you see any problem in it or type "CORRECT" if it is correct.

- Nitin

netappreject on June 05, 2010 |Edit | Edit

Point here is definition of majority is (n/2) + 1. thats way:

1 20 2 20 3 20 4 20 needs to keep another 20, for n/2 it fails several cases.

nitin on June 09, 2010 |Edit | Edit

yes, right.
The solution is correct if 20's are more than n/2.
:-)

Prateek on June 01, 2010 |Edit | Edit

Thanks gevorgk.

code bug on June 01, 2010 |Edit | Edit

Hi gevorgk , as you are setting again count=0 . It making count logic of first for loop useless. I am not getting why that is required. also according to my analysis your logic will be definitely failed for array {3,1,1}

Anonymous on June 01, 2010 |Edit | Edit

The first loop finds the required element if it exists and an arbitrary element otherwise. The second loop checks whether this element occurs more n/2 times, which is sort of pointless given that the input is guaranteed to have that property.

Anonymous on June 01, 2010 |Edit | Edit

It's not useless, count logic in first loop guarantees that element with more than n/2 occurrence will survive.
And I don't see any problem with {3, 1, 1}.

3 - elem = 3, count = 1
1 - elem = 3, count = 0
1 - elem = 1, count = 1

So we have elem = 1 after first loop and check if it occures more than n/2 in second loop.

nvguest on June 03, 2010 |Edit | Edit

nice solution

nvguest on June 03, 2010 |Edit | Edit

nice solution gevorgk

Anonymous on June 02, 2010 |Edit
/* The class name doesn't have to be Main, as long as the class is not public. */
class Main
{
  public static void main (String[] args) throws java.lang.Exception
  {
     java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
     String s;
     while (!(s=r.readLine()).startsWith("42")) System.out.println(s);
  }
}

1
2
10
42
11

Anonymous on June 09, 2010 |Edit | Edit

The algorithm, though very clever, does not work in all cases. For example:
1112222111

Anonymous on June 10, 2010 |Edit | Edit

very gud solution , great work !!

deepak on June 11, 2010 |Edit | Edit

#include<stdio.h>
#define arraysize 6
int array[arraysize]={1,3,3,3,4,3};

int repeatedElem(int array[], int size)
{

int index = 0;
int count = 0;
int val;
int elem;
count = 0;
for(index=0;index<size;++index)
{
elem = array[index];
if(count ==0)
{
val = elem;count++;

}
else if(val == elem)
{
count++;
}
else
{ count--;}
}
if(count>0)
{
return val;
}
else{return -1;}

}

int main()
{
int ans = repeatedElem(array, arraysize);
printf("answer is %d ", ans);
return 0;
}

chenming831 on June 17, 2010 |Edit | Edit

gevorgk: gorgous solution!

bond on July 23, 2010 |Edit | Edit

traverse the array from i=0 to n-3
if a[i]==a[i+1] or a[i]==a[i+2]
then num=a[i]

it's simple

anjum on August 27, 2010 |Edit | Edit

I found Bond's solution the best.It works and i'm not that good with calculating complexity but I m sure there is only one for loop so complexity must be less.

Add a Text Comment | Add Runnable Code
Name:
Comment:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.








Amazon (1033)Bloomberg LP (403)Qualcomm (117)Adobe (88)Goldman Sachs (78)NetApp (49)IBM (43)Morgan Stanley (33)CapitalIQ (30)Sophos (25)Achieve Internet (23)Electronic Arts (19)Motorola (18)Research In Motion (17)Flipkart (16)
Microsoft (867)Google (141)NVIDIA (98)Yahoo (82)Epic Systems (69)Expedia (47)VMWare Inc (43)Apple (32)Cisco Systems (28)Facebook (23)Infosys (22)Agilent Technologies (19)Sage Software (17)Deshaw Inc (16)FlexTrade (15)
More Companies »
Software Engineer / Dev... (1062)Financial Software Deve... (170)Testing / Quality Assur... (56)Analyst (35)Virus Researcher (25)Field Sales (15)Developer Program Engin... (9)Front-end Software Engi... (6)MyJoB (5)area sales manager (4)Assistant (3)Cabin crew (2)Accountant (1)personnel (1)Intern (1)
Software Engineer in Te... (288)Program Manager (65)Development Support Eng... (47)INTERN(MSIDC) (28)Web Developer (18)System Administrator (10)Consultant (10)Production Engineer (5)Associate Technology L2 (5)AcquireKnowledge (4)Product Security Engine... (3)Solutions Architect (2)Gamer (1)mts (1)Fresh graduate interview (0)
More Job Titles »
Algorithm (1073)Terminology & Trivia (294)C (166)Object Oriented Design (159)Java (121)Testing (114)Arrays (101)Operating System (78)Database (70)Linked List (62)String Manipulation (56)Networking / Web / Inte... (44)Threads (36)Linux Kernel (33)PHP (22)
Coding (511)C++ (204)Behavioral (159)Data Structures (155)Experience (116)Brain Teasers (111)Computer Architecture &... (79)General Questions and C... (73)Trees and Graphs (69)Math & Computation (57)Application / UI Design (45)Ideas (38)System Design (35)Puzzles (30)Bit Manipulation (20)
More Topics »
CareerCup Official Interview Book Daily Questions Requests for Help Mock Interviews Video for Cracking the Coding Interview Job Placement Service CareerCup Blog
My Profile Edit Profile & Email Settings Sign Out