maitreyak
BAN USER
python
def combinations(sofar,phno,numpad):
if phno == '' or phno is None:
print sofar
return
for dig in phno:
options = numpad[int(dig)]
for op in options:
combinations(sofar+op,phno[1:],numpad)
numpad = {2: ["A", "B", "C"],
3: ["D", "E", "F"],
4: ["G", "H", "I"],
5: ["J", "K", "L"],
6: ["M", "N", "O"],
7: ["P", "Q", "R", "S"],
8: ["T", "U", "V"],
9: ["W", "X", "Y", "Z"]};
combinations('','23',numpad)
Merging two lists at a time. The solution is O(N). Where N is the total number of elements.
def merge(l1,l2):
len1 = len(l1)-1
len2 = len(l2)-1
#expand the l1 to the size of l1+l2
l1.extend([None]*(len2+1))
#Traverse in reverse.
for index in range(len(l1))[::-1]:
if len1<0 or len2<0:
break
if l1[len1] >= l2[len2]:
l1[index] = l1[len1]
len1-=1
else:
l1[index] = l2[len2]
len2-=1
return l1
def sortList(lol):
mainl = lol[0]
for l in range(1,len(lol)):
mainl = merge(mainl,lol[l])
return mainl
input = [ [2, 5, 10], [25, 100, 105], [7, 56, 42]]
print sortList(input)
Python
def OneEditApartImpl(big,small,limit,lag):
hit = 0
for index, letters in enumerate(zip(big,small)):
if letters[0]!=letters[1]:
hit+=1
if hit > limit:
return False
return OneEditApartImpl (big[index+1:],small[index+1-lag:],0,0)
return True
def OneEditApart(word1,word2):
len1 = len(word1)
len2 = len(word2)
#trival: lenght greater than 1
if abs(len1 - len2) > 1:
return False
#trival: string are equal
if word1 == word2:
return True
#non trial cases
if(len1==len2):
return OneEditApartImpl(word1,word2,1,0)
elif(len1>len2):
return OneEditApartImpl(word1,word2,1,1)
else:
return OneEditApartImpl(word2,word1,1,1)
assert OneEditApart("cat", "dog") == False
assert OneEditApart("cat", "cats") == True
assert OneEditApart("cat", "cut") == True
assert OneEditApart("cat", "cast") == True
assert OneEditApart("cat", "at") == True
assert OneEditApart("cat", "acts") == False
Think in terms of a substitution cipher. String1 is the input, we apply a cipher and we get the string2. The problem is can we find a substitution cipher or in other words, are the strings isomorphic.
To check if two stings are isomorphic, one would not have keep counts. Below O(1) space implementation(bitVector implementation) that works for alphabets.
public class Isomorphic {
public boolean isIsomorphic(String word1, String word2){
long bitMap1 = 0;
long bitMap2 = 0;
long mask1 = 0;
long mask2 = 0;
for (int i=0;i<word1.length();i++){
long res1,res2;
//left shift 1, the ascii value amount of times
mask1 = 1 << (int)(word1.charAt(i));
mask2 = 1 << (int)(word2.charAt(i));
//XOR the mask
res1 = bitMap1 ^ mask1 ;
res2 = bitMap2 ^ mask2 ;
//either both have to be 0 or both have to be non-zero
if((res1>0 && res2>0) || (res1==0&& res2==0)){
bitMap1|= mask1;
bitMap2|= mask2;
continue;
}
return false;
}
return true;
}
}
The code prints all forms without duplicates. This question (solution) is in "Cracking the coding interview" Book.
def paren(left,right,string):
if(left == 0 and right == 0):
print string
if(left>right):
return
if (left > 0):
paren(left-1,right,string+"(")
if (right > 0):
paren(left,right-1,string+")")
def parentheses(n):
paren(n/2,n/2,"")
parentheses(6)
output:
((()))
(()())
(())()
()(())
()()()
I have a similar implementation as yours in the same thread.(in python as well). The thing is you have a string "==" inside the loop. "==" is an operation that takes O(M), where m is the size of the smaller string. The program takes O(N*M). To avoid that "==" I had to use a dictionary.
- maitreyak December 02, 2013The Algorithm will take O(N) time and O(Constant) space. Python.
def reArrange(elements):
elementCount = len(elements)
for i in range(0,elementCount)[::2]:
#subList will have atmost 3 elements
subList = (elements[i:i+3])
if(len(subList)>1):
#again subList is atmost 3 elements long.
#sorting 3 elements is a constant time operation.
subList= sorted(subList)
#If the sublist has 3 elements then swap the last two
if(len(subList)>2):
temp = subList[-1]
subList[-1] = subList[-2]
subList[-2] = temp
#copy subList back to the element list
for index in range(0,len(subList)):
elements[i+index] = subList[index]
return elements
print reArrange([10,3,4,5,6,7,1,2,9,8])
#output: 3, 10, 4, 6, 1, 7, 2, 9, 5, 8
Here we build the hash with all the suffixes of the longer string. Only the keys are truncated to the size of smaller string. Time Complexity O(N) with a hash ofcourse. Written in Python.
def isSubString(mainString,subString):
subStrLen = len(subString)
#hash
suffixHash = {}
for i in range(0,len(mainString)):
key = mainString[i:i+subStrLen]
suffixHash[key] = True
print suffixHash.keys()
if subString in suffixHash:
print "True"
else:
print "False"
isSubString("hellothisiscool", "isi")
Repellabryan25416, Accountant at A9
Hello, I am a Managing editor. I have completed my studies from New York. Apart from this, whenever I am ...
RepAsaDills, HR Executive Trainee at Cerner Corporation
I 'm Asa Dills, My role of the Public Housing Manager (PHM) is complex. the financial viability of the property ...
RepKatieKate, Developer at Amazon
Katie , a general laborer skilled in construction work, landscaping and trimming, and other commercial and residential tasks. Love to find ...
Repaanyagill, café manager at The Best Cafe
Unshakable dedication to bringing out the best in a restaurant and its employees, while taking exemplary care of guests and ...
Repyahviross, translator at learnify
Dedicated English-Mandarin Chinese translator with years of experience working in professional and scientific communities.Diverse translation work including proprietary scientific ...
Repaalexlingram, AT&T Customer service email at ABC TECH SUPPORT
I am Alex and I live in Colorado Springs . I am working as a International human resources manager and I ...
RepBarbaraLocke, Android test engineer at ABC TECH SUPPORT
Hey, I'm a BarbaraLocke. And I love my work. Apart from this, I am doing some new experiments in ...
Repherminanmuller87, Animator at 247quickbookshelp
Hello,I am a literacy teacher. I completed my degree from Chicago and now am a literacy teacher in a ...
Repsonjamramos45, Graphics Programmer at CGI-AMS
I am a strong writer with a passion for story-telling who has extensive experience of writing literary compositions, articles, reports ...
RepHi, I am Maria from Worcester, USA. I have been working as a Blogger in Enticing Express from last 2 ...
Repgarlandkrebs, Animator at ADP
Highly focused and seasoned magazine editor with vast experience in all stages of weekly and monthly magazine production. My aim ...
Repcarlotamdaniel, abc at ADP
Repgiannanewhart, Cloud Support Associate at ABC TECH SUPPORT
I am Clinical managers, a type of medical and health services manager, and work as managers in both administrative areas ...
Reppaulinedsisk, Testing / Quality Assurance at Cloudmere, Inc.
I want to become a successful professional in a highly competitive technological world where performance is rewarded with exciting new ...
Repnatetouche, Applications Developer at Alcatel Lucent
My name is NateTouche . I currently live in Seattle . One desire that has always been a constant since As a ...
Repellaiyer15, Content Writer at Precious Moments
Committed to producing exceptional and creative types of content, including articles, internet content, advertisements, commercials, brochures, and publications. Experienced in ...
RepRuthMitchell, Applications Developer at ASAPInfosystemsPvtLtd
My name is Mitchell working as a technical sales support worker in the USA. I identify and establish new business ...
Repjacksabjohne, Accountant at ABC TECH SUPPORT
Michael is a Biological Technician with 4 years of experience monitoring, characterizing, and quantifying riverine processes and habitat in the ...
Reprafaeltanner210, Associate at 247quickbookshelp
I am Labor relations directors, oversee employment policies in union and nonunion settings. I draw up, negotiate, and administer labor ...
Reprealspellcaster4, Cloud Support Associate at Aricent
Hi, I am from PA, United states. I believe in making the impossible possible because there’s no fun in ...
Repkylecfarrell, Personnel at Bocada
Property custodian with a reputed organization and help in keeping accurate check over the supplies and inventory of materials and ...
Replarryehickl, Associate at ABC TECH SUPPORT
I am a blogger in the Geek system operator . As an editor with a strong background in english and hindi ...
Repandreemsims8765, Accountant at 247quickbookshelp
AndreeSims and I am a Clinical social worker.And nowadays I am doing new research like dua to make someone ...
Repeleanormzavala63, Android Engineer at 247quickbookshelp
Hello I am a publicity agent, I have completed all my studies from Brighton. And now-a-days I am working as ...
Repjeannetucker768, Analyst at 247quickbookshelp
Hello I am a computer programmer. I have completed all my studies from New York. Currently I am working in ...
Repruchimosha, Analyst at Absolute Softech Ltd
My name is MaryDuncan . I am working at Crandall's Fine Furniture as a Probation officer . Here I am dealing ...
RepRoseLeen, abc at 8x8
I am a strongly seasoned and handworking entry level graphic designer with extraordinary creative thinking and project design abilities. I ...
RepBellaReyes, Android Engineer at ADP
I am a creative and dedicated photo editor with experience in photojournalism and marketing material development. I have a proven ...
RepRosieBell, Accountant at 8x8
I have technical knowledge of multiple camera technologies -Extensive communication, cooperation, and service skills -Critical thinking, analysis, free revenge spells ...
RepTimothyAYocum1, Android Engineer at ABC TECH SUPPORT
I am a medical or osteopathic doctor who specializes in eye and vision care. My work Ophthalmologists differ from optometrists ...
RepEvaSanchez, Animator at Abs india pvt. ltd.
Eva , Manufacturing Worker with 3+ years of experience working in Dynatronics . Went for traveling around the world and gets to ...
RepNaomiMoore, abc at A9
I have wide experience with commercial negotiations and international transactions.Advising on the incorporation and related shareholder agreements for a ...
RepSpent 2001-2007 promoting augmented reality integrated through social media in West Palm Beach, FL. Won several awards for merchandising Roombas ...
RepDonnaArvin, Analyst at Apple
Hii am from the United States. I work as a computer control programmer at Dynatronics Accessories. I am a social ...
Repdelenestanf0, HR Executive at Agilent Technologies
Hi, I am a Clinical social worker. methods of prevention and treatment in providing mental-health/healthcare services, I also have ...
RepEllaAllen, Accountant at 247quickbookshelp
I am a senior graphic designer with many years of experience managing quarter-million dollar design budgets. I specialize in strategic ...
python
- maitreyak May 05, 2014