You are on page 1of 19

nb

dn
bd
nb
d0
00
nb nb @
dn dn gm
bd bd ai
00 nbd
l.
co
0@ 00 m
gm 0@
ai gm
l.
co ai
m

算法面试宝典
l.
co
m
m
co
l.
匠⼈学院成⽴于2017年 ⼒于 助在

ai
gm ⼈ 让找⼯作不再是难事 是 学习和⼯作
伴 超过10000的⼩ 伴加 我们 三年服务超

m
过了5000 学⽣ 助 ⼈从学业困难 到就业
@

co
困难 超过800 位同学拿到了Offer 进 了
00

l.
主 社会 我们希 成为下⼀代的 助

ai
d0

更 的 ⼈ 决问题 希 同样⽬标 志同

gm
合的⼈加
nb

0@
bd
dn

00
nb

bd
n
bd
dn

m
nb

co
l.
ai
gm
0@
00
bd
dn
nb
m
co
从学业 实习 到就业培训 司猎头 学习平台 更 ⽅位 助学⽣

l.
ai
gm

m
@

co
00

l.
ai
d0

gm
nb

0@
bd
dn

00

盖软件开发 Web开发 UI/UX 维 ⼈⼒资源 动端开发 数据


nb

bd

析 数据科学 市场营销
n
bd
dn

m
nb

co
l.
ai
gm
0@
00
bd
dn
nb
⾯试题
1.Whatisanalgorithm?Whatistheneedforanalgorithm?

m
co
Analgorithmisawell-definedcomputationalprocedurethattakessome

l.
valuesorthesetofvalues,asaninputandproducesasetofvaluesor

ai
somevalues,asanoutput.
 gm
needforalgorithm:

m
Thealgorithmprovidesthebasicideaoftheproblemandanapproachto
@

co
solveit.Somereasonstouseanalgorithmareasfollows.
00

l.
Thealgorithmimprovestheefficiencyofanexistingtechnique.

ai
d0

Tocomparetheperformanceofthealgorithmwithrespecttoother
techniques.

gm
nb

Thealgorithmgivesastrongdescriptionofrequirementsandgoalof
theproblemstothedesigner. 0@
bd

Thealgorithmprovidesareasonableunderstandingoftheflowofthe
program.
dn

Thealgorithmmeasurestheperformanceofthemethodsindifferent
00

cases(Bestcases,worstcases,averagecases).
nb

Thealgorithmidentifiestheresources(input/output,memory)cycles
bd

requiredbythealgorithm.
Withthehelpofanalgorithm,wecanmeasureandanalyzethe
n

complexitytimeandspaceoftheproblems.
bd

Thealgorithmalsoreducesthecostofdesign.
dn


m
nb

co
l.
ai
gm
0@
00
bd
dn
nb
⾯试题
2.WhatistheComplexityofAlgorithm?

m
co
Thecomplexityofthealgorithmisawaytoclassifyhowefficientan

l.
algorithmiscomparedtoalternativeones.Itsfocusisonhowexecution

ai
timeincreaseswiththedatasettobeprocessed.Thecomputational
gm
complexityofthealgorithmisimportantincomputing.
Itisverysuitabletoclassifyalgorithmbasedontherelativeamountof

m
timeorrelativeamountofspacetheyrequiredandspecifythegrowthof
@

co
time/spacerequirementasafunctionofinputsize
00

l.
Timecomplexity

ai
d0

TimecomplexityisaRunningtimeofaprogramasafunctionofthesize
oftheinput.

gm
nb


Spacecomplexity 0@
bd

Spacecomplexityanalyzesthealgorithms,basedonhowmuchspacean
algorithmneedstocompleteitstask.Spacecomplexityanalysiswas
dn

criticalintheearlydaysofcomputing(whenstoragespaceonthe
00

computerwaslimited).Nowadays,theproblemofspacerarelyoccurs
nb

becausespaceonthecomputerisbroadlyenough.Weachievethe
bd

