Interview Question

Senior Software Engineer Interview

-Dublin, Dublin

Tripadvisor

Give a range of numbers, return 6 different numbers randomly. In O(n).

AnswerAdd Tags

Interview Answers

3 Answers

4

Suppose the range from 0 to 100 1- Create and initialize an array of 101 elements, filled from 0 --> 100 2- Set the max to be the last element in the array i.e max = 100 3- Get a random number between 0 and max. r= rand(0,max) 4- Replace array[r] with array[max] and decrease max by 1(max = max -1) 5- Repeat from step 3

Ahmad Bakr on

0

As this question is usually posed, there is an additional constraint: the numbers are presented in a stream, and you do not have enough memory to store them all.

a hiring manager on

0

public static void main(String[] args) { int max = 100; Integer[] nums = new Integer[max]; for (int i = 0; i < nums.length; i++) { nums[i] = i; } Collections.shuffle(Arrays.asList(nums)); for (int i = 0; i < 6; i++) { System.out.println(nums[i]); } }

Anonymous on

Add Answers or Comments

To comment on this, Sign In or Sign Up.