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
 



Write a Java program to check whether any two elements in an array add to a constant C or not. Implement the program with least complexity O(n).

19


Sanjeev on May 20, 2008 |Edit | Edit

what does it mean by "add to a constant C"? What I got is take sum of any two elements of array and that sum will be always constant. If it is so, then all the array elements must be equal. You can easily check the equality of all array elements by taking the 1st element and comparing it with the rest n-1 elements in O(n) time.

prudhvi on May 26, 2008 |Edit | Edit

Sanjeev,

I think you got the question wrong...what if I have 1,2,3,4,5,6,7 in the array..and my constant is "7", then I have two possibilities 1+6 and 4+3

Anonymous on November 08, 2008 |Edit | Edit

Sort the array first and then :

int[] a = {2,5,12,15,17};
i=0;j=a.length-1;
while(i<j){
if( a[i] + a[j] > C )
j--;
else if ( a[i] + a[j] < C )
i++;
else print a[i],a[j];
}
}

SiD on January 24, 2009 |Edit | Edit

The sorting would take O(nlog n) time, so this solution is incorrect.

the man above is a fool on January 24, 2009 |Edit | Edit

for every number in the array,Suppose the number is x,put the C-x as the index in the Hash table,so when carray on ,check whether the number you are dealing in the hash table if it is there then the function should return true.

SiD on January 24, 2009 |Edit | Edit

This solution is incorrect too, the running time is O(n square) which is inefficient as per the problem asked.

pwang234 on March 14, 2009 |Edit | Edit

How about first subtracting every elements of the array by C/2. Then insert the new array into a hash table using the abs value of each elements. If two numbers are hashed to the same place and they have opposite signs, we found the result.

T on March 14, 2009 |Edit | Edit

Why do any subtracting at all?

When you are about to hash a[i], just check if C - a[i] is already there, if not, add a[i] the hash.

Your solution will be go through the whole array no matter what.

This one will immediately return on the first hit, which could be nice thing to have.

Anonymous on December 02, 2009 |Edit | Edit
PKS on May 20, 2009 |Edit | Edit

Let the given array be "elements". Let the length of the array be 'N'. Create another array "check" having C+1 elements initialized to 0.

// Initialize "check" in O(N).
// Also subtract individual "elements" in O(N).

for(i=0; i<N;, i++)
{
if (elements[i]<=C)
{
check[elements[i]] = 1;
elements[i] = C - elements[i];
}
}

//Check for the presence C-"elements" using "check" and the modified "elements"
// Again being done in O(N)

for(i=0; i<N;, i++)
{
if (elements[i]<=C)
if (check[elements[i]] == 1)
// The pair is (elements[i],C-elements[i])
}

All the numbers in "elements" are assumed to be greater than or equal to 0 and C is assumed to be +ve. Note that the above algorithm can be used only if we want 2 positive numbers adding up to C. Even addition of (C+1, -1) can give a result C. However, detection of such pairs using the above methodology would require an unbounded array "check" and so the above method cannot be used.

mg on August 03, 2009 |Edit | Edit


void addsToC(int a[], int c) {
map<int, int> map;
for (int i = 0; i < N; ++i) {
if (map[c - a[i]]) return true;
map[a[i]] = c - a[i];
}
return false;
}

mg on August 03, 2009 |Edit | Edit

Edit: bool addsToC(.... not void, obviously!

sw on January 29, 2010 |Edit | Edit

how can you use Map like Array.

sw on January 29, 2010 |Edit | Edit

how can you use Map like Array.

sw on January 29, 2010 |Edit | Edit

how can you use Map like Array.

sw on January 29, 2010 |Edit | Edit

how can you use Map like Array.

sw on January 29, 2010 |Edit | Edit

how can you use Map like Array.

Anonymous on January 29, 2010 |Edit | Edit

Can you please repeat the question?

Anonymous on March 02, 2010 |Edit | Edit
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