followingtypesofanalysisforcomplexity.

n

Worst-case:f(n)
bd

Itisdefinedbythemaximumnumberofstepstakenonanyinstanceof
dn

sizen.
m
Best-case:f(n)
nb

co

Itisdefinedbytheminimumnumberofstepstakenonanyinstanceof
sizen.
l.

Average-case:f(n)
Itisdefinedbytheaveragenumberofstepstakenonanyinstanceofsize
ai

n.
gm
0@
00
bd
dn
nb
⾯试题
3.Writeanalgorithmtoreverseastring.Forexample,ifmy

m
stringis uhsnamiH thenmyresultwillbe Himanshu .

co
l.
ai
Algorithm to reverse a string.
 gm
Step1: start


m
@

co
Step2: Take two variable i and j

00

l.
Step3: do length (string)-1, to set J at last position


ai
d0

gm
Step4: do string [0], to set i on the first character.

nb

Step5: string [i] is interchanged with string[j] 0@


bd


dn

Step6: Increment i by 1

00
nb

Step7: Increment j by 1
bd


n

Step8: if i>j then go to step3



bd

Step9: Stop

dn

m
nb

co
l.
ai
gm
0@
00
bd
dn
nb
⾯试题
4.Writeanalgorithmtoinsertanodeinasorted

m
linkedlist. 

co
l.
ai
Algorithm to insert a node in a sorted linked list.
Case1:
gm
Check if the linked list is empty then set the node as head and

m
return it.
@
1. New_node-> Next= head;

co
2. Head=New_node

00

l.
ai
d0

Case2:
Insert the new node in middle

gm
nb

1. While( P!= insert position)


2. {
0@
bd

3. P= p-> Next;
4. }
dn

5. Store_next=p->Next;
00

6. P->Next= New_node;
nb

7. New_Node->Next = Store_next;
bd


n

Case3:
bd

Insert a node at the end


1. While (P->next!= null)
dn

m
2. {
3. P= P->Next;
nb

co

4. }
5. P->Next = New_Node;
l.

6. New_Node->Next = null;


ai
gm
0@
00
bd
dn
nb
⾯试题
5.WhataretheAsymptoticNotations?

m
co
Asymptotic analysis is used to measure the efficiency of an algorithm that

l.
doesn't depend on machine-specific constants and prevents the algorithm

ai
from comparing the time taking algorithm. Asymptotic notation is a
mathematical tool that is used to represent the time complexity of
gm
algorithms for asymptotic analysis.

m
The three most used asymptotic notation is as follows.

@

co
00

θ Notation

l.
θ Notation defines the exact asymptotic behavior. To define a behavior, it

ai
d0

bounds functions from above and below. A convenient way to get Theta
notation of an expression is to drop low order terms and ignore leading

gm
nb

constants.
0@
bd
dn

00
nb

n bd
bd

Big O Notation
dn

The Big O notation bounds a function from above, it defines an upper bound of an
m
algorithm. Let's consider the case of insertion sort; it takes linear time in the best case
nb

co

and quadratic time in the worst case. The time complexity of insertion sort is O(n2). It is
useful when we only have upper bound on time complexity of an algorithm.

l.

ΩNotation
ai

JustlikeBigOnotation
gm

providesanasymptoticupperbound,theΩNotation
providesanasymptoticlowerboundonafunction.It
isusefulwhenwehavelowerboundon
0@

timecomplexityofanalgorithm.
00
bd
dn
nb
⾯试题

m
6.ExplaintheBubblesortalgorithm?

co
l.
Bubble sort is the simplest sorting algorithm among all sorting algorithm. It
repeatedly works by swapping the adjacent elements if they are in the

ai
wrong order.
e.g. gm
(72538) we have this array for sorting.

m
Pass1:
@

co
(72538) -> (27538) swap 7 and 2.
00

(27538) -> (25738) swap 7 and 5

l.
(25738) -> (25378) swap 7 and 3.

ai
d0

