Microsoft Interview Question for SDE1s


Country: India




Comment hidden because of low score. Click to expand.
4
of 4 vote

enter each element in hash table and store starting and ending index. first time inserting an element in hash table starting and ending index is same, after that for duplicate elements update the ending index...

for each element the max distance will be (end index - start index + 1)

- algos April 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

something like this perhaps ..

...
class NumInfo {
        public int dist;
        public int firstInstance;
        
        public NumInfo(int i) {
            firstInstance = i;
            dist = 0;
        }
    }
    
    void findMaxDistances(int[] arr) {
        HashMap<Integer, NumInfo> map;
        map = new HashMap();
        
        for(int i=0;i<arr.length;i++) {
            if(map.containsKey(arr[i])) {
                NumInfo n = map.get(arr[i]);
                n.dist = i - n.firstInstance;
            }else {
                map.put(arr[i], new NumInfo(i));
            }
        }
        
        for(Entry<Integer, NumInfo> n : map.entrySet()){
            System.out.println("Value: " + n.getKey() + " MaxDist: " + n.getValue().dist);
        }
    }

- VJ April 16, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Time: O(N)
Space: O(N)

public static Map<Integer, Integer> calcularteMaxDistance( int[] arr ){
		
		Map<Integer, Integer> distance = new HashMap<>();		
		Map<Integer, Integer> firstOccurrence = new HashMap<>();
				
		for( int i = 0; i < arr.length; i++ ){
			
			if( firstOccurrence.containsKey( arr[i]) ){
				int firstIndex = firstOccurrence.get( arr[i] );
				distance.put( arr[i], i - firstIndex);
			}
			else {
				// first time occurrence
				firstOccurrence.put( arr[i], i );
				distance.put( arr[i], 0);
			}
		}
		
		
		return distance;
	}

