Interview Question


Country: United States
Interview Type: Phone Interview




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

Redis is an in-memory database implemnted in ANSI C.
I have tried to give a basic idea how something like this can be structured in C++ , in the implementation things can be added further .

#include<bits/stdc++.h>
#define ff first
#define ss second
#define pb push_back
#define redis_obj robj*


using namespace std;

class robj   //base class for redis objects , rest classes are to be derived from it 
{
	public :
		
	virtual string get()
	{
		
	}
	
	virtual string append(char v)
	{
			
	}
	
	virtual string append(string v)
	{
		
	}
	
	virtual void lpush(string v)
	{
		
	}
	
	virtual void rpush(string v)
	{
		
	}
	
	virtual void sadd(string s)
	{
		
	}
	
	
};

class sstring : public robj    //class for string in redis
{
	string val;
	
	public :
	
	sstring()               //constructor1
	{
		val.clear();
	}
	
	sstring(string v)           //constructor2
	{	
		val=v;
	}
	
	string get()              //returns string version of the data_Structure
	{
		return val;
	}
	
	string append(string v)              //func. to append string to the stored string.
	{
		val+=v;
		return val;
	}
	
	string append(char v)          //func. to append char to the stored string.
	{
		val.pb(v);
	}
};     

class llist:public robj 
{
	list<string> val;
	
	public :
		
	llist()   //constructor
	{
		val.clear();
	}
	
	llist(list<string> v)   //constructor 2           
	{
		val=v;
	}
	 
	void lpush(string v)   //function to insert in begining
	{
		val.push_front(v);
	}
	
	void rpush(string v)    //function to insert in the end
	{
		val.push_back(v);
	}
	
	string get()   
	{
		string tmp;
		for(list<string> :: iterator i=val.begin();i!=val.end();i++)
			tmp+=(*i)+" ";
			
		return tmp;
	}	
};

class sset:public robj     //class for set in redis , this can be implented using trie , I just implemnted using the c++ default set
{									// in redis it is implemented using hash
	set<string> val;
	
	public : 
	
	sset()             //cons.
	{
		val.clear();	
	}
	
	sset(set<string> v)    //cons.1
	{
		val=v;
	}
	
	void sadd(string s)  //adding val to the set
	{
		val.insert(s);
	}
	
	string get()
	{
		string tmp;
		
		for(set<string> :: iterator i=val.begin();i!=val.end();i++)
			tmp+=(*i)+" ";
				
		return tmp;
	}
		
};

class s_set : public robj       //class for sorted set in redis...
{
	set<string> val;
	
	public : 
	
	s_set()
	{
		val.clear();	
	}
	
	s_set(set<string> v)
	{
		val=v;
	}
	
	void sadd(string s)
	{
		val.insert(s);
	}
	
	
	string get()
	{
		string tmp;
		
		for(set<string> :: iterator i=val.begin();i!=val.end();i++)
			tmp+=(*i)+" ";
				
		return tmp;
	}
	
};

class hash : public robj         //although its O(1) in redis , i used map over here, 
{
	map<string,string> val;
	
	public :
	
	hash()
	{	
	}
	
	hash(map<string,string> s)
	{
		val=s;
	}

	string get()
	{
		string tmp ;  tmp.clear();
		
		for(map<string,string> :: iterator i=val.begin();i!=val.end();i++)
		{
				tmp+=i->ff+" "+i->ss+" ";
		}
		
		return tmp;
	}
	
};



int main()
{
	redis_obj s=new sstring();
	cout<<s->append("check")<<"\n";
		
	redis_obj li= new llist();	
	
	li->lpush("first");   li->rpush("second");    li->rpush("third");
	cout<<li->get()<<"\n";


	return 0;
}

- dhsharma27 May 27, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class SimpleDb(object):

""" Simple in-memory database as a response to the Thumbtack coding challenge. """