(25378) -> (25378) algorithm does not swap 7 and 8 because 7<8.

gm
Pass2:
nb

(25378) -> (25378) algorithm does not swap 2 and 5 because 2<5.
(25378) -> (23578) swap 3 and 5. 0@
bd

(23578) -> (23578) algorithm does not swap 5 and 7 because 5<7.
(23578) -> (23578) algorithm does not swap 7 and 8 because 7<8.
dn

Here, the sorted element is (23578).


00


nb

7.ExplaintheBubblesortalgorithm?
n bd

Dijkstra's algorithm is an algorithm for finding the shortest path from a


bd

starting node to the target node in a weighted graph. The algorithm makes
a tree of shortest paths from the starting vertex and source vertex to all
dn

other nodes in the graph. Suppose you want to go from home to office in
m
the shortest possible way. You know some roads are heavily congested
nb

co

and challenging to use this, means these edges have a large weight.
In Dijkstra's algorithm, the shortest path tree found by the algorithm will try
l.

to avoid edges with larger weights.


ai
gm
0@
00
bd
dn
nb
⾯试题

m
8.Howtoswaptwointegerwithoutswappingthe

co
temporaryvariableinJava?

l.
ai
It's a very commonly asked trick question. There are many ways to solve
gm
this problem. But the necessary condition is we have to solve it without

m
swapping the temporary variable. If we think about integer overflow and
@
consider its solution, then it creates an excellent impression in the eye of

co
interviewers.
00

Suppose we have two integers I and j, the value of i=7 and j=8 then how

l.
will you swap them without using a third variable. This is a journal problem.

ai
d0

We need to do this using Java programming constructs. We can swap

gm
numbers by performing some mathematical operations like addition,
nb

subtraction, multiplication, and division. But maybe it will create the problem
of integer overflow. 0@
bd

Using addition and subtraction


1. a= a + b;
dn

00
2. b=a - b; // this will act like (a+b)-b, now b is equal to a.
3. a=a - b; // (a+b)-a, now, a is equal to b.
nb

bd

It is a nice trick. But in this trick, the integer will overflow if the addition is
more than the maximum value of int primitive as defined by
n

Integer.MAX_VALUE and if subtraction is less than minimum value i.e.,


bd

Integer.MIN_VALUE.
dn

Using XOR trick


m
Another solution to swap two integers without using a third variable (temp
nb

co

variable) is widely recognized as the best solution, as it will also work in a


language which doesn't handle integer overflow like Java example C, C++.
l.

Java supports several bitwise operators. One of them is XOR (denoted by


ai

^).
1. x=x^y;
gm

2. y=x^y;
3. x=x^y;
0@
00
bd
dn
nb
⾯试题
9.WhatisaHashTable?Howcanweusethis

m
structuretofindallanagramsinadictionary?

co
l.
A Hash table is a data structure for storing values to keys of arbitrary type.

ai
The Hash table consists of an index into an array by using a Hash function.
gm
Indexes are used to store the elements. We assign each possible element
to a bucket by using a hash function. Multiple keys can be assigned to the

m
same bucket, so all the key and value pairs are stored in lists within their
@

co
respective buckets. Right hashing function has a great impact on
00

performance.

l.
To find all anagrams in a dictionary, we have to group all words that contain the

ai
d0

same set of letters in them. So, if we map words to strings representing their sorted
letters, then we could group words into lists by using their sorted letters as a key.

gm
nb

1. FUNCTION find_anagrams(words) 0@
bd

2. word_groups = HashTable<String, List>


dn

3. FOR word IN words


00

4. word_groups.get_or_default(sort(word), []).push(word)
nb

5. END FOR
bd

6. anagrams = List
7. FOR key, value IN word_groups
n

8. anagrams.push(value)
bd

9. END FOR
10. RETURN anagrams

dn

m
nb

co

The hash table contains lists mapped to strings. For each word, we add it to the list
at the suitable key, or create a new list and add it to it.