- m@}{ April 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

Use a Self-Balanced Binary Search Tree. Let each node have 2 fields - start_index and end_index.

Insert elements into the BST along with the below operations.
If the element is not found in BST, create a node in BST using a[i]. Let start_index=end_index=i
If element is already found, then end_index=i

After inserting all the elements, traverse the BST to find the node with maximum distance.

Time Complexity Analysis
------------------------
Insert Operation= O(logN)
Inserting N elements = O(NlogN)
Other operations = O(1)

Time Complexity - O(NlogN)
Space Complexity - O(N)

- Sudhindra.A April 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Rotation to maintain the balance, creation of nodes etc.,

- Sudhindra.A April 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

One more solution:
Find the last occurrence of element by traversing from end.

Code:

public void maxDistance(int a[]) {
		TreeSet<Integer> t = new TreeSet<Integer>();
		for (int i = 0; i < a.length; i++) {
			if (!t.contains(a[i])) {
				int j = a.length - 1;
				while (j >= i) {
					if (a[i] == a[j]) {
						t.add(a[i]);
						System.out.println("Max(" + a[i] + ")= " + (j - i));
						break;
					}
					j--;
				}
			}
		}
	}

- Dhass April 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

a = [1,2,3,4,1,1,7,4]
max_dist = {}

for i,e in enumerate(a):
    if e in max_dist:
        max_dist[e][-1] = i
    else:
        max_dist[e] = [i,i]
for k,v in max_dist.items():
    print '{0}:{1}'.format(k,v[-1]-v[0])

- antony thomas April 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

c++ code:

#include <cstdio>
#include <map>
#include <vector>
#include <cstring>

using namespace std;

int main()
{
    int i = 0;
    int t = 0;
    int n = 0;
    map<int, vector<int> > position;
    scanf("%d", &n);
    for(i = 0; i < n; i++)
    {
        scanf("%d", &t);
        position[t].push_back(i);
    }
    for(map<int, vector<int> >::iterator it = position.begin(); it != position.end(); it++)
    {
        t = 0;
        if(it->second.size() > 0)
        {
            t = it->second[it->second.size() - 1] - it->second[0];
        }
        printf("max(%d)=%d\n", it->first, t);
    }
    return 0;
}

- Gabriel April 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static HashMap<Integer, Integer> findAllMaxDistance(int[] arr){
	HashMap<Integer, Integer> hashFirst = new HashMap<Integer, Integer>();
	HashMap<Integer, Integer> hashLast = new HashMap<Integer, Integer>();
	HashMap<Integer, Integer> result = new HashMap<Integer, Integer>();
	
	/* Record the first index for all the characters */
	for(int i = 0; i < arr.length; i++){
		if(!hashFirst.containsKey(arr[i])){
			hashFirst.put(arr[i], i);
		}
	}
	/* Record the last index for all the characters */
	for(int i = arr.length - 1; i >= 0; i--){
		if(!hashLast.containsKey(arr[i])){
			hashLast.put(arr[i], i);
		}
	}
	/* Compute the max distance for all the characters */
	for(int i = 0; i < arr.length; i++){
		if(!result.containsKey(arr[i])){
			result.put(arr[i], hashLast.get(arr[i]) - hashFirst.get(arr[i]));
		}
	}
	
	return result;
}

- LB_Johnson April 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.HashMap;
import java.util.Map;
public class MaxDistance {
    public static Map<Integer, Integer> getMaxDists(int a[]) {
        Map<Integer, Integer> ret = new HashMap<Integer, Integer>();
        Map<Integer, Integer> firstOccurance = new HashMap<Integer, Integer>();
        int maxDist = 0;
        for (int i = 0; i < a.length; ++i) {
            Integer j = firstOccurance.get(a[i]);
            if (j == null) {
                firstOccurance.put(a[i], i);
                j = i;
            }
            ret.put(a[i], i - j);
        }
        return ret;
    }
    public static void main(String args[]) {
        int a[] = new int[] {1, 2, 3, 4, 1, 1, 7, 4};
        Map<Integer, Integer> ans = getMaxDists(a);
        for (Map.Entry<Integer, Integer> entry : ans.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}

- rixcat April 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

not understood

- Anonymous April 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Logic:
-Search the first occurrence of element from left side say elementLeftIndex
-Search the first occurrence of element from right side say elementRightIndex
-now [elementLeftIndex-elementRightIndex+1] is the max length as asked in qus
-apply logic for all elements

- PKT April 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

If both occurences of the number are adjacent, then it would result O(n^2) algorithm.

- Sudhindra.A April 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Sudhi:
We can use customized binary search for searching first occurrence from left and right...
so complexity can be 'nlog(n)'

- PKT April 21, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Agreed.

Step1 : Sorting elements - O(nlogn)
Step2 : Looping through the elements - O(nlogn)

- Sudhindra.A April 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Correct me if I'm wrong, but isn't the max distance the position of the last occurrence subtracted from the position of the first occurrence?

In C#

static uint FindDistance( List<int> numberList, int target ) {

	uint lastPos = ~0;
	uint firstPos= ~0;

	for( int i = 0; i < numberList.Count; ++i ) {
		if( numberList[ i ] == target ) {
			if( firstPos == ~0 ) 
				firstPos = i;

			lastPos = i;
		}	
	}

	return lastPos - firstPos;
}

- Bones April 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Target is not given to you. You have to find for all numbers and arrive at the solution.

- Sudhindra.A April 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

HashMap l_DistMap = new HashMap();
		
		for (int i = 0 ; i < input.length; i++)
		{
			if(! l_DistMap.containsKey(input[i]))
				l_DistMap.put(input[i],i);
		}
		
		int l_minIndex;
		
		for (int i = input.length - 1 ; i >= 0; i--)
		{
			if(l_DistMap.containsKey(input[i]))
			{
				l_minIndex = Integer.parseInt(l_DistMap.get(input[i]).toString());
				System.out.println(input[i] + ":" + i + " - " + l_minIndex + " = " + (i - l_minIndex));
				l_DistMap.remove(input[i]);
			}
		}

- Anonymous April 23, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

HashMap l_DistMap = new HashMap();
		
		for (int i = 0 ; i < input.length; i++)
		{
			if(! l_DistMap.containsKey(input[i]))
				l_DistMap.put(input[i],i);
		}
		
		int l_minIndex;
		
		for (int i = input.length - 1 ; i >= 0; i--)
		{
			if(l_DistMap.containsKey(input[i]))
			{
				l_minIndex = Integer.parseInt(l_DistMap.get(input[i]).toString());
				System.out.println(input[i] + ":" + i + " - " + l_minIndex + " = " + (i - l_minIndex));
				l_DistMap.remove(input[i]);
			}
		}

- Anonymous April 23, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

HashMap l_DistMap = new HashMap();
		
		for (int i = 0 ; i < input.length; i++)
		{
			if(! l_DistMap.containsKey(input[i]))
				l_DistMap.put(input[i],i);
		}
		
		int l_minIndex;
		
		for (int i = input.length - 1 ; i >= 0; i--)
		{
			if(l_DistMap.containsKey(input[i]))
			{
				l_minIndex = Integer.parseInt(l_DistMap.get(input[i]).toString());
				System.out.println(input[i] + ":" + i + " - " + l_minIndex + " = " + (i - l_minIndex));
				l_DistMap.remove(input[i]);
			}
		}

- Anonymous April 23, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. Create an array called index array which stores the indexes of elements of input array. Initialize index[i]=i for i=0 to n-1
2. Now sort the input array and while sorting also maintain the order of indexes in index array corresponds to the each element in the input array. This can be done using O(nlogn) sorting algorithm
3. Now traverse both the input and index arrays and calculate the max length for each element. This can be done on O(n) time.

Time Complexity: O(nlogn)
Space: O(n)

- f2003062 May 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

One important point to note here is that sorting has to be stable.

- Hello world June 02, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Hope this won't be considered cheating ;)

import re

def max_distance(elements):
    merged = ''.join([str(x) for x in elements])
    for item in elements:
        try:
            k = re.search(r'(%s.+%s)' % (item, item), merged).group(1)
        except:
            k = ' '
        print 'for %s: %s' % (item,(len(k)-1))

for 1: 5
for 2: 0
for 3: 0
for 4: 4
for 1: 5
for 1: 5
for 7: 0
for 4: 4

- BK November 27, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Iterate over an array from start to end for a given number, find out its first and last position in an array

int low=size;
int hight=-1;

for(i=0;i<size;i++)
{
	if( a[i] == x) / *x is input number */
		if( i < low )
			low = i;
		if( i > high )
			high = i;
}
if( high < low )
	return 0;

return high-low;

time complexity is O(n).

- confused_banda December 20, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

'x is input number'? what input number? there is only 1 array input

- Anonymous December 20, 2013 | Flag


Add a Comment
Name:

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

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More