Google Interview Question for Software Engineer Interns


Country: United States




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

public static <T> Iterator<T> repeat(T e, int num) {
		final T t = e;
		final int number = num;
		return new Iterator<T>() {
			private T object = t;

			private int repeatNumber = number;
			private int counter = 0;

			@Override
			public boolean hasNext() {
				return counter < repeatNumber;
			}

			@Override
			public T next() {
				counter++;
				return object;
			}

			@Override
			public void remove() {
				repeatNumber--;

			}
		};
	}

	public static void main(String[] args) {
		Iterator<String> iter = repeat("Test repeater", 7);
		while (iter.hasNext()) {
			System.out.println(iter.next());
		}
	}

- artak.a.petrosyan November 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

"remove" should remove the last returend value.
so:

Iterator<String> iter = repeat("Test repeater", 7);
		while (iter.hasNext()) {
			System.out.println(iter.next());
                        iter.remove();
		}

should print 7 values, I think you code doesn't. should be:

@Override
			public void remove() {
			// Simply do nothing

			}

- boaznahum November 14, 2015 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

Here's Python version :) :

def repeat(obj, N): 
    for i in range(N): 
        yield obj

- Mabooka November 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

/*
Showcasing ZoomBA iterator proto-object types
Try beating this one on elegance and aesthetics  
*/
def Iter : { obj : null , times : 0 , 
  $next : def(){
    break ( $.times <= 0 )
    $.times -= 1 
    $.obj
  }  
}
my_iter = new ( Iter , obj = 'ZoomBA' , times = 5 )
for ( my_iter ){
  println( $ )
}

- NoOne October 08, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// An example in golang using a closure.
// It simply decrements the counter on every call.
// Returns nil when the counter is zero.
// A use case is shown in the main function.

package main

import (
	"fmt"
)

// Returns an iterator of obj
func Iterator(obj interface{}, n int) (func() interface{}) {
	f := func() interface{} {
		if n > 0 {
			n--
			return obj
		} else {
			return nil
		}
	}
	return f
}

type Person struct {
	Name string
	Age int
}

func main() {
	p := Person{Name:"Bruce", Age:45}
	g := Iterator(p, 5)
	
	for v := g(); v != nil; v = g() {
		fmt.Println(v.(Person))
	}
}

/*
Output:
{Bruce 45}
{Bruce 45}
{Bruce 45}
{Bruce 45}
{Bruce 45}
*/

- zingcat November 12, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class ObjIterator<Object> implements Iterator<Object>{
	private ArrayList<Object> ls;
	int pos=0;
	
	ObjIterator(int count,Object toRepeat)throws NullPointerException, IllegalArgumentException
	{
		if(toRepeat==null)
		{
			throw new NullPointerException();
		}
		if(count<0)
		{
			throw new IllegalArgumentException
		}
		ls=new ArrayList<Object>(count);
		for(int i=0;i<count;i++)
		{
			ls.add(toRepeat);
		}
	}
	public boolean hasNext()
	{
		return (pos<ls.size());
	}
	public Object next()
	{
		return ls.get(pos++);
	}
	
	public Object remove()
	{
		return ls.remove(pos);
	}
}


public ObjectIterator<Object> repeat(Object e, int n)
{
	ObjectIterator it=new ObjectIterator(e,n);
	return it;
	
}

- divm01986 November 12, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

c++, implementation

#include <iostream>
#include <string>

using namespace std;

template <typename T>
struct Iterator {
	T obj;
	int cnt;
	Iterator(T e, int n) : obj(e), cnt(n) {}
	bool operator() (T& ret) {
		if (cnt > 0) {
			cnt--;
			ret = obj;
			return true;
		}
		return false;
	}
};

template <typename T>
Iterator<T> repeat(T e, int n) {
	Iterator<T> iterator(e, n);
	return iterator;
}

struct Object {
	int value;
	string name;
};

int main(int argc, char* argv[]) {
	int n = 3;
	Iterator<int> integerIterator = repeat(n, 5);

	n = -1;
	while (integerIterator(n)) {
		cout << n << " ";
	}
	cout << "\n";

	Object obj;
	obj.value = 7;
	obj.name = "ABC";
	Iterator<Object> objectIterator = repeat(obj, 3);
	
	obj.value = -1;
	obj.name = "";
	while (objectIterator(obj)) {
		cout << "(" << obj.value << ", " << obj.name << ") ";
	}
	cout << "\n";

    return 0;
}

- kyduke November 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

how come this is creating copy of object?
bool operator() (T& ret) {
if (cnt > 0) {
cnt--;
ret = obj;
return true;
}
return false;
}

- SDK_BU_CADP November 13, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

may be i am interpreting "producing" meaning differently. I assume it as creating copy of the object.

- SDK_BU_CADP November 13, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 vote

public <T> Iterator<T> repeat(final T obj, final int n) {
        return new AbstractList<T>() {
            public T get(int index) {
                return obj;
            }

            public int size() {
                return n;
            }


        }.iterator();

}

- adamstawicki91 November 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

with your code - i can get list.get(0) more than n times. Nothing stops me.

- ranganath.mr February 17, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Repeat {

    public static <T> Iterator<T> repeat(T object, int n) {
        return new MyIterator(object, n);
    }

    private static class MyIterator<T> implements Iterator<T> {

        final T object;
        int n;

        public MyIterator(T object, int n) {
            this.object = object;
            this.n = n;
        }

        @Override
        public boolean hasNext() {
            return n > 0 ? true : false;
        }

        @Override
        public T next() {
            if (!hasNext()) throw new IllegalStateException("No element to iterate over");
            n--;
            return object;
        }
    }
}

- rajat.shrivastava.aw November 13, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

c# implementation, quite straightforward.

using System;

namespace IteratorProducingElementsNTimes {

    public interface IIterator<T> {
        void First();
        void Next();
        bool IsDone();
        T CurrentItem();
    }

    public class Iterator<T> : IIterator<T> {
        private readonly T _obj;
        private readonly int _total;
        private int _current = 0;

        public Iterator( T obj, int total ) {
            _obj = obj;
            _total = total;
        }

        public void First() {
            _current = 0;
        }

        public void Next() {
            _current++;
        }

        public bool IsDone() {
            return _current > _total - 1;
        }

        public T CurrentItem() {
            return _obj;
        }
    }

    public struct Person {
        public string Name;
        public string Surname;

        public override string ToString() {
            return $"{Name}, {Surname}";
        }
    }

    public static class Program {

        private static Iterator<T> _repeate<T>( T obj, int n ) {
            return new Iterator<T>(obj, n);
        }

        static void Main(string[] args) {

            var iter = _repeate( new Person { Name = "John", Surname = "Coombes" }, 3 );
            iter.First();
            while ( !iter.IsDone() ) {
                Console.WriteLine( iter.CurrentItem() );
                iter.Next();
            }
            Console.ReadLine();
        }
    }
}

- zr.roman November 14, 2015 | Flag Reply


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