l.
ai
gm
0@
00
bd
dn
nb
⾯试题
10.ExplaintheBFSalgorithm?

m
BFS (Breadth First Search) is a graph traversal algorithm. It starts

co
traversing the graph from the root node and explores all the neighboring

l.
nodes. It selects the nearest node and visits all the unexplored nodes.
The algorithm follows the same procedure for each of the closest nodes

ai
until it reaches the goal state.
gm

m
Algorithm
@
Step1: Set status=1 (ready state)

co
Step2: Queue the starting node A and set its status=2, i.e. (waiting state)
00

Step3: Repeat steps 4 and 5 until the queue is empty.

l.
Step4: Dequeue a node N and process it and set its status=3, i.e.

ai
d0

(processed state)

gm
Step5: Queue all the neighbors of N that are in the ready state (status=1)
nb

and set their status =2 (waiting state)


[Stop Loop] 0@
bd

Step6: Exit

dn

11.WhatisDijkstra sshortestpathalgorithm?
00
nb

bd

Dijkstra's algorithm is an algorithm for finding the shortest path from a


starting node to the target node in a weighted graph. The algorithm
n

makes a tree of shortest paths from the starting vertex and source vertex
bd

to all other nodes in the graph. Suppose you want to go from


home to office in the shortest possible way. You know some roads are
dn

m
heavily congested and challenging to use this, means these edges have a
large weight. In Dijkstra's algorithm, the shortest path tree found by the
nb

co

algorithm will try to avoid edges with larger weights.


l.

12.GivesomeexamplesofDivideandConquer
ai

algorithm?
gm

Some problems that use Divide


and conquer algorithm to find their solution are listed below.
0@

Merge Sort
Quick Sort
00

Binary Search
Strassen's Matrix Multiplication
bd

Closest pair (points)


dn
nb
⾯试题
13.WhatareGreedyalgorithms?Givesomeexample

m
ofit?

co
l.
A greedy algorithm is an algorithmic strategy which is made for the best

ai
optimal choice at each sub stage with the goal of this, eventually leading to
a globally optimum solution. This means that the algorithm chooses the
gm
best solution at the moment without regard for consequences.

m
In other words, an algorithm that always takes the best immediate, or
@
local, solution while finding an answer.

co
Greedy algorithms find the overall, ideal solution for some idealistic
00

l.
problems, but may discover less-than-ideal solutions for some instances of
other problems.

ai
d0

Below is a list of algorithms that finds their solution with the use of the

gm
Greedy algorithm.
nb

o Travelling Salesman Problem


0@
bd

o Prim's Minimal Spanning Tree Algorithm


o Kruskal's Minimal Spanning Tree Algorithm
dn

o Dijkstra's Minimal Spanning Tree Algorithm


00

o Graph - Map Coloring


nb

o Graph - Vertex Cover


bd

o Knapsack Problem
o Job Scheduling Problem

n

14.Whatisalinearsearch?
bd

Linear search is used on a group of items. It relies on the technique of


dn

m
traversing a list from start to end by visiting properties of all the elements
nb

that are found on the way. For example, suppose an array of with some
co

integer elements. You should find and print the position of all the elements
l.

with their value. Here, the linear search acts in a flow like matching each
element from the beginning of the list to the end of the list with the integer,
ai