def __init__(self):
""" Initialize SimpleDb instance. """
self.__db = {}
self.__num_equal_to_cache = {}
self.__transactions = [] # Stores previous values to allow rollback

def assign(self, name, value):
""" Sets value of name to value. Inserts name into database if it doesn't already exist. """
current_value = self.get(name)
if current_value == value:
return
self.__update_num_equal_to(current_value, value)
self.__update_current_transaction(name, current_value)
self.__db[name] = value

def get(self, name):
""" Returns value of name if it exists in the database, otherwise returns None. """
return self.__db[name] if name in self.__db else None

def get_num_equal_to(self, value):
""" Returns number of entries in the database that have the specified value. """
return self.__num_equal_to_cache[value] if value in self.__num_equal_to_cache else 0

def unset(self, name):
""" Removes name from database if it's present. """
current_value = self.__db.pop(name, None)
if current_value is None:
return
self.__update_num_equal_to(current_value)
self.__update_current_transaction(name, current_value)

def begin(self):
""" Opens transaction block. """
self.__transactions += [{}]

def rollback(self):
"""
Reverts database to its state before most current transaction.
Returns True on success, returns False if there aren't any open transactions.
"""
if not self.__transactions:
return False
for name, value in self.__transactions.pop().iteritems():
current_value = self.get(name)
if current_value == value:
continue
self.__update_num_equal_to(current_value, value)
if value is None:
del self.__db[name]
else:
self.__db[name] = value
return True

def commit(self):
"""
Commits all transactions to database. Returns True on success,
returns False if there aren't any open transactions.
"""
if not self.__transactions:
return False
self.__transactions = []
return True

def __update_num_equal_to(self, current_value, new_value=None):
"""
Decrements by one the number items present with current_value (if current_value
is not equal to None) and increments by one the number present with new_value
(if new_value is not equal to None).
"""
for amount_to_add, value in [(-1, current_value), (1, new_value)]:
if value is not None:
self.__num_equal_to_cache.setdefault(value, 0)
self.__num_equal_to_cache[value] += amount_to_add

def __update_current_transaction(self, name, value):
"""
Stores current value of name if not already stored to most recent transaction
(if any transactions open) to enable restoration of previous state on rollback.
"""
if self.__transactions and name not in self.__transactions[-1]:
self.__transactions[-1][name] = value


def display(value, default=None):
"""
Prints value to stdout. If value is None and a default value is
specified (and not None), then the default value is printed instead. Otherwise
the None value is printed.
"""
if value is None and default is not None:
value = default
print value


OPS = {
'GET': (2, lambda db, name: display(db.get(name), "NULL")),
'NUMEQUALTO': (2, lambda db, value: display(db.get_num_equal_to(value))),
'UNSET': (2, lambda db, name: db.unset(name)),
'BEGIN': (1, lambda db: db.begin()),
'ROLLBACK': (1, lambda db: db.rollback() or display("NO TRANSACTION")),
'COMMIT': (1, lambda db: db.commit() or display("NO TRANSACTION")),
'END': (1, lambda db: False),
'SET': (3, lambda db, name, value: db.assign(name, value)),
}


def process_command(simpleDb, command):
"""
Parses string commands and applies them to the database.
Returning False indicates that no more commands should be passed in.
"""
command = command.split()
opcode = command.pop(0).upper() if len(command) > 0 else None
if opcode is None or opcode not in OPS or len(command) != (OPS[opcode][0] - 1):
print "INVALID COMMAND"
elif 'END' == opcode:
return False
else:
OPS[opcode][1](simpleDb, *command)
return True


def run():
""" Reads database command from the command line and passes it through for processing. """
# BEGIN \n SET a 30 \n BEGIN \n SET a 40 \n COMMIT \n GET a \n ROLLBACK \n END
simpleDb = SimpleDb()
while process_command(simpleDb, raw_input()):
pass

run()

- manojsetty.02 July 30, 2016 | 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