and if the condition is `True then printing the position of the element.'
gm

Implementing Linear Search


Below steps are required to implement the linear search.
0@

Step1: Traverse the array using for loop.


Step2: In every iteration, compare the target value
with the current value of the array
00

Step3: If the values match, return the current index of


the array
bd

Step4: If the values do not match, shift on to the next


array element.
dn

Step5: If no match is found, return -1


nb
⾯试题
15.WhatisaBinarySearchTree?

m
co
The binary search tree is a special type of data structure which has the following

l.
properties.
o Nodes which are less than root will be in the left subtree.

ai
o Nodes which are greater than root (i.e., contains more value) will be right subtree.
gm
o A binary search tree should not have duplicate nodes.

m
o Both sides subtree (i.e., left and right) also should be a binary search tree.

@

co
00

l.
ai
d0

gm
nb

0@
bd
dn

00
nb

bd

16.Writeanalgorithmtoinsertanodeinthe
n

Binarysearchtree?
bd
dn

Insert node operation is a smooth operation. You need to compare it with


m
the root node and traverse left (if smaller) or right (if greater) according to
nb

co

the value of the node to be inserted.


Algorithm:
l.

o Make the root node as the current node


ai

o If the node to be inserted < root


o If it has left child, then traverse left
gm

o If it does not have left child, insert node here


o If the node to be inserted > root
0@

o If it has the right child, traverse right


o If it does not have the right child, insert node here.

00
bd
dn
nb
⾯试题
17.Howtocountleafnodesofthebinarytree?

m
co
Algorithm-

l.
Steps for counting the number of leaf nodes are:

ai
o If the node is null (contains null values) then return 0.
o If encountered leaf node. Left is null and node Right is null then return 1.
gm
o Recursively calculate the number of leaf nodes using

m
No. of leaf nodes= no of leaf nodes in left subtree + number of leaf nodes in the
@

co
right subtree.

00

l.
18.Howtofindallpossiblewordsinaboardof

ai
d0

characters(Bogglegame)?

gm
nb

In the given dictionary, a process to do a lookup in the dictionary and an M x N


0@
bd

board where every cell has a single character. Identify all possible words that can
be formed by order of adjacent characters. Consider that we can move to any of
dn

the available 8 adjacent characters, but a word should not have multiple instances
00

of the same cell.


nb


bd

Example:
1.dictionary[]={ Java , Point , Quiz };
n

2.Array[][]={{ J , T , P ,},
bd

3.{ U , A , A },
4.{ Q , S , V }};
dn

m
5.isWord(str):returnstrueifstrispresentindictionary
nb

co

6. else false.

Output:
l.

Followingwordsofthedictionaryarepresent
ai

JAVA
gm


0@
00
bd
dn
nb
⾯试题
19.Writeanalgorithmtoinsertanodeinalinklist?

m
co
Algorithm
oCheckIftheLinkedlistdoesnothaveanyvaluethenmakethenodeas

l.
headandreturnit

ai
oCheckifthevalueofthenodetobeinsertedislessthanthevalueof
gm
theheadnode,theninsertthenodeatthestartandmakeithead.
oInaloop,findtheappropriatenodeafterwhichtheinputnodeistobe

m
inserted.Tofindthejustnodestartfromthehead,keepforwardinguntil
@

co
youreachanodewhosevalueisgreaterthantheinputnode.Thenode
00

justbeforeistheappropriatenode.

l.
o Insert the node after the proper node found in step 3.

ai
d0

gm
nb

20.Explainhowtheencryptionalgorithm
works?
0@
bd

Encryptionisthetechniqueofconvertingplaintextintoasecretcode
dn

00

formatitisalsocalledas Ciphertext. Toconvertthetext,thealgorithm


nb

usesastringofbitscalledas keys forcalculations.Thelargerthekey,


bd

thehigherthenumberofpotentialpatternsforEncryption.Mostofthe
algorithmusecodesfixedblocksofinputthathavealengthofabout64
n

to128bits,whilesomeusesstreammethodforencryption.
bd

21.WhatAreTheCriteriaOfAlgorithm
dn

Analysis?
nb

co

Analgorithmisgenerallyanalyzedbytwofactors.
l.

oTimecomplexity
ai

oSpacecomplexity
gm

Timecomplexitydealswiththequantificationoftheamountof
timetakenbyasetofcodeoralgorithmtoprocessorrunasafunction
oftheamountofinput.Inotherwords,thetimecomplexityisefficiency
0@

orhowlongaprogramfunctiontakestoprocessagiveninput.
Spacecomplexityistheamountofmemoryusedbythealgorithmto
executeandproducetheresult.
00
bd
dn
nb
⾯试题
22.Howtodeleteanodeinagivenlinklist?Writean

m
algorithmandaprogram?

co
WriteafunctiontodeleteagivennodefromaSinglyLinkedList.Thefunction
mustfollowthefollowingconstraints:

l.
oThefunctionmustacceptapointertothestartnodeasthefirstargumentand

ai
nodetobedeletedasthesecondargument,i.e.,apointertoheadnodeisnot
gm
global.
oThefunctionshouldnotreturnapointertotheheadnode.

m
@
o The function should not accept pointer to pointer to head node.

co
WemayassumethattheLinkedListneverbecomesempty.
00

SupposethefunctionnameisdelNode().Inadirectimplementation,the

l.
functionneedstoadjusttheheadpointerwhenthenodetobedeletedthefirst

ai
d0

node.
CprogramfordeletinganodeinLinkedList

gm
nb

We will handle the case when the first node to be deleted then we copy the data of the next
0@
bd

node to head and delete the next node. In other cases when a deleted node is not the head
node can be handled generally by finding the previous node.

dn

00
nb

n bd
bd
dn

m
nb

co
l.
ai
gm
0@
00
bd
dn
nb
⾯试题
23.Writeacprogramtomergealinklistintoanother

m
atanalternateposition?

co
Wehavetwolinkedlists,insertnodesofthesecondlistintothefirstlistat

l.
substitutepositionsofthefirstlist.
Example

ai
iffirstlistis1->2->3andsecondis12->10->2->4->6,thefirstlistshould
gm
become1->12->2->10->17->3->2->4->6andsecondlistshouldbecome
empty.Thenodesofthesecondlistshouldonlybeinsertedwhenthere

m
@
arepositionsavailable.

co
Useofextraspaceisnotallowedi.e.,insertionmustbedoneinaplace.
00

PredictabletimecomplexityisO(n)wherenisnumberofnodesinfirstlist.

l.
ai
d0

gm
nb

0@
bd
dn

00
nb

n bd
bd
dn

m
nb

co
l.
ai
gm
0@
00
bd
dn
nb
⾯试题
24. What are the differences between stack and Queue?

m
co
StackandQueuebotharenon-primitivedatastructureusedforstoring
dataelementsandarebasedonsomereal-worldequivalent.

l.
Let shavealookatkeydifferencesbasedonthefollowingparameters.

ai
Workingprinciple
Thesignificantdifferencebetweenstackandqueueisthatstackuses
gm
LIFO(LastinFirstOut)methodtoaccessandadddataelements

m
whereasQueueusesFIFO(Firstinfirstout)methodtoobtaindata
@
member.

co
Structure
00

l.
InStack,thesameendisusedtostoreanddeleteelements,butin
Queue,oneendisusedforinsertion,i.e.,rearendandanotherendis

ai
d0

usedfordeletionofelements.

gm
Numberofpointersused
nb

StackusesonepointerwhereasQueueusestwopointers(inthesimple
0@
case).
bd

Operationsperformed
dn

StackoperatesasPushandpopwhileQueueoperatesasEnqueueand
00

dequeuer.
nb

Variants
bd

StackdoesnothavevariantswhileQueuehasvariantslikeacircular
queue,Priorityqueue,doublyendedQueue.
n

Implementation
bd

The stack is simpler while Queue is comparatively complex.



dn

25.WhatisthedifferencebetweentheSinglyLinked
nb

co

ListandDoublyLinkedListdatastructure?
l.

Thisisatraditionalinterviewquestiononthedatastructure.Themajordifference
ai

betweenthesinglylinkedlistandthedoublylinkedlististheabilitytotraverse.
gm

Youcannottraversebackinasinglylinkedlistbecauseinitanodeonlypoints
towardsthenextnodeandthereisnopointertothepreviousnode.
0@

On the other hand, the doubly linked list allows you to navigate in both directions in any linked list
because it maintains two pointers towards the next and previous node.

00
bd
dn
nb

You might also like