Interview Questions Part 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 123
At a glance
Powered by AI
Some of the key takeaways from the document are principles of OOP, method overloading vs overriding, abstraction, encapsulation etc.

The main principles of OOP are encapsulation, inheritance, polymorphism and abstraction.

OOP languages support inheritance and polymorphism while object based languages do not support inheritance.

A. Java Interview Questions 22. Explain the concept of Inheritance?

23. Which class in Java is superclass of every


1. What is the difference between JDK and JRE? other class?
2. What is Java Virtual Machine (JVM)? 24. Why Java does not support multiple
3. What are the different types of memory areas inheritances?
allocated by JVM? 25. In OOPS, what is meant by composition?
4. What is JIT compiler? 26. How aggregation and composition are
5. How Java platform is different from other different concepts?
platforms? 27. Why there are no pointers in Java?
6. Why people say that Java is 'write once and run 28. If there are no pointers in Java, then why do
anywhere' language? we get NullPointerException?
7. How does ClassLoader work in Java? 29. What is the purpose of ‘super’ keyword in
8. Do you think ‘main’ used for main method is a java?
keyword in Java? 30. Is it possible to use this() and super() both in
9. Can we write main method as public void static same constructor?
instead of public static void? 31. What is the meaning of object cloning in Java?
10. In Java, if we do not specify any value for local Static
variables, then what will be the default value of 32. In Java, why do we use static variable?
the local variables? 33. Why it is not a good practice to create static
11. Let say, we run a java class without passing variables in Java?
any arguments. What will be the value of String 34. What is the purpose of static method in Java?
array of arguments in Main method? 35. Why do we mark main method as static in
12. What is the difference between byte and char Java?
data types in Java? 36. In what scenario do we use a static block?
OOPS 37. Is it possible to execute a program without
13. What are the main principles of Object defining a main() method?
Oriented Programming? 38. What happens when static modifier is not
14. What is the difference between Object mentioned in the signature of main method?
Oriented Programming 39. What is the difference between static method
language and Object Based Programming and instance method in Java?
language? Method Overloading and Overriding
15. In Java what is the default value of an object 40. What is the other name of Method
reference defined as an instance variable in an Overloading?
Object? 41. How will you implement method overloading
16. Why do we need constructor in Java? in Java?
17. Why do we need default constructor in Java 42. What kinds of argument variations are
classes? allowed in Method Overloading?
18. What is the value returned by Constructor in 43. Why it is not possible to do method
Java? overloading by changing return type of method in
19. Can we inherit a Constructor? java?
20. Why constructors cannot be final, static, or 44. Is it allowed to overload main() method in
abstract in Java? Java?
Inheritance 45. How do we implement method overriding in
21. What is the purpose of ‘this’ keyword in java? Java?
1
46. Are we allowed to override a static method in 70. How can you change the value of a final
Java? variable in Java?
47. Why Java does not allow overriding a static 71. Can a class be marked final in Java?
method? 72. How can we create a final method in Java?
48. Is it allowed to override an overloaded 73. How can we prohibit inheritance in Java?
method? 74. Why Integer class in final in Java?
49. What is the difference between method 75. What is a blank final variable in Java?
overloading and method overriding in Java? 76. How can we initialize a blank final variable?
50. Does Java allow virtual functions? 77. Is it allowed to declare main method as final?
51. What is meant by covariant return type in Package
Java? 78. What is the purpose of package in Java?
52. What is Runtime Polymorphism? 79. What is java.lang package?
53. Is it possible to achieve Runtime 80. Which is the most important class in Java?
Polymorphism by data members in 81. Is it mandatory to import java.lang package
Java? every time?
54. Explain the difference between static and 82. Can you import same package or class twice
dynamic binding? in your class?
Abstraction 83. What is a static import in Java?
55. What is Abstraction in Object Oriented 84. What is the difference between import static
programming? com.test.Fooclass and import com.test.Fooclass?
56. How is Abstraction different from 85. What is Locale in Java?
Encapsulation? 86. How will you use a specific Locale in Java?
57. What is an abstract class in Java? Serialization
58. Is it allowed to mark a method abstract 87. What is the serialization?
method without marking the class abstract? 88. What is the purpose of serialization?
59. Is it allowed to mark a method abstract as 89. What is Deserialization?
well as final? 90. What is Serialization and Deserialization
60. Can we instantiate an abstract class in Java? conceptually?
61. What is an interface in Java? 91. Why do we mark a data member transient?
62. Is it allowed to mark an interface method as 92. Is it allowed to mark a method as transient?
static? 93. How does marking a field as transient makes
63. Why an Interface cannot be marked as final in it possible to serialize an object?
Java? 94. What is Externalizable interface in Java?
64. What is a marker interface? 95. What is the difference between Serializable
65. What can we use instead of Marker interface? and Externalizable interface?
66. How Annotations are better than Marker 96. What is Reflection in Java?
Interfaces? 97. What are the uses of Reflection in Java?
67. What is the difference between abstract class 98. How can we access private method of a class
and interface in Java? from outside the class?
68. Does Java allow us to use private and 99. How can we create an Object dynamically at
protected modifiers for variables in interfaces? Runtime in Java?
69. How can we cast to an object reference to an Garbage Collection
interface reference? 100. What is Garbage Collection in Java?
Final 101. Why Java provides Garbage Collector?
2
102. What is the purpose of gc() in Java? 128. What is the basic difference between a
103. How does Garbage Collection work in Java? String and StringBuffer object?
104. When does an object become eligible for 129. How will you create an immutable class in
Garbage Collection in Java? Java?
105. Why do we use finalize() method in Java? 130. What is the use of toString() method in java
106. What are the different types of References ?
in Java? 131. Arrange the three classes String, StringBuffer
107. How can we reference an unreferenced and StringBuilder in the order of efficiency for
object again? String processing operations?
108. What kind of process is the Garbage 132. What is Exception Handling in Java?
collector thread? 133. In Java, what are the differences between a
109. What is the purpose of the Runtime class? Checked and Unchecked?
110. How can we invoke an external process in 134. What is the base class for Error and
Java? Exception classes in Java?
111. What are the uses of Runtime class? 135. What is a finally block in Java?
Inner Classes 136. What is the use of finally block in Java?
112. What is a Nested class? 137. Can we create a finally block without
113. How many types of Nested classes are in creating a catch block?
Java? 138. Do we have to always put a catch block after
114. Why do we use Nested Classes? a try block?
115. What is the difference between a Nested 139. In what scenarios, a finally block will not be
class and an Inner class in Java? executed?
116. What is a Nested interface? 140. Can we re-throw an Exception in Java?
117. How can we access the non-final local 141. What is the difference between throw and
variable, inside a Local Inner class? throws in Java?
118. Can an Interface be defined in a Class? 142. What is the concept of Exception
119. Do we have to explicitly mark a Nested Propagation?
Interface public static? 143. When we override a method in a Child class,
120. Why do we use Static Nested interface in can we throw an additional Exception that is not
Java? thrown by the Parent class method?
String 144. How Multi-threading works in Java?
121. What is the meaning of Immutable in the 145. What are the advantages of Multithreading?
context of String class in Java? 146. What are the disadvantages of
122. Why a String object is considered immutable Multithreading?
in java? 147. What is a Thread in Java?
123. How many objects does following code 148. What is a Thread’s priority and how it is used
create? in scheduling?
124. How many ways are there in Java to create a 149. What are the differences between Pre-
String object? emptive Scheduling Scheduler and Time Slicing
125. How many objects does following code Scheduler?
create? 150. Is it possible to call run() method instead of
126. What is String interning? start() on a thread in Java?
127. Why Java uses String literal concept? 151. How will you make a user thread into
daemon thread if it has already started?
3
152. Can we start a thread two times in Java? 176. What is the difference between Singleton
153. In what scenarios can we interrupt a thread? class and Static class?
154. In Java, is it possible to lock an object for Java Collection
exclusive use by a thread? 177. What is the difference between Collection
155. How notify() method is different from and Collections Framework in Java?
notifyAll() method? 178. What are the main benefits of Collections
Collections Framework in Java?
156. What are the differences between the two 179. What is the root interface of Collection
data structures: a Vector and an ArrayList? hierarchy in Java?
157. What are the differences between Collection 180. What are the main differences between
and Collections in Java? Collection and Collections?
158. In which scenario, LinkedList is better than 181. What are the Thread-safe classes in Java
ArrayList in Java? Collections framework?
159. What are the differences between a List and 182. How will you efficiently remove elements
Set collection in Java? while iterating a Collection?
160. What are the differences between a HashSet 183. How will you convert a List into an array of
and TreeSet collection in Java? integers like- int[]?
161. In Java, how will you decide when to use a 184. How will you convert an array of primitive
List, Set or a Map collection? integers int[] to a List collection?
162. What are the differences between a 185. How will you run a filter on a Collection?
HashMap and a Hashtable in Java? 186. How will you convert a List to a Set?
163. What are the differences between a 187. How will you remove duplicate elements
HashMap and a TreeMap? from an ArrayList?
164. What are the differences between 188. How can you maintain a Collection with
Comparable and Comparator? elements in Sorted order?
165. In Java, what is the purpose of Properties 189. What is the difference between
file? Collections.emptyList() and creating new instance
166. What is the reason for overriding equals() of Collection?
method? 190. How will you copy elements from a Source
167. How does hashCode() method work in Java? List to another list?
168. Is it a good idea to use Generics in 191. What are the Java Collection classes that
collections? implement List interface?
Mixed Questions 192. What are the Java Collection classes that
169. What are Wrapper classes in Java? implement Set interface?
170. What is the purpose of native method in 193. What is the difference between an Iterator
Java? and ListIterator in Java?
171. What is System class? 194. What is the difference between Iterator and
172. What is System, out and println in Enumeration?
System.out.println method call? 195. What is the difference between an ArrayList
173. What is the other name of Shallow Copy in and a LinkedList data structure?
Java? 196. What is the difference between a Set and a
174. What is the difference between Shallow Map in Java?
Copy and Deep Copy in Java? 197. What is the use of a Dictionary class?
175. What is a Singleton class?
4
198. What is the default size of load factor in a 220. What is CopyOnWriteArrayList? How it is
HashMap collection in Java? different from ArrayList in Java?
199. What is the significance of load factor in a 221. How remove() method is implemented in a
HashMap in Java? HashMap?
200. What are the major differences between a 222. What is BlockingQueue in Java Collections?
HashSet and a HashMap? 223. How is TreeMap class implemented in Java?
201. What are the similarities between a HashSet 224. What is the difference between Fail-fast and
and a HashMap in Java? Fail-safe iterator in Java?
202. What is the reason for overriding equals() 225. How does ConcurrentHashMap work in
method? Java?
203. How can we synchronize the elements of a 226. What is the importance of hashCode() and
List, a Set or a Map? equals() methods?
204. What is Hash Collision? How Java handles 227. What is the contract of hashCode() and
hash-collision in HashMap? equals() methods in Java?
205. What are the Hash Collision resolution 228. What is an EnumSet in Java?
techniques? 229. What are the main Concurrent Collection
206. What is the difference between Queue and classes in Java?
Stack data structures? 230. How will you convert a Collection to
207. What is an Iterator in Java? SynchronizedCollection in Java?
208. What is the difference between Iterator and 231. How IdentityHashMap is different from a
Enumeration in Java? regular Map in Java?
209. What is the design pattern used in the 232. What is the main use of IdentityHashMap?
implementation of Enumeration in Java? 233. How can we improve the performance of
210. Which methods do we need to override to IdentityHashMap?
use an object as key in a HashMap? 234. Is IdentityHashMap thread-safe?
211. How will you reverse a List in Java? 235. What is a WeakHashMap in Java?
212. How will you convert an array of String 236. How can you make a Collection class read
objects into a List? Only in Java?
213. What is the difference between peek(), poll() 237. When is UnsupportedOperationException
and remove() methods of Queue interface in thrown in Java?
java? 238. Let say there is a Customer class. We add
214. What is the difference between Array and objects of Customer class to an ArrayList. How
ArrayList in Java? can we sort the Customer objects in ArrayList by
215. How will you insert, delete and retrieve using customer firstName attribute of Customer
elements from a HashMap collection in Java? class?
216. What are the main differences between 239. What is the difference between
HashMap and ConcurrentHashMap in Java? Synchronized Collection and Concurrent
217. What is the increasing order of performance Collection?
for following collection classes in Java? 240. What is the scenario to use
218. Why does Map interface not extend ConcurrentHashMap in Java?
Collection interface in Java? 241. How will you create an empty Map in Java?
219. What are the different ways to iterate 242. What is the difference between remove()
elements of a list in Java? method of Collection and
remove() method of Iterator?
5
243. Between an Array and ArrayList, which one 265. What is a Thread in Java?
is the preferred collection for storing objects? 266. What is the priority of a Thread and how it is
244. Is it possible to replace Hashtable with used in scheduling?
ConcurrentHashMap in Java? 267. What is the default priority of a thread in
245. How CopyOnWriteArrayList class is different Java?
from ArrayList and 268. What are the three different priorities that
Vector classes? can be set on a Thread in Java?
246. Why ListIterator has add() method but 269. What is the purpose of join() method in
Iterator does not have? Thread class?
247. Why do we sometime get 270. What is the fundamental difference between
ConcurrentModificationException during wait() and sleep() methods?
iteration? 271. Is it possible to call run() method instead of
248. How will you convert a Map to a List in Java? start() on a thread in Java?
249. How can we create a Map with reverse view 272. What is a daemon thread in Java?
and lookup in Java? 273. How can we make a regular thread Daemon
250. How will you create a shallow copy of a thread in Java?
Map? 274. How will you make a user thread into
251. Why we cannot create a generic array in daemon thread if it has already started?
Java? 275. Can we start a thread two times in Java?
252. What is a PriorityQueue in Java? 276. What is a Shutdown hook in Java?
253. What are the important points to remember 277. What is synchronization in Java?
while using Java Collections Framework? 278. What is the purpose of Synchronized block in
254. How can we pass a Collection as an Java?
argument to a method and ensure that method 279. What is static synchronization?
will not be able to modify it? 280. What is a Deadlock situation?
255. Can you explain how HashMap works in 281. What is the meaning of concurrency?
Java? 282. What is the main difference between
256. Can you explain how HashSet is process and thread?
implemented in Java? 283. What is a process and thread in the context
257. What is a NavigableMap in Java? of Java?
258. What is the difference between 284. What is a Scheduler?
descendingKeySet() and descendingMap() 285. What is the minimum number of Threads in
methods of NavigableMap? a Java program?
259. What is the advantage of NavigableMap 286. What are the properties of a Java thread?
over Map? 287. What are the different states of a Thread in
260. What is the difference between headMap(), Java?
tailMap() and subMap() methods of 288. How will you set the priority of a thread in
NavigableMap? Java?
261. How will you sort objects by Natural order in 289. What is the purpose of Thread Groups in
a Java List? Java?
262. How can we get a Stream from a List in Java? 290. Why we should not stop a thread by calling
263. Can we get a Map from a Stream in Java? its stop() method?
264. What are the popular implementations of 291. How will you create a Thread in Java?
Deque in Java?
6
292. How can we stop a thread in the middle of 318. How JVM determines which thread should
execution in Java? wake up on notify()?
293. How do you access the current thread in a 319. Check if following code is thread-safe for
Java program? retrieving an integer value from a Queue?
294. What is Busy waiting in Multi-threading? 320. How can we check if a thread has a monitor
295. How can we prevent busy waiting in Java? lock on a given object?
296. Can we use Thread.sleep() method for real- 321. What is the use of yield() method in Thread
time processing in Java? class?
297. Can we wake up a thread that has been put 322. What is an important point to consider while
to sleep by using Thread.sleep() method? passing an object from one thread to another
298. What are the two ways to check if a Thread thread?
has been interrupted? 323. What are the rules for creating Immutable
299. How can we make sure that Parent thread Objects?
waits for termination of Child thread? 324. What is the use of ThreadLocal class?
300. How will you handle InterruptedException in 325. What are the scenarios suitable for using
Java? ThreadLocal class?
301. Which intrinsic lock is acquired by a 326. How will you improve the performance of an
synchronized method in Java? application by multithreading?
302. Can we mark a constructor as synchronized 327. What is scalability in a Software program?
in Java? 328. How will you calculate the maximum speed
303. Can we use primitive values for intrinsic up of an application by using multiple processors?
locks? 329. What is Lock contention in multi-threading?
304. Do we have re-entrant property in intrinsic 330. What are the techniques to reduce Lock
locks? contention?
305. What is an atomic operation? 331. What technique can be used in following
306. Can we consider the statement i++ as an code to reduce Lock contention?
atomic operation in Java? 332. What is Lock splitting technique?
307. What are the Atomic operations in Java? 333. Which technique is used in ReadWriteLock
308. Can you check if following code is thread- class for reducing Lock contention?
safe? 334. What is Lock striping?
309. What are the minimum requirements for a 335. What is a CAS operation?
Deadlock situation in a program? 336. Which Java classes use CAS operation?
310. How can we prevent a Deadlock? 337. Is it always possible to improve performance
311. How can we detect a Deadlock situation? by object pooling in a multi-threading
312. What is a Livelock? application?
313. What is Thread starvation? 338. How can techniques used for performance
314. How can a synchronized block cause Thread improvement in a single thread application may
starvation in Java? degrade the performance in a multi-threading
315. What is a Race condition? application?
316. What is a Fair lock in multi-threading? 339. What is the relation between Executor and
317. Which two methods of Object class can be ExecutorService interface?
used to implement a Producer Consumer 340. What will happen on calling submit()
scenario? method of an ExecutorService instance whose
queue is already full?
7
341. What is a ScheduledExecutorService? 364. Why did Oracle release a new version of Java
342. How will you create a Thread pool in Java? like Java 8?
343. What is the main difference between 365. What are the advantages of a lambda
Runnable and Callable interface? expression?
344. What are the uses of Future interface in 366. What is a Functional interface in Java 8?
Java? 367. What is a Single Abstract Method (SAM)
345. What is the difference in concurrency in interface in Java 8?
HashMap and in Hashtable? 368. How can we define a Functional interface in
346. How will you create synchronized instance of Java 8?
List or Map Collection? 369. Why do we need Functional interface in
347. What is a Semaphore in Java? Java?
348. What is a CountDownLatch in Java? 370. Is it mandatory to use @FunctionalInterface
349. What is the difference between annotation to define a Functional interface in
CountDownLatch and CyclicBarrier? Java 8?
350. What are the scenarios suitable for using 371. What are the differences between Collection
Fork/Join framework? and Stream API in Java 8?
351. What is the difference between 372. What are the main uses of Stream API in
RecursiveTask and RecursiveAction class? Java 8?
352. In Java 8, can we process stream operations 373. What are the differences between
with a Thread pool? Intermediate and Terminal Operations in Java 8
353. What are the scenarios to use parallel Streams?
stream in Java 8? 374. What is a Spliterator in Java 8?
354. How Stack and Heap work in Java multi- 375. What are the differences between Iterator
threading environment? and Spliterator in Java 8?
355. How can we take Thread dump in Java? 376. What is Type Inference in Java 8?
356. Which parameter can be used to control 377. Does Java 7 support Type Inference?
stack size of a thread in Java? 378. How does Internal Iteration work in Java 8?
357. There are two threads T1 and T2? How will 379. What are the main differences between
you ensure that these threads run in sequence Internal and External Iterator?
T1, T2 in Java? 380. What are the main advantages of Internal
Iterator over External Iterator in Java 8?
B. Java 8 Interview Questions 381. What are the applications in which we
should use Internal Iteration?
358. What are the new features released in Java 382. What is the main disadvantage of Internal
8? Iteration over External Iteration?
359. What are the main benefits of new features 383. Can we provide implementation of a method
introduced in Java 8? in a Java Interface?
360. What is a Lambda expression in Java 8? 384. What is a Default Method in an Interface?
361. What are the three main parts of a Lambda 385. Why do we need Default method in a Java 8
expression in Java? Interface?
362. What is the data type of a Lambda 386. What is the purpose of a Static method in an
expression? Interface in Java 8?
363. What is the meaning of following lambda 387. What are the core ideas behind the
expression? Date/Time API of Java 8?
8
388. What are the advantages of new Date and 406. How can we analyze the dependencies in
Time API in Java 8 over old Date API? Java classes and packages?
389. What are the main differences between 407. What are the new JVM arguments
legacy Date/Time API in Java and Date/Time API introduced by Java 8?
of Java 8? 408. What are the popular annotations
390. How can we get duration between two dates introduced in Java 8?
or time in Java 8? 409. What is a StringJoiner in Java 8?
391. What is the new method family introduced 410. What is the type of a Lambda expression in
in Java 8 for processing of Arrays on multi core Java 8?
machines? 411. What is the target type of a lambda
392. How does Java 8 solve Diamond problem of expression?
Multiple Inheritance? 412. What are the main differences between an
393. What are the differences between Predicate, interface with default method and an abstract
Supplier and Consumer in Java 8? class in Java 8?
394. Is it possible to have default method
definition in an interface without marking it with
default keyword? Java Tricky Questions
395. Can we create a class that implements two
Interfaces with default methods of same name 413. Is there any difference between a = a + b and
and signature? a += b expressions?
396. How Java 8 supports Multiple Inheritance? 414. What does the expression 1.0 / 0.0 return?
397. In case we create a class that extends a base Will there be any compilation error?
class and implements an interface. If both base 415. Can we use multiple main methods in
class and interface have a default method with multiple classes?
same name and arguments, then which definition 416. Does Java allow you to override a private or
will be picked by JVM? static method?
398. If we create same method and define it in a 417. What happens when you put a key object in
class, in its parent class and in an interface a HashMap that is already present?
implemented by the class, then definition will be 418. How can you make sure that N threads can
invoked if we access it using the reference of access N resources without deadlock?
Interface and the object of class? 419. How can you determine if JVM is 32-bit or
399. Can we access a static method of an 64-bit from Java Program?
interface by using reference of the interface? 420. What is the right data type to represent
400. How can you get the name of Parameter in Money (like Dollar/Pound) in Java?
Java by using reflection? 421. How can you do multiple inheritances in
401. What is Optional in Java 8? Java?
402. What are the uses of Optional? 422. Is ++ operation thread-safe in Java?
403. Which method in Optional provides the 423. How can you access a non-static variable
fallback mechanism in case of null value? from the static context?
404. How can we get current time by using 424. Let say there is a method that throws
Date/Time API of Java 8? NullPointerException in the superclass. Can we
405. Is it possible to define a static method in an override it with a method that throws
Interface? RuntimeException?
425. How can you mark an array volatile in Java?
9
426. What is a thread local variable in Java? 448. You have a character array and a String.
427. What is the difference between sleep() and Which one is more secure to store sensitive data
wait() methods in Java? (like password, date of birth, etc.)?
428. Can you create an Immutable object that 449. Why do you use volatile keyword in Java?
contains a mutable object? 450. What is the difference between poll() and
429. How can you convert an Array of bytes to remove() methods of Queue in Java?
String? 451. Can you catch an exception thrown by
430. What is difference between CyclicBarrier another thread in Java?
and CountDownLatch class? 452. How do you decide which type of Inner Class
431. What is the difference between StringBuffer – Static or Non-Static to use in Java?
and StringBuilder? 453. What are the different types of Classloaders
432. Which class contains clone method? in Java?
Cloneable or Object class? 454. What are the situations in which you choose
433. How will you take thread dump in Java? HashSet or TreeSet?
434. Can you cast an int variable into a byte 455. What is the use of method references in
variable? What happens if the value of int is Java?
larger than byte? 456. Do you think Java Enums are more powerful
435. In Java, can we store a double value in a long than integer constants?
variable without explicit casting? 457. Why do we use static initializers in Java?
436. What will this return 5*0.1 == 0.5? true or 458. Your client is complaining that your code is
false? throwing NoClassDefFoundError or
437. Out of an int and Integer, which one takes NoSuchMethodError, even though you are able
more memory? to compile your code without error and method
438. Can we use String in the switch case exists in your code. What could be the reason
statement in Java? behind this?
439. Can we use multiple main methods in same 459. How can you check if a String is a number by
class? using regular expression?
440. When creating an abstract class, is it a good 460. What is the difference between the
idea to call abstract methods inside its expressions String s = "Temporary" and String s =
constructor? new String("Temporary ")? Which one is better
441. How can you do constructor chaining in and more efficient?
Java? 461. In Java, can two equal objects have the
442. How can we find the memory usage of JVM different hash code?
from Java code? 462. How can we print an Array in Java?
443. What is the difference between x == y and 463. Is it ok to use random numbers in the
x.equals(y) expressions in Java? implementation of hashcode() method in Java?
444. How can you guarantee that the garbage 464. Between two types of dependency
collection takes place? injections, constructor injection and setter
445. What is the relation between x.hashCode() dependency injection, which one is better?
method and x.equals(y) method of Object class? 465. What is the difference between DOM and
446. What is a compile time constant in Java? SAX parser in Java?
447. Explain the difference between fail-fast and 466. Between Enumeration and Iterator, which
fail-safe iterators? one has better performance in Java?

10
467. What is the difference between pass by 489. Why Java does not support operator
reference and pass by value? overloading?
468. What are the different ways to sort a 490. Why String class is Immutable or Final in
collection in Java? Java?
469. Why Collection interface doesn’t extend 491. What is the difference between
Cloneable and Serializable interfaces? sendRedirect and forward methods?
470. What is the difference between a process 492. How do you fix your Serializable class, if it
and a thread in Java? contains a member that is not serializable?
471. What are the benefits of using an unordered 493. What is the use of run time polymorphism in
array over an ordered array? Java?
472. Between HashSet and TreeSet collections in 494. What are the rules of method overloading
Java, which one is better? and method overriding in Java?
473. When does JVM call the finalize() method? 495. What is the difference between a class and
474. When would you use Serial Garabage an object in Java?
collector or Throughput Garbage collector in 496. Can we create an abstract class that extends
Java? another abstract class?
475. In Java, if you set an object reference to null, 497. Why do you use Upcasting or Downcasting in
will the Garbage Collector immediately free the Java?
memory held by that object? 498. What is the reason to organize classes and
476. How can you make an Object eligible for interfaces in a package in Java?
Garbage collection in Java? 499. What is information hiding in Java?
477. When do you use Exception or Error in Java? 500. Why does Java provide default constructor?
What is the difference between these two? 501. What is the difference between super and
478. What is the advantage of this keywords in Java?
PreparedStatement over Statement class in Java? 502. What is the advantage of using Unicode
479. In Java, what is the difference between characters in Java?
throw and throws keywords? 503. Can you override an overloaded method in
480. What happens to the Exception object after Java?
the exception handling is done? 504. How can we change the heap size of a JVM?
481. How do you find which client machine is 505. Why should you define a default constructor
sending request to your servlet in Java? in Java?
482. What is the difference between a Cookie and 506. How will you make an Object Immutable in
a Session object in Java? Java?
483. Which protocol does Browser and Servlet 507. How can you prevent SQL Injection in Java
use to communicate with each other? Code?
484. What is HTTP Tunneling? 508. Which two methods should be always
485. Why do we use JSP instead of Servlet in implemented by HashMap key Object?
Java? 509. Why an Object used as Key in HashMap
486. Is empty ‘.java’ file name a valid source file should be Immutable?
name in Java? 510. How can we share an object between
487. How do you implement Servlet Chaining in multiple threads?
Java? 511. How can you determine if your program has
488. Can you instantiate this class? a deadlock?

11
533. What are the examples of Command design
Java Design Patterns pattern in JDK?
512. When will you use Strategy Design Pattern in 534. What are the examples of Interpreter design
Java? pattern in JDK?
513. What is Observer design pattern? 535. What are the examples of Mediator design
514. What are the examples of Observer design pattern in JDK?
pattern in JDK? 536. What are the examples of Strategy design
515. How Strategy design pattern is different pattern in JDK?
from State design pattern in Java? 537. What are the examples of Visitor design
516. Can you explain Decorator design pattern pattern in JDK?
with an example in Java? 538. How Decorator design pattern is different
517. What is a good scenario for using Composite from Proxy pattern?
design Pattern in Java? 539. What are the different scenarios to use
518. Have you used Singleton design pattern in Setter and Constructor based injection in
your Java project? Dependency Injection (DI) design pattern?
519. What are the main uses of Singleton design 540. What are the different scenarios for using
pattern in Java project? Proxy design pattern?
520. Why java.lang.Runtime is a Singleton in 541. What is the main difference between
Java? Adapter and Proxy design pattern?
521. What is the way to implement a thread-safe 542. When will you use Adapter design pattern in
Singleton design pattern in Java? Java?
522. What are the examples of Singleton design 543. What are the examples of Adapter design
pattern in JDK? pattern in JDK?
523. What is Template Method design pattern in 544. What is the difference between Factory and
Java? Abstract Factory design
524. What are the examples of Template method pattern?
design pattern in JDK? 545. What is Open/closed design principle in
525. Can you tell some examples of Factory Software engineering?
Method design pattern implementation in Java? 546. What is SOLID design principle?
526. What is the benefit we get by using static 547. What is Builder design pattern?
factory method to create object? 548. What are the different categories of Design
527. What are the examples of Builder design Patterns used in Object
pattern in JDK? Oriented Design?
528. What are the examples of Abstract Factory 549. What is the design pattern suitable to access
design pattern in JDK? elements of a Collection?
529. What are the examples of Decorator design 550. How can we implement Producer Consumer
pattern in JDK? design pattern in Java?
530. What are the examples of Proxy design 551. What design pattern is suitable to add new
pattern in JDK? features to an existing object?
531. What are the examples of Chain of 552. Which design pattern can be used when to
Responsibility design pattern in JDK? decouple abstraction from the implementation?
532. What are the main uses of Command design 553. Which is the design pattern used in Android
pattern? applications?

12
554. How can we prevent users from creating 579. What is the default scope of a bean?
more than one instance of singleton object by 580. Are Spring beans thread safe?
using clone() method? 581. What are the other scopes available?
555. What is the use of Interceptor design 582. How is Spring’s singleton bean different
pattern? from Gang of Four Singleton Pattern?
556. What are the Architectural patterns that you 583. What are the different types of dependency
have used? injections?
557. What are the popular uses of Façade design 584. What is setter injection?
pattern? 585. What is constructor injection?
558. What is the difference between Builder 586. How do you choose between setter and
design pattern and Factory design pattern? constructor injections?
559. What is Memento design pattern? 587. What are the different options available to
560. What is an AntiPattern? create Application Contexts for Spring?
561. What is a Data Access Object (DAO) design 588. What is the difference between XML and
pattern? Java Configurations for Spring?
589. How do you choose between XML and Java
Spring Interview Questions Configurations for Spring?
590. How does Spring do Autowiring?
562. What is Loose Coupling? 591. What are the different kinds of matching
563. What is a Dependency? used by Spring for Autowiring?
564. What is IOC (Inversion of Control)? 592. How do you debug problems with Spring
565. What is Dependency Injection? Framework?
566. Can you give few examples of Dependency 593. How do you solve
Injection? NoUniqueBeanDefinitionException?
567. What is Auto Wiring? 594. How do you solve
568. What are the important roles of an IOC NoSuchBeanDefinitionException?
Container? 595. What is @Primary?
569. What are Bean Factory and Application 596. What is @Qualifier?
Context? 597. What is CDI (Contexts and Dependency
570. Can you compare Bean Factory with Injection)?
Application Context? 598. Does Spring Support CDI?
571. How do you create an application context 599. Would you recommed to use CDI or Spring
with Spring? Annotations?
572. How does Spring know where to search for 600. What are the major features in different
Components or Beans? versions of Spring?
573. What is a Component Scan? 601. What are new features in Spring Framework
574. How do you define a component scan in 4.0?
XML and Java Configurations? 602. What are new features in Spring Framework
575. How is it done with Spring Boot? 5.0?
576. What does @Component signify? 603. What are important Spring Modules?
577. What does @Autowired signify? 604. What are important Spring Projects?
578. What’s the difference Between @Controller, 605. What is the simplest way of ensuring that we
@Component, @Repository, and @Service are using single version of all Spring related
Annotations in Spring? dependencies?
13
606. Name some of the design patterns used in 635. Compare Spring Boot vs Spring?
Spring Framework? Compare Spring Boot vs Spring MVC?
607. What do you think about Spring Framework? 636. What is the importance of
608. Why is Spring Popular? @SpringBootApplication?
609. Can you give a big picture of the Spring 637. What is Auto Configuration?
Framework? 638. How can we find more information about
Auto Configuration?
Spring MVC 639. What is an embedded server? Why is it
important?
610. What is Model 1 architecture? 640. What is the default embedded server with
611. What is Model 2 architecture? Spring Boot?
612. What is Model 2 Front Controller 641. What are the other embedded servers
architecture? supported by Spring Boot?
613. Can you show an example controller method 642. What are Starter Projects?
in Spring MVC? 643. Can you give examples of important starter
614. Can you explain a simple flow in Spring projects?
MVC? 644. What is Starter Parent?
615. What is a ViewResolver? 645. What are the different things that are
616. What is Model? defined in Starter Parent?
617. What is ModelAndView? 646. How does Spring Boot enforce common
618. What is a RequestMapping? dependency management for all its Starter
619. What is Dispatcher Servlet? projects?
620. How do you set up Dispatcher Servlet? 647. What is Spring Initializr?
621. What is a form backing object? 648. What is application.properties?
622. How is validation done using Spring MVC? 649. What are some of the important things that
623. What is BindingResult? can customized in application.properties?
624. How do you map validation results to your 650. How do you externalize configuration using
view? Spring Boot?
625. What are Spring Form Tags? 651. How can you add custom application
626. What is a Path Variable? properties using Spring Boot?
627. What is a Model Attribute? 652. What is @ConfigurationProperties?
628. What is a Session Attribute? 653. What is a profile?
629. What is a init binder? 654. How do you define beans for a specific
630. How do you set default date format with profile?
Spring? 655. How do you create application configuration
631. Why is Spring MVC so popular? for a specific profile?
656. How do you have different configuration for
Spring Boot different environments?
657. What is Spring Boot Actuator?
632. What is Spring Boot? 658. How do you monitor web services using
633. What are the important Goals of Spring Spring Boot Actuator?
Boot? 659. How do you find more information about
634. What are the important Features of Spring your application envrionment using Spring Boot?
Boot? 660. What is a CommandLineRunner?
14
29) What are embedded containers support by
1) Explain the term ‘Spring Boot’. Spring
2) Mention some advantages of Spring Boot 30) Explain thymeleaf in Spring Boot
3) How to create a Spring Boot application using 31) What are the Spring Boot properties?
Spring Initializer? 32) What is the main difference between JPA and
4) Name the features of using Spring Boot Hibernate?
5) Explain different phases of RAD model. 33) What is a shutdown in the actuator?
6) What is RAD model? 34) Is it possible to replace or override the
7) What are the commands to run and stop Embedded Tomcat server in Spring Boot?
Spring Boot executable jar file? 35) Can you disable the default web server in the
8) How can you change JDK version in Spring Spring Boot application?
Boot? 36) How do you Add, Filter to an application?
9) What is the process that you need to follow to 37) What are Spring Boot Starter Projects?
run Spring Boot application on the custom port? 38) What is @pathVariable?
10) What is Spring Boot starter? How is it useful? 39) What is Swagger2?
11) Can you use Spring Boot with applications 40) What are different environments for
which are not using Spring? enterprise application development?
12) What is the name of the configuration file 41) What are the major differences between
which you can use in Spring Boot? RequestMapping and GetMapping?
13) What is DevTools in Spring Boot? 42) How can you define properties in Spring
14) What are the important features of Reactjs? Boot?
15) What are the essential components of Spring 43) How to create a Spring Boot project using
Boot Maven?
16) How are properties defined? Where? 44) What is the use of profiles in Spring Boot?
17) What is spring-boot-starter-parent? 45) How to change tomcat HTTP port?
18) How to enable HTTP/2 supports in Spring 46) What is LiveReload in Spring Boot?
Boot? 47) What are the major benefits of spring
19) What is a Spring Boot Actuator? Externalized Configuration?
20) What is the command to run Spring Boot 48) What do you mean by hot-swapping in Spring
application to custom port? Boot?
21) How can you access a value defined in the 49) Explain Auto-Configuration in Spring Boot.
application? What is properties file in Spring 50) What is the meaning of Aspect-Oriented
Boot? Programming (AOP)?
22) What is the primary difference between 51) How to enable logging in Spring Boot?
Spring and Spring Boot? 52) Explain overriding default properties in Spring
23) Explain Spring Boot Admin Boot application.
24) How can you connect Spring Boot to the 53) Explain Docker in Spring Boot.
database using JPA? 54) Define ELK stack.
25) Explain @RestController annotation in Spring 55) How to handle exception in Spring Boot.
Boot? 56) Explain caching.
26) Define the term Spring Initializer 57) What is Cross-Site Request Forgery attack?
27) Explain Spring CLI 58) Define apache freemarker.
28) Where can you define properties in Spring 59) What is mean by spring batch?
Boot application? 60) Explain Apache Kafka.
15
61) Explain CORS in Spring Boot? 679. How do you define transaction management
62) Explain different types of dependency for Spring – Hibernate integration?
injection.
63) What are the advantages of micro service?
64) What is the default package in Spring Boot?
65) Explain the difference between an embedded Spring Data
container and a WAR.
66) Explain Spring MVC. 680. What is Spring Data?
67) What is the use of <set> tag? 681. What is the need for Spring Data?
68) What do you mean by aspect? 682. What is Spring Data JPA?
69) What is join point in Spring Boot? 683. What is a CrudRepository?
70) How can you set active profile in Spring Boot? 684. What is a PagingAndSortingRepository?
71) Is excluding package without using the
basePackages filter is possible? How? Unit Testing
72) List out benefits of using the JavaConfig
method. 685. How does Spring Framework Make Unit
73) Explain steps to deploy an application on Testing Easy?
virtual machine. 686. What is Mockito?
74) List out some of the Spring Boot Starters. 687. What is your favorite mocking framework?
Database Connectivity - JDBC, Spring JDBC & JPA 688. How do you do mock data with Mockito?
689. What are the different mocking annotations
661. What is Spring JDBC? How is different from that you worked with?
JDBC? 690. What is MockMvc?
662. What is a JdbcTemplate? 691. What is @WebMvcTest?
663. What is a RowMapper? 692. What is @MockBean?
664. What is JPA? 693. How do you write a unit test with
665. What is Hibernate? MockMVC?
666. How do you define an entity in JPA? 694. What is JSONAssert?
What is an Entity Manager? 695. How do you write an integration test with
667. What is a Persistence Context? Spring Boot?
668. How do you map relationships in JPA? 696. What is @SpringBootTest?
669. What are the different types of relationships 697. What is @LocalServerPort?
in JPA? 698. What is TestRestTemplate?
670. How do you define One to One Mapping in
JPA? AOP
671. How do you define One to Many Mapping in
JPA? 699. What are cross cutting concerns?
672. How do you define Many to Many Mapping 700. How do you implement cross cutting
in JPA? concerns in a web application?
673. How do you define a datasource in a Spring 701. If you would want to log every request to a
Context? web application, what are the options you can
674. What is the use of persistence.xml think of?
678. How do you configure Entity Manager 702. If you would want to track performance of
Factory and Transaction Manager? every request, what options can you think of?
16
703. What is an Aspect and Pointcut in AOP? 26. What do you mean by end-to-end
704. What are the different types of AOP advices? microservices testing?
705. What is weaving? 27. Explain the term Eureka in Microservices.
706. Compare Spring AOP vs AspectJ? 28. Explain the way to implement service
discovery in microservices architecture.
Microservices Interview Questions 29. Explain the importance of reports and
1. Write main features of Microservices. dashboards in microservices.
2. Write main components of Microservices. 30. What are Reactive Extensions in
3. What are the benefits and drawbacks of Microservices?
Microservices? 31. Explain type of tests mostly used in
4. Name three common tools mostly used for Microservices.
microservices. 32. What do you mean by Mike Cohn’s Test
5. Explain the working of Microservice Pyramid?
Architecture. 33. Explain Container in Microservices.
6. Write difference between Monolithic, SOA and 34. What is the main role of docker in
Microservices Architecture. microservices?
7. Explain spring cloud and spring boot.
8. What is the role of actuator in spring boot? GIT
9. Explain how you can override the default 1. How can we see n most recent commits in GIT?
properties of Spring boot projects. 2. How can we know if a branch is already
10. What issues are generally solved by spring merged into master in GIT?
clouds? 3. What is the purpose of git stash drop?
11. What do you mean by Cohesion and 4. What is the HEAD in GIT?
Coupling? 5. What is the most popular branching strategy in
12. What do you mean by Bounded Context? GIT?
13. Write the fundamental characteristics of 6. What is SubGit?
Microservice Design. 7. What is the use of git instaweb?
14. What are the challenges that one has to face 8. What are git hooks?
while using Microservices? 9. What is GIT?
15. Explain PACT in microservices. 10. What is a repository in GIT?
16. Explain how independent microservices 11. What are the main benefits of GIT?
communicate with each other. 12. What are the disadvantages of GIT?
17. What do you mean by client certificates? 13. What are the main differences between GIT
18. Explain CDC. and SVN?
19. Name some famous companies that use 14. How will you start GIT for your project?
Microservice architecture. 15. What is git clone in GIT?
20. What do you mean by Semantic Monitoring? 16. How will you create a repository in GIT?
21. Explain continuous monitoring. 17. What are the different ways to start work in
22. What do you mean by Domain driven design? GIT?
23. Explain OAuth. 18. GIT is written in which language?
24. What do you mean by Distributed 19. What does ‘git pull’ command in GIT do
Transaction? internally?
25. Explain Idempotence and its usage. 20. What does ‘git push’ command in GIT do
internally?
17
21. What is git stash? 53. Why do we need git add command in GIT?
22. What is the meaning of ‘stage’ in GIT? 54. Why do we use git reset command?
23. What is the purpose of git config command? 55. What does a commit object contain?
24. How can we see the configuration settings of 56. How can we convert git log messages to a
GIT installation? different format?
25. How will you write a message with commit 57. What are the programming languages in
command in GIT? which git hooks can be written?
26. What is stored inside a commit object in GIT? 58. What is a commit message in GIT?
27. How many heads can you create in a GIT 59. How GIT protects the code in a repository?
repository? 60. How GIT provides flexibility in version
28. Why do we create branches in GIT? control?
29. What are the different kinds of branches that 61. How can we change a commit message in
can be created in GIT? GIT?
30. How will you create a new branch in GIT? 62. Why is it advisable to create an additional
31. How will you add a new feature to the main commit instead of amending an existing commit?
branch? 63. What is a bare repository in GIT?
32. What is a pull request in GIT? 64. How do we put a local repository on GitHub
33. What is merge conflict in GIT? server?
34. How can we resolve a merge conflict in GIT? 65. How will you delete a branch in GIT?
35. What command will you use to delete a 66. How can we set up a Git repository to run
branch? code sanity checks and UAT tests just before a
36. What command will you use to delete a commit?
branch that has unmerged changes? 67. How can we revert a commit that was pushed
37. What is the alternative command to merging earlier and is public now?
in GIT? 68. In GIT, how will you compress last n commits
38. What is Rebasing in GIT? into a single commit?
39. What is the ‘Golden Rule of Rebasing’ in GIT? 69. How will you switch from one branch to a
40. Why do we use Interactive Rebasing in place new branch in GIT?
of Auto Rebasing? 70. How can we clean unwanted files from our
41. What is the command for Rebasing in Git? working directory in GIT?
42. What is the main difference between git clone 71. What is the purpose of git tag command?
and git remote? 72. What is cherry-pick in GIT?
43. What is GIT version control? 73. What is shortlog in GIT?
44. What GUI do you use for working on GIT? 74. How can you find the names of files that were
45. What is the use of git diff command in GIT? changed in a specific commit?
46. What is git rerere? 75. How can we attach an automated script to
47. What are the three most popular version of run on the event of a new commit by push
git diff command? command?
48. What is the use of git status command? 76. What are the differences between pre-
49. What is the main difference between git diff receive, update and post-receive hooks in GIT?
and git status? 77. Do we have to store Scripts for GIT hooks
50. What is the use of git rm command in GIT? within same repository?
51. What is the command to apply a stash? 78. How can we determine the commit that is the
52. Why do we use git log command? source of a bug in GIT?
18
79. How can we see differences between two 5 What are the key components of Angular?
commits in GIT? 6 What are directives?
80. What are the different ways to identify a 7 What are components?
commit in GIT? 8 What are the differences between
81. When we run git branch <branchname>, how Component and Directive?
does GIT know the SHA-1 of the last commit? 9 What is a template?
82. What are the different types of Tags you can 10 What is a module?
create in GIT? 11 What are lifecycle hooks available?
83. How can we rename a remote repository? 12 What is a data binding?
84. Some people use git checkout and some use 13 What is metadata?
git co for checkout. How is that possible? 14 What is Angular CLI?
85. How can we see the last commit on each of 15 What is the difference between
our branch in GIT? constructor and ngOnInit?
86. Is origin a special branch in GIT? 16 What is a service
87. How can we configure GIT to not ask for 17 What is dependency injection in Angular?
password every time? 18 How is Dependency Hierarchy formed?
88. What are the four major protocols used by 19 What is the purpose of async pipe?
GIT for data transfer? 20 What is the option to choose between
89. What is GIT protocol? inline and external template file?
90. How can we work on a project where we do 21 What is the purpose of *ngFor directive?
not have push access? 22 What is the purpose of ngIf directive?
91. What is git grep? 23 What happens if you use script tag inside
92. How can your reorder commits in GIT? template?
93. How will you split a commit into multiple 24 What is interpolation?
commits? 25 What are template expressions?
94. What is filter-branch in GIT? 26 What are template statements?
95. What are the three main trees maintained by 27 How do you categorize data binding
GIT? types?
96. What are the three main steps of working 28 What are pipes?
GIT? 29 What is a parameterized pipe?
97. What are ours and theirs merge options in 30 How do you chain pipes?
GIT? 31 What is a custom pipe?
98. How can we ignore merge conflicts due to 32 Give an example of custom pipe?
Whitespace? 33 What is the difference between pure and
99. What is git blame? impure pipe?
100. What is a submodule in GIT? 34 What is a bootstrapping module?
Angular Interview Questions 35 What are observables?
36 What is HttpClient and its benefits?
1 What is Angular Framework? 37 Explain on how to use HttpClient with an
2 What is the difference between AngularJS example?
and Angular? 38 How can you read full response?
3 What is TypeScript? 39 How do you perform Error handling?
4 Write a pictorial diagram of Angular 40 What is RxJS?
architecture? 41 What is subscribing?
19
42 What is an observable? 76 What are different types of compilation in
43 What is an observer? Angular?
44 What is the difference between promise 77 What is JIT?
and observable? 78 What is AOT?
45 What is multicasting? 79 Why do we need compilation process?
46 How do you perform error handling in 80 What are the advantages with AOT?
observables? 81 What are the ways to control AOT
47 What is the short hand notation for compilation?
subscribe method? 82 What are the restrictions of metadata?
48 What are the utility functions provided by 83 What are the three phases of AOT?
RxJS? 84 Can I use arrow functions in AOT?
49 What are observable creation functions? 85 What is the purpose of metadata json
50 What will happen if you do not supply files?
handler for observer? 86 Can I use any javascript feature for
51 What are angular elements? expression syntax in AOT?
52 What is the browser support of Angular 87 What is folding?
Elements? 88 What are macros?
53 What are custom elements? 89 Give an example of few metadata errors?
54 Do I need to bootstrap custom elements? 90 What is metadata rewriting?
55 Explain how custom elements works 91 How do you provide configuration
internally? inheritance?
56 How to transfer components to custom 92 How do you specify angular template
elements? compiler options?
57 What are the mapping rules between 93 How do you enable binding expression
Angular component and custom element? validation?
58 How do you define typings for custom 94 What is the purpose of any type cast
elements? function?
59 What are dynamic components? 95 What is Non null type assertion operator?
60 What are the various kinds of directives? 96 What is type narrowing?
61 How do you create directives using CLI? 97 How do you describe various
62 Give an example for attribute directives? dependencies in angular application?
63 What is Angular Router? 98 What is zone?
64 What is the purpose of base href tag? 99 What is the purpose of common module?
65 What are the router imports? 100 What is codelyzer?
66 What is router outlet? 101 What is angular animation?
67 What are router links? 102 What are the steps to use animation
68 What are active router links? module?
69 What is router state? 103 What is State function?
70 What are router events? 104 What is Style function?
71 What is activated route? 105 What is the purpose of animate function?
72 How do you define routes? 106 What is transition function?
73 What is the purpose of Wildcard route? 107 How to inject the dynamic script in
74 Do I need a Routing Module always? angular?
75 What is Angular Universal?
20
108 What is a service worker and its role in 139 How do you detect route change in
Angular? Angular?
109 What are the design goals of service 140 How do you pass headers for HTTP client?
workers? 141 What is the purpose of differential loading
110 What are the differences between in CLI?
AngularJS and Angular with respect to 142 Is Angular supports dynamic imports?
dependency injection? 143 What is lazy loading?
111 What is Angular Ivy? 144 What are workspace APIs?
112 What are the features included in ivy 145 How do you upgrade angular version?
preview? 146 What is Angular Material?
113 Can I use AOT compilation with Ivy? 147 How do you upgrade location service of
114 What is Angular Language Service? angularjs?
115 How do you install angular language 148 What is NgUpgrade?
service in the project? 149 How do you test Angular application using
116 Is there any editor support for Angular CLI?
Language Service? 150 How to use polyfills in Angular
117 Explain the features provided by Angular application?
Language Service? 151 What are the ways to trigger change
118 How do you add web workers in your detection in Angular?
application? 152 What are the differences of various
119 What are the limitations with web versions of Angular?
workers? 153 What are the security principles in
120 What is Angular CLI Builder? angular?
121 What is a builder? 154 What is the reason to deprecate Web
122 How do you invoke a builder? Tracing Framework?
123 How do you create app shell in Angular? 155 What is the reason to deprecate web
124 What are the case types in Angular? worker packages?
125 What are the class decorators in Angular? 156 How do you find angular CLI version?
126 What are class field decorators? 157 What is the browser support for Angular?
127 What is declarable in Angular? 158 What is schematic?
128 What are the restrictions on declarable 159 What is rule in Schematics?
classes? 160 What is Schematics CLI?
129 What is a DI token? 161 What are the best practices for security in
130 What is Angular DSL? angular?
131 What is an rxjs Subject? 162 What is Angular security model for
132 What is Bazel tool? preventing XSS attacks?
133 What are the advantages of Bazel tool? 163 What is the role of template compiler for
134 How do you use Bazel with Angular CLI? prevention of XSS attacks?
135 How do you run Bazel directly? 164 What are the various security contexts in
136 What is platform in Angular? Angular?
137 What happens if I import the same 165 What is Sanitization? Is angular supports
module twice? it?
138 How do you select an element with in a 166 What is the purpose of innerHTML?
component template?
21
167 What is the difference between 196 How do you use jquery in Angular?
interpolated content and innerHTML? 197 What is the reason for No provider for
168 How do you prevent automatic HTTP exception?
sanitization? 198 What is router state?
169 Is safe to use direct DOM API methods in 199 How can I use SASS in angular project?
terms of security? 200 What is the purpose of hidden property?
170 What is DOM sanitizer? 201 What is the difference between ngIf and
171 How do you support server side XSS hidden property?
protection in Angular application? 202 What is slice pipe?
172 Is angular prevents http level 203 What is index property in ngFor directive?
vulnerabilities? 204 What is the purpose of ngFor trackBy?
173 What are Http Interceptors? 205 What is the purpose of ngSwitch
174 What are the applications of HTTP directive?
interceptors? 206 Is it possible to do aliasing for inputs and
175 Is multiple interceptors supported in outputs?
Angular? 207 What is safe navigation operator?
176 How can I use interceptor for an entire 208 Is any special configuration required for
application? Angular9?
177 How does Angular simplifies 209 What are type safe TestBed API changes in
Internationalization? Angular9?
178 How do you manually register locale data? 210 Is mandatory to pass static flag for
179 What are the four phases of template ViewChild?
translation? 211 What is the list of template expression
180 What is the purpose of i18n attribute? operators?
181 What is the purpose of custom id? 212 What is the precedence between pipe and
182 What happens if the custom id is not ternary operators?
unique? 213 What is an entry component?
183 Can I translate text without creating an 214 What is a bootstrapped component?
element? 215 How do you manually bootstrap an
184 How can I translate attribute? application?
185 List down the pluralization categories? 216 Is it necessary for bootstrapped
186 What is select ICU expression? component to be entry component?
187 How do you report missing translations? 217 What is a routed entry component?
188 How do you provide build configuration 218 Why is not necessary to use
for multiple locales? entryComponents array every time?
189 What is an angular library? 219 Do I still need to use entryComponents
190 What is AOT compiler? array in Angular9?
191 How do you select an element in 220 Is it all components generated in
component template? production build?
192 What is TestBed? 221 What is Angular compiler?
193 What is protractor? 222 What is the role of ngModule metadata in
194 What is collection? compilation process?
195 How do you create schematics for 223 How does angular finds components,
libraries? directives and pipes?
22
224 Give few examples for NgModules? 252 How do you configure injectors with
225 What are feature modules? providers at different levels?
226 What are the imported modules in CLI 253 Is it mandatory to use injectable on every
generated feature modules? service class?
227 What are the differences between 254 What is an optional dependency?
ngmodule and javascript module? 255 What are the types of injector
228 What are the possible errors with hierarchies?
declarations? 256 What are reactive forms?
229 What are the steps to use declaration 257 What are dynamic forms?
elements? 258 What are template driven forms?
230 What happens if browserModule used in 259 What are the differences between
feature module? reactive forms and template driven forms?
231 What are the types of feature modules? 260 What are the different ways to group
232 What is a provider? form controls?
233 What is the recommendation for provider 261 How do you update specific properties of
scope? a form model?
234 How do you restrict provider scope to a 262 What is the purpose of FormBuilder?
module? 263 How do you verify the model changes in
235 How do you provide a singleton service? forms?
236 What are the different ways to remove 264 What are the state CSS classes provided
duplicate service registration? by ngModel?
237 How does forRoot method helpful to 265 How do you reset the form?
avoid duplicate router instances? 266 What are the types of validator functions?
238 What is a shared module? 267 Can you give an example of built-in
239 Can I share services using modules? validators?
240 How do you get current direction for 268 How do you optimize the performance of
locales?? async validators?
241 What is ngcc? 269 How to set ngFor and ngIf on the same
242 What classes should not be added to element?
declarations? 270 What is host property in css?
243 Wat is ngzone? 271 How do you get the current route?
244 What is NoopZone? 272 What is Component Test Harnesses?
245 How do you create displayBlock 273 What is the benefit of Automatic Inlining
components? of Fonts?
246 What are the possible data change
scenarios for change detection? Java Coding Interview Questions
247 What is a zone context?
248 What are the lifecycle hooks of a zone? 1 : How to reverse a String in java? Can you write
249 Which are the methods of NgZone used to a program without using any java inbuilt
control change detection? methods?
250 How do you change the settings of 2 : Write a java program to check if two Strings
zonejs? are anagram in java?
251 How do you trigger an animation? 3 : Write a program to check if String has all
unique characters in java?
23
4 : How to check if one String is rotation of 30 : Find first repeating element in an array of
another String in java? integers.
5 : How to find duplicate characters in String in 31 : Check if Array Elements are Consecutive.
java? 32 : Permutations of array in java.
6 : Find first non repeated character in String in 33 : Rotate an array by K positions.
java? 34 : Stock Buy Sell to Maximize Profit.
7 : Find all substrings of String in java? 35 : Find maximum difference between two
8 : Find length of String without using any inbuilt elements such that larger element appears after
method in java? the smaller number.
9 : Write a program to print all permutations of 36 : Search in a row wise and column wise sorted
String in java? matrix.
37 : Largest sum contiguous subarray.
10 : Write java Program to Find Smallest and 38 : Find the Contiguous Subarray with Sum to a
Largest Element in an Array. Given Value in an array.
11 : Find missing number in the array. 39 : Longest Common Prefix in an array of Strings
12 : Search an element in rotated and sorted in java.
array. 40 : Find all subsets of set (power set) in java.
13 : Find minimum element in a sorted and Stack
rotated array. 41: Implement a stack using array.
14: Find second largest number in an array 42: Implement a stack using Linked List.
15 : Find the number occurring odd number of 43: Implement a stack using two queues.
times in an array 44 : Sort an stack using another stack
16 : Find minimum number of platforms required Queue
for railway station 45: Implement Queue using Array in java.
17 : Find a Pair Whose Sum is Closest to zero in 46: Implement a stack using two queues .
Array Linked List
18 : Given a sorted array and a number x, find the 47 : Implement singly linked list in java.
pair in array whose sum is closest to x 48: How to reverse linked list in java.
19 : Find all pairs of elements from an array 49: How to find middle element of linked list.
whose sum is equal to given number 50 : How to find nth element from end of linked
20: Given an array of 0’s and 1’s in random order, list .
you need to separate 0’s and 1’s in an array. 51 : How to detect a loop in linked list. If linked
21 : Separate odd and even numbers in an array list has loop, find the start node for the loop.
22 : Given an array containing zeroes, ones and 52: How to check if linked list is palindrome or
twos only. Write a function to sort the given array not?
in O(n) time complexity. 53 : Find intersection of two linked lists?
23 : Find local minima in array 54 : How to reverse a linked list in pairs?
24 : Sliding window maximum in java 55 : Implement Doubly linked list in java?
25 : Count number of occurrences (or frequency) Binary Tree
of each element in a sorted array 56 : How can you traverse binary tree?
26 : Find subarrays with given sum in an array. 57 : Write an algorithm to do level order traversal
27 : Find peak element in the array. of binary tree?
28 : Find leaders in an array. 58 : Write an algorithm to do spiral order
29 : Count 1’s in sorted Binary Array. traversal of binary tree?
24
59 : How can you print leaf nodes of binary tree? 86 : Write algorithm to do depth first search in a
60 : How to count leaf nodes of binary tree. graph.
61 : How to print all paths from root to leaf in 87 : Write algorithm to do breadth first search in
binary tree. a graph.
62 : How to find level of node in binary tree 88 : Explain Dijkstra algorithm from source to all
63 : How to find maximum element in binary tree. other vertices.
64 : How to find lowest common ancestor(LCA) in 89 : Explain Bellman Ford algorithm to find
binary tree. shortest distance
65 : How to do boundary traversal of binary tree. 90 : Explain Kruskal’s algorithm for finding
66 : How to print vertical sum of binary tree? minimum spanning tree
67 : Count subtrees with Sum equal to target in Dynamic Programming
binary tree? 91 : Given two String, find longest common
Binary Search tree substring.
68 : What is binary search tree? 92 : Given two Strings A and B. Find the length of
69 : Can you write algorithm to insert a node in the Longest Common Subsequence (LCS) of the
binary search tree. given Strings.
70 : Can you write algorithm to delete a node in 93 : Given a matrix, we need to count all paths
binary search tree. from top left to bottom right of MxN matrix. You
71 : How can you find minimum and maximum can either move down or right.
elements in binary search tree? 94 : Edit Distance Problem in java
72 : How to find lowest common ancestor(LCA) in 95: Coin change problem in java
binary search tree. 96 : Minimum number of jumps to reach last
73 : Find inorder successor in a Binary search Tree index
74 : Convert sorted array to balanced BST Miscellaneous
75 : Convert sorted Linked List to balanced BST 97 : What is an algorithm and how to calculate
76 : Check if a binary tree is binary search tree or complexity of algorithms.
not in java 98 : Implement trie data structure in java.
Sorting 99 : Count Factorial Trailing Zeroes in java.
77 : Write an algorithm to implement bubble 100 : Largest Rectangular Area in a Histogram.
sort? 101 : Check for balanced parentheses in an
78 : Write an algorithm to implement insertion expression in java.
sort sort? 102 : What is Memoization.
79 : Write an algorithm to implement selection
sort sort? Data Structures Interview Questions
80 : Can you write algorithm for merge sort and
also do you know complexity of merge sort? 1. What is the data structure?
81 : Do you know how to implement Heap sort? 2. Difference between file structure and storage
82 : Implement quick sort in java? structure
83 : Implement shell sort in java? 3. When is a binary search best applied?
84 : Implement Counting sort in java? 4. What do you mean by linked list?
85 : What is binary search? Can you write an 5. In what areas data structures can be applied?
algorithm to find an element in sorted array using 6. What do you understand by LIFO?
binary search? 7. What is the queue?
Graph 8. What do you mean by binary trees?
25
9. Which data structures are meant to be applied 14. What is the lifecycle of a Docker Container?
while dealing with a recursive function? 15. What is Docker Machine?
10. What do you mean by a stack? 16. How to check for Docker Client and Docker
11. Explain binary search tree Server version?
12. What are multidimensional arrays? 17. How do you get the number of containers
13. What can be linked lists considered as: linear running, paused and stopped?
or non-linear data structures? 18. If you vaguely remember the command and
14. List the ways how dynamic memory allocation you’d like to confirm it, how will you get help on
helps in managing data that particular command?
15. What do you understand by FIFO? The following command is very useful as it gives
16. What is an ordered list? you help on how to use a command, the syntax,
17. What do you understand by merge sort? etc.
18. Differentiate between NULL and VOID 19. How to login into docker repository?
19. List out the primary advantages of linked list. 20. If you wish to use a base image and make
20. What’s the difference between a PUSH and a modifications or personalize it, how do you do
POP? that?
30. What is a linear search? 21. How do you create a docker container from
31. How does the variable declaration affect an image?
memory allocation? 22. How do you list all the running containers?
32. List out the advantages that can come when 23. Suppose you have 3 containers running and
the heap is over a stack out of these, you wish to access one of them.
33. What do you understand by postfix How do you access a running container?
expression? 24. How to start, stop and kill a container?
34. What does data abstraction mean? 25. Can you use a container, edit it, and update
35. How to insert a new item in the binary search it? Also, how do you make it a new and store it on
tree? the local system?
36. What are the ways in which a selection sort Of course, you can use a container, edit it and
works for an array? update it. This sounds complicated but its actually
just one command.
Docker Interview Questions 26. Once you’ve worked with an image, how do
1. What is Hypervisor? you push it to docker hub?
2. What is virtualization? 27. How to delete a stopped container?
3. What is containerization? 28. How to delete an image from the local
4. Difference between virtualization and storage system?
containerization 29. How to build a Dockerfile?
5. What is Docker? 30. Do you know why docker system prune is
6. What is a Docker Container? used? What does it do?
7. What are Docker Images? 31. Will you lose your data, when a docker
8. What is Docker Hub? container exists?
9. Explain Docker Architecture? 32. Where all do you think Docker is being used?
10. What is a Dockerfile? 33. How is Docker different from other
11. Tell us something about Docker Compose. containerization methods?
12. What is Docker Swarm? 34. Can I use JSON instead of YAML for my
13. What is a Docker Namespace? compose file in Docker?
26
35. How have you used Docker in your previous 12) Explain Kubernetes Architecture
position? 13) List various services available in Kubernetes
36. How far do Docker containers scale? Are 14) Define Cluster IP
there any requirements for the same? 15) Explain node port
37. What platforms does docker run on? 16) Define kubelet
38. Is there a way to identify the status of a 17) What are the disadvantages of Kubernetes?
Docker container? 18) What is Kube-proxy?
39. Can you remove a paused container from 19) What is the difference between Kubernetes
Docker? and Docker Swarm?
40. Can a container restart by itself? 20) Define Ingress Network
41. Is it better to directly remove the container 21) What is Kubectl used for?
using the rm command or stop the container 22) What is GKE?
followed by remove container? 23) Why load balancer is needed?
42. Will cloud overtake the use of 24) How to run Kubernetes locally?
Containerization? 25) What are the tools that are used for container
43. How many containers can run per host? monitoring?
44. Is it a good practice to run stateful 26) List components of Kubernetes
applications on Docker? 27) Define headless service
45. Suppose you have an application that has 28) What are the important components of node
many dependant services. Will docker compose status?
wait for the current container to be 29) What is minikube?
46. How will you monitor Docker in production? 30) Mention the uses of GKE
47. Is it a good practice to run Docker compose in 31) Define orchestration in Kubernetes
production? 32) Explain Prometheus in Kubernetes
48. What changes are expected in your docker 33) List tools for container orchestration
compose file while moving it to production? 34) Mention the list of objects of Kubernetes?
49. Have you used Kubernetes? If you have, 35) Define Stateful sets in Kubernetes
which one would you prefer amongst Docker and 36) Why use Daemon sets?
Kubernetes? 37) Explain Replica set
50. Are you aware of load balancing across 38) List out some important Kubectl commands:
containers and hosts? How does it work? 39) Why uses Kube-apiserver?
40) Explain the types of Kubernetes pods
Kubernetes Interview Questions 41) What are the labels in Kubernetes?
1) What is Kubernetes? 42) What are the objectives of the replication
2) Define node in Kubernetes controller?
3) What is the work of a kube-scheduler? 43) What do you mean by persistent volume?
4) Define daemon sets 44) What are Secrets in Kubernetes?
5) Define Heapster in Kubernetes 45) What is Sematext Docker Agent?
6) What tasks are performed by Kubernetes? 46) Define OpenShift
7) Define Kubernetes controller manager 47) Define K8s
8) Why use namespace in Kubernetes? 48) What are federated clusters?
9) Why use Kubernetes? 49) Mention the difference between Docker
10) What are the features of Kubernetes? volumes and Kubernetes Volumes
11) Mention the types of controller managers
27
50) What are the ways to provide API-Security on 33. How to underline text in HTML?
Kubernetes? 34. How to create a box in HTML?
51) What is ContainerCreating pod? 35. How to put an image in HTML?
52) What are the types of Kubernetes Volume? 36. How to change font in HTML?
53) Explain PVC 37. How to add a link in HTML?
54) What is the Kubernetes Network Policy? 38. What is HTML tags?
55) What is Kubernetes proxy service? 39. How to create a checkbox in HTML?
40. How to create a box in HTML?
HTML Interview Questions 41. How to add a scroll bar in HTML?
42. What is an attribute in HTML?
1. What is HTML? 43. How to increase button size in HTML?
2. How to insert an image in HTML? 44. How to change font size in HTML?
3. How to set background image in HTML? 45. How to change color of text in HTML?
4. How to comment in HTML? 46. How to bold text in HTML?
5. How to give space in HTML? 47. How to add a footer in HTML?
6. How to link CSS to HTML? 48. Who invented HTML?
7. How to align text in HTML? 49. How to align the image in the center in
8. How to create a table in HTML? HTML?
9. How to convert HTML to PDF? 50. How to create a hyperlink in HTML?
10. How to change text color in HTML? 51. How do add a header in HTML?
11. How to change font color in HTML? 52. How to give space between two buttons in
12. How to change background color in HTML? HTML?
13. What is doctype in HTML? 53. How to change image size in HTML?
14. How to change font style in HTML? 54. Why do we use doctype in HTML?
15. How to add space in HTML? 55. How to add video in HTML?
16. What is dom in HTML? 56. How to add favicon in HTML?
17. How to add image in HTML from a folder? 57. How to embed YouTube video in HTML?
18. How to create form in HTML? 58. How to write text on image in HTML?
19. How to create button in HTML? 59. How to create a popup in html with CSS?
20. How to run HTML program? 60. How to connect html to database with
21. How to save HTML file? MySQL?
22. How to select multiple options from a drop 61. How to blink text in HTML?
down list in HTML? 62. How to add calendar in HTML Form?
23. How to use div tag in html to divide the page? 63. How to add video in HTML?
24. What is HTML used for? 64. How to add google map in HTML?
25. How to align text in center in HTML? 65. How to create registration form in HTML with
26. How to increase font size in HTML? database?
27. How to create button in HTML? 66. How to create a dynamic calendar in HTML?
28. How to add images in html? 67. How to create frames in HTML?
29. How to change button color in HTML? 68. How to create a menu in HTML?
30. What is the difference between html and 69. What is the difference between HTML tags
html5? and elements?
31. How to create drop down list in HTML? 70. Which types of heading are found in HTML?
32. What is span in HTML?
28
71. How can you insert a copyright symbol in 20. What is the new form elements introduced in
HTML webpage? HTML5?
72. How to specify the metadata in HTML? 21. What happens if you view a new HTML5 form
73. What are Inline and block elements in HTML? input type in an older browser?
74. Is audio tag supported in HTML 5? 22. Which tags are no longer valid in HTML5?
75. Is it possible to change the color of the bullet? 23. How to center text in HTML5?
76. How can you keep list elements straight in an 24. How to center an image in HTML5?
HTML file? 25. What is HTML5 Canvas?
77. What are Forms in HTML? 26. What is the difference between HTML5 and
78. What are void elements in HTML? CSS3?
79. What is a marquee? 27. Briefly explain the different formatting tags
80. What is an Anchor tag in HTML? used in HTML5.
81. What is an image map? 28. Which HTML5 tag would you use to define
82. What is datalist tag? footer?
83. What is difference between HTML and 29. Which tags are used to create a table in
XHTML? HTML5?
84. What is the ‘class’ attribute in HTML? 30. Which tag represents an independent piece of
85. What is the use of an IFrame tag? content of a document in HTML5?
86. What is the use of figure tag in HTML 5? 31. What are the common lists to design a
87. Why is a URL encoded in HTML? webpage using HTML5?
32. What are the audio and video formats that
HTML5 Interview Questions are used for embedding on a webpage?
33. Which plugin is required to use svg tags in
1. What is HTML5? HTML5?
2. What is HTML5 used for? 34. How to convert Flash to HTML5?
3. What are the building blocks of HTML5? 35. How to convert PSD to HTML5?
4. When was HTML5 released? 36. What is the HTML5 stack?
5. What is the difference between HTML and 37. Explain the Drag and Drop concept of HTML5.
HTML5? 38. What is the Geolocation API in HTML5 and
6. What is the difference between HTML4 and how to use it?
HTML5? 39. How to clear HTML5 offline storage mega?
7. What is new in HTML5? 40. What is HTML5 boilerplate?
8. Which browsers support HTML5? 41. How to make HTML5 games?
9. How to turn on HTML5 in Chrome? 42. How to create a dashboard in HTML5?
10. How to install HTML5?
11. Why to use HTML5? CSS Interview Questions and Answers
12. How to use or code in HTML5?
13. Which DOCTYPE is correct for HTML5? 1. Define CSS?
14. How to turn off HTML5? 2. Mention the origin of CSS?
15. How to download HTML5 video? 3. What are the several forms of CSS?
16. What is an HTML5 player? 4. State the restrictions of CSS?
17. Which functionality applies to HTML5 ads? 5. List the benefits of CSS?
18. How to disable HTML5 twitch? 6. Define CSS frameworks?
19. How to link CSS to HTML5? 7. Who postulates the specifications of CSS?
29
8. What are the ways in which CSS can be 41. What is at-rule?
integrated as a website? 42. What is the difference between CSS and
9. What merits and disadvantages do External CSS3?
Style Sheets offer?
10. State the benefits and disadvantages of JavaScript Interview Questions
Embedded Style Sheets?
11. What is the meaning of the CSS selector? 1. What is JavaScript?
12. What are the media types allowed by CSS? 2. Enumerate the differences between Java and
13. Differentiate between physical tags and JavaScript?
logical tags? 3. What are JavaScript Data Types?
14. State the difference between Style Sheet and 4. What is the use of isNaN function?
HTML? 5. Which is faster between JavaScript and an ASP
15. Describe ‘ruleset’? script?
16. Is there Case-sensitivity in CSS? 6. What is negative Infinity?
17. Give the definition of the Declaration block? 7. Is it possible to break JavaScript Code into
18. Enlist the various attributes of font? several lines?
19. Why does inserting a file make importation 8. Which company developed JavaScript?
easy? 9. What are undeclared and undefined variables?
20. What is the use of a Class selector? 10. Write the code for adding new elements
21. What is the difference between a Class dynamically?
selector and an ID selector? 11. What are global variables? How are these
22. Can you add more than one declaration in variable declared?
CSS? 12. What is a prompt box?
23. What are Pseudo-elements? 13. What is ‘this’ keyword in JavaScript?
24. How to overrule underlining Hyperlinks? 14. What is the working of timers in JavaScript?
25. Can CSS help in restoring default property 15. Which symbol is used for comments in
value? Javascript?
26. List the kinds of Media types used in CSS? 17. What is === operator?
27. Define CSS Box Model and state its elements? 18. How you can submit a form using JavaScript?
28. What is a contextual selector? 19. Does JavaScript support automatic type
29. Compare Hexadecimal color codes with RGB conversion?
values? 20. How can the style/class of an element be
30. Define Image sprites with context to CSS? changed?
31. Compare Grouping and Nesting in CSS? 21. How to read and write a file using JavaScript?
32. How can the dimensions of an element be 22. What are all the looping structures in
defined? JavaScript?
33. What is float property? 23. What is called Variable typing in Javascript?
34. How does the Z index function? 24. How can you convert the string of any base to
36. Which of them is precedent: HTML an integer in JavaScript?
procedures or CSS properties? 25. Difference between “==” and “===”?
37. Define Inline style? 26. What would be the result of 3+2+”7″?
38. In CSS, how can comments be added? 27. How to detect the operating system on the
39. What is Attribute Selector? client machine?
40. Define property? 28. What do you mean by NULL in Javascript?
30
29. What is the function of the delete operator? 58. What is a window.onload and
30. What is an undefined value in JavaScript? onDocumentReady?
31. What are all the types of Pop up boxes 59. How closures work in JavaScript?
available in JavaScript? 60. How can a value be appended to an array?
32. What is the use of Void (0)? 61. What is for-in loop in Javascript?
33. How can a page be forced to load another 62. What are the important properties of an
page in JavaScript? anonymous function in JavaScript?
34. What is the data type of variables in 63. What is the difference between .call() and
JavaScript? .apply()?
35. What is the difference between an alert box 64. What is event bubbling?
and a confirmation box? 65. Is JavaScript case sensitive? Give its example.
36. What are escape characters? 66. What boolean operators can be used in
37. What are JavaScript Cookies? JavaScript?
38. What a pop()method in JavaScript is? 67. How can a particular frame be targeted, from
39. Does JavaScript has concept level scope? a hyperlink, in JavaScript?
40. What are the disadvantages of using 68. What is the role of break and continue
innerHTML in JavaScript? statements?
41. What is break and continue statements? 69. Write the point of difference between a web
42. What are the two basic groups of data types garden and a web farm?
in JavaScript? 70. How are object properties assigned?
43. How can generic objects be created? 71. What is the method for reading and writing a
44. What is the use of a type of operator? file in JavaScript?
45. Which keywords are used to handle 72. How are DOM utilized in JavaScript?
exceptions? 73. How are event handlers utilized in JavaScript?
46. Which keyword is used to print the text on 74. What is the role of deferred scripts in
the screen? JavaScript?
47. What is the use of the blur function? 75. What are the various functional components
48. What is variable typing? in JavaScript?
49. How to find an operating system in the client 76. Write about the errors shown in JavaScript?
machine using JavaScript? 77. What are Screen objects?
50. What are the different types of errors in 78. What is the unshift() method?
JavaScript? 79. What is unescape() and escape() functions?
51. What is the use of the Push method in 80. What are the decodeURI() and encodeURI()?
JavaScript? 81. Why you should not use innerHTML in
52. What is the unshift method in JavaScript? JavaScript?
53. What is the difference between JavaScript 82. What does the following statement declare?
and Jscript? 83. How are JavaScript and ECMA Script related?
54. How are object properties assigned? 84. What is namespacing in JavaScript, and how is
55. What is the ‘Strict Mode in JavaScript, and it used?
how can it be enabled? 85. How can JavaScript codes be hidden from old
56. What is the way to get the status of a browsers that do not support JavaScript?
CheckBox? 86. How to use Loop in JavaScript?
57. How can the OS of the client machine be 87. How to use Loops in Javascript?
detected?
31
88. What are the important JavaScript Array Q16. Is it possible to compile .ts automatically
Method explain with example? with real-time changes in the .ts file?
89. What is OOPS Concept in JavaScript? Q17. What are the object-oriented terms
90. What is Loop Though the Properties of an supported by TypeScript?
Object? Q18. What are Interfaces in TypeScript?
91. What is JavaScript Unit Testing, and what are Q19. What are Classes in TypeScript? List out
the challenges in JavaScript Unit Testing? some of the features.
92. What are some important JavaScript Unit Q20. What are the access modifiers supported by
Testing Frameworks? TypeScript?
93. What is QuickSort Algorithm in JavaScript? Q21. How is TypeScript an optionally statically
94.How does QuickSort Work typed language?
94. What is DOM in JavaScript? Q22. What are modules in TypeScript?
95. How to use DOM and Events? Q23. What is the difference between the internal
96. What is External JavaScript? module and the external module?
97. When to Use Internal and External JavaScript Q24. What is namespace in Typescript and how
Code? to declare it?
98. What are Cookies in JavaScript? Q25. Does TypeScript support function
99. Give an example of JavaScript Multiplication overloading?
Table Q26. Explain Decorators in TypeScript.
100. Explain Popup Message using event with Q27. What are Mixins?
example Q28. How does TypeScript support optional
parameters in function?
TypeScript Interview Questions Q29. What is Scope variable?
Q30. How can you debug a TypeScript file?
Q1. What are the Differences between TypeScript Q31. What is TypeScript Definition Manager and
and JavaScript? why do we need it?
Q2. What is TypeScript? Q32. What are the steps to include Type
Q3. Why do we need TypeScript? Definition File?
Q4. Mention some of the features of TypeScript Q33. What is TypeScript Declare Keyword?
Q5. What are the Benefits of using TypeScript? Q34. What is the Default Parameters Function in
Q6. What are the Disadvantages of TypeScript? TypeScript?
Q7. What are the Components of TypeScript? Q35. What is tsconfig.json file?
Q8. Who developed Typescript and what is the Q36. What are Generics in TypeScript?
current stable version available? Q37. What is the difference between interface
Q9. How to install TypeScript? and type statements?
Q10. How do you compile TypeScript files? Q38. What is JSX in TypeScript?
Q11. Can we combine multiple .ts files into a Q39. What are all the JSX modes TypeScript
single .js file? supports?
Q12. What are the different types of TypeScript? Q40. What are Ambients in TypeScripts and when
Q13. List out the built-in data types in TypeScript. to use them?
Q14. What are Variables in TypeScript and how to Q41. What is a TypeScript Map file?
create them? Q42. What is Type assertions in TypeScript?
Q15. What are the different ways of declaring a Q43. What are Rest parameters?
Variable?
32
Q44. What are the rules to declare Rest 20. What is HQL?
parameters? Give an example. 21. Can you tell something about one to many
Q45. What is “as” syntax in TypeScript? associations and how can we use them in
Q46. Explain Enum in TypeScript. Hibernate?
Q47. Explain Relative and Non-relative module 22. What are Many to Many associations?
imports. 23. What does session.lock() method in hibernate
Q48. What is an anonymous function? do?
Q49. What is method overriding in TypeScript? 24. What is hibernate caching?
Q50. What is Lambda/Arrow function? 25. When is merge() method of the hibernate
session useful?
Hibernate Interview Questions 26. Collection mapping can be done using One-to-
One and Many-to-One Associations. What do you
1. What is ORM in Hibernate? think?
2. What are the advantages of Hibernate over 27. Can you tell the difference between
JDBC? setMaxResults() and setFetchSize() of Query?
3. What are some of the important interfaces of 28. Does Hibernate support Native SQL Queries?
Hibernate framework? 29. What happens when the no-args constructor
4. What is a Session in Hibernate? is absent in the Entity bean?
5. What is a SessionFactory? 30. Can we declare the Entity class final?
6. What do you think about the statement - 31. What are the states of a persistent entity?
“session being a thread-safe object”? 32. Explain Query Cache
7. Can you explain what is lazy loading in 33. Can you tell something about the N+1 SELECT
hibernate? problem in Hibernate?
8. What is the difference between first level 34. How to solve N+1 SELECT problem in
cache and second level cache? Hibernate?
9. What can you tell about Hibernate 35. What are the concurrency strategies available
Configuration File? in hibernate?
10. How do you create an immutable class in 36. What is Single Table Strategy?
hibernate? 37. Can you tell something about Table Per Class
11. Can you explain the concept behind Hibernate Strategy.
Inheritance Mapping? 38. Can you tell something about Named SQL
12. Is hibernate prone to SQL injection attack? Query
13. Explain hibernate mapping file 39. What are the benefits of NamedQuery?
14. What are the most commonly used
annotations available to support hibernate SQL Interview Questions
mapping?
15. Explain Hibernate architecture 1) What is SQL?
16. Can you tell the difference between 2) What are tables in SQL?
getCurrentSession and openSession methods? 3) What are the different types of statements
17. Differentiate between save() and supported by SQL?
saveOrUpdate() methods in hibernate session. 4) How do we use the DISTINCT statement? What
18. Differentiate between get() and load() in is its use?
Hibernate session 5) What are the different Clauses used in SQL?
19. What is criteria API in hibernate?
33
6) Why do we use SQL constraints? Which 34) What are Nested Triggers?
constraints we can use while creating a database 35) What is a Cursor?
in SQL? 36) What is Collation?
7) What are different JOINS used in SQL? 37) What do we need to check in Database
8) What are transactions and their controls? Testing?
9) What are the properties of the transaction? 38) What is Database White Box Testing?
10) How many Aggregate functions are available 39) What is Database Black Box Testing?
in SQL? 40) What are Indexes in SQL?
11) What are Scalar functions in SQL? 41) What does SQL stand for?
12) What are triggers? 42) How to select all records from the table?
13) What is View in SQL? 43) Define join and name different types of joins?
14) How we can update the view? 44) What is the syntax to add a record to a table?
15) Explain the working of SQL Privileges? 45) How do you add a column to a table?
16) How many types of Privileges are available in 46) Define the SQL DELETE statement.
SQL? 47) Define COMMIT?
17) What is SQL Injection? 48) What is the Primary key?
18) What is SQL Sandbox in SQL Server? 49) What are Foreign keys?
19) What is the difference between SQL and 50) What is CHECK Constraint?
PL/SQL? 51) Is it possible for a table to have more than
20) What is the difference between SQL and one foreign key?
MySQL? 52) What are the possible values for the
21) What is the use of the NVL function? BOOLEAN data field?
22) What is the Cartesian product of the table? 53) What is a stored procedure?
23) What do you mean by Subquery? 54) What is identity in SQL?
24) How many row comparison operators are 55) What is Normalization?
used while working with a subquery? 56) What is a Trigger?
25) What is the difference between clustered and 57) How to select random rows from a table?
non-clustered indexes? 58) Which TCP/IP port does SQL Server run?
26) What is the difference between DELETE and 59) Write a SQL SELECT query that only returns
TRUNCATE? each name only once from a table?
27) What is the difference between DROP and 60) Explain DML and DDL?
TRUNCATE? 61) Can we rename a column in the output of the
28) How to write a query to show the details of a SQL query?
student from Students table whose 62) Give the order of SQL SELECT?
29) What is the difference between Nested 63) Suppose a Student column has two columns,
Subquery and Correlated Subquery? Name and Marks. How to get names and marks of
30) What is Normalization? How many the top three students.
Normalization forms are there? 64) What is SQL comments?
31) What is a Relationship? How many types of 65) Difference between TRUNCATE, DELETE and
Relationships are there? DROP commands?
32) What do you mean by Stored Procedures? 66) What are the properties of a transaction?
How do we use it? 67) What do you mean by ROWID?
33) State some properties of Relational 68) Define UNION, MINUS, UNION ALL,
databases? INTERSECT?
34
69) What is a transaction? 8. Why does Profiler use in MongoDB?
70) What is the difference between UNIQUE and 9. What is “Namespace” in MongoDB?
PRIMARY KEY constraints? 10. What are Indexes in MongoDB?
71) What is a composite primary key? 11. What is BSON in MongoDB?
72) What is an Index? 12. What is a replica set?
73) What is the Subquery? 13. What Is Replication In MongoDB?
74) What do you mean by query optimization? 14. Mention the command to insert a document
75) What is Collation? in a database called school and collection called
76) What is Referential Integrity? persons.
77) What is the Case function? 15. Explain the structure of ObjectID in MongoDB
78) Define a temp table? 16. Why MongoDB is not preferred over a 32-bit
79) How can we avoid duplicating records in a system?
query? 17. Does MongoDB pushes the writes to disk
80) Explain the difference between Rename and immediately or lazily?
Alias? 18. When to use MongoDB or other document
81) What is a View? oriented database systems?
82) What are the advantages of Views? 19. What is sharding?
83) List the various privileges that a user can 20. What is use of capped collection in
grant to another user? MongoDB?
84) What is schema? 21. What is the difference between MongoDB
85) What is a Table? and MySQL?
86) Does View contain Data? 22. Does Mongodb Support Foreign Key
87) Can a View based on another View? Constraints?
88) What is the difference between the HAVING 23. Why are MongoDB data files large in size?
clause and WHERE clause? 24. What is the difference b/w MongoDB and
89) What is the difference between Local and CouchDB?
Global temporary tables? 25. Can you create an index on an array field in
90) What is CTE? MongoDB? If yes, what happens in this case?
26. If you remove a document from database,
Mongo DB Interview Questions does MongoDB remove it from disk?
27. What is Sharding in MongoDB?
1. Explain what is MongoDB? 28. Should I normalize my data before storing it in
2. How many indexes does MongoDB create by MongoDB?
default for a new collection? 29. What does MongoDB not being ACID
3. Which are the most important features of compliant really mean?
MongoDB? 30. When to use CouchDB over MongoDB and
4. When should we embed one document within vice versa?
another in MongoDB? 31. How is MongoDB better than other SQL
5. Compare SQL databases and MongoDB at a databases?
high level 32. How can you achieve transaction and locking
6. If you remove an object attribute, is it deleted in MongoDB?
from the database? 33. How can you achieve primary key - foreign
7. Does MongoDB need a lot space of Random key relationships in MongoDB?
Access Memory (RAM)? 34. What is oplog?
35
35. What is a covered query in MongoDB? 65. How does MongoDB ensure high availability?
36. Is there an “upsert” option in the mongodb 66. What's the advantage of the backup features
insert command? in Ops Manager versus traditional backup
37. Explain advantages of BSON over JSON in strategies?
MongoDB? 67. Where does MongoDB stand in the CAP
38. Does MongoDB support ACID transaction theorem?
management and locking functionalities? 68. Which are the two storage engines used by
39. How is data stored in MongoDB? MongoDB?
40. Can one MongoDB operation lock more than 69. What are three primary concerns when
one databases? If yes, how? choosing a data management system?
41. What is Aggregation in MongoDB? 70. How much faster is Redis than MongoDB?
42. What is BSON and exactly how is it different 71. What is a Storage Engine in MongoDB
from JSON? 72. What is splitting in MongoDB?
43. What is a cluster in MongoDB? 73. How to condense large volumes of data in
44. Mention the command to check whether you Mongo?
are on the master server or not. 74. What are the differences between MongoDB
45. How can I combine data from multiple and MySQL?
collections into one collection? 75. Update MongoDB field using value of another
46. How do I perform the SQL JOIN equivalent in field
MongoDB? 76. How to check if a field contains a substring?
47. How to query MongoDB with %like%? 77. How to get the last N records from find?
48. Find objects between two dates MongoDB 78. MongoDB relationships. What to use - embed
49. How to query MongoDB with “like”? or reference?
50. What happens if an index does not fit into 79. How to remove a field completely from a
RAM? MongoDB document?
51. Mention the command to list all the indexes 80. By default, MongoDB writes and reads data
on a particular collection from both primary and secondary replica sets.
52. How can you isolate your cursors from True or False.
intervening with the write operations? 81. How to find MongoDB records where array
53. Explain what is horizontal scalability? field is not empty?
54. How does MongoDB provide concurrency? 82. Is it possible to update MongoDB field using
55. How does Journaling work in MongoDB? value of another field?
56. Is MongoDB schema-less? 83. How to find document with array that
57. When to Redis or MongoDB? contains a specific value?
58. How replication works in MongoDB?
59. What are alternatives to MongoDB? Agile Interview Questions
60. Where can I run MongoDB?
61. At what interval does MongoDB write updates 1. What are different types of Agile
to the disk? Methodology?
62. What are Primary and Secondary Replica 2. What are advantages and disadvantages of
sets? Agile Process.
63. Why is a covered query important? 3. Explain Agile Testing? What are the principles
64. Does MongoDB provide a facility to do text of Agile Testing?
searches? How?
36
4. What good qualities an Agile Tester should 28. Explain the terms User story, Epic, and Tasks
have? in Scrum?
5. What do you mean by refactoring? 29. What are the important tools that are mostly
6. What's the difference between sprint backlog used in a Scrum Project?
and product backlog? 30. Explain TimeBoxing in Scrum.
7. What is Spike and Zero Sprint in Agile? 31. Explain the term “impediments” in Scrum.
8. What’s the difference between Agile 32. What is the main role of Sashimi in Scrum?
methodology and Traditional methodology of 33. Explain the term “story point” in Scrum.
Software Development? 34. What do you mean by Scrum of Scrums (SoS)?
9. What do you mean by the term “velocity” in
Agile? Algorithms and Programming Interview
10. What do you mean by Daily Stand-Up Questions
meeting?
11. What is Incremental and Iterative 1. Array Coding Interview Questions
Development?
12. What is a Product Roadmap? How do you find the missing number in a given
13. What are different project management tools integer array of 1 to 100?
that are mostly used in Agile? How do you find the duplicate number on a given
14. What is the difference between Agile and integer array?
Scrum? How do you find the largest and smallest number
15. What do you mean by Pair Programming? in an unsorted integer array?
Write its advantages. How do you find all pairs of an integer array
16. What is Agile Manifesto? What are its values whose sum is equal to a given number?
and principles? How do you find duplicate numbers in an array if
17. What are Burn-up and Burn-down charts in it contains multiple duplicates?
Agile? How are duplicates removed from a given array in
18. What are different types of Burn-Down Java?
charts? How is an integer array sorted in place using the
19. Name three main Agile frameworks other quicksort algorithm?
than Scrum for product development. How do you remove duplicates from an array in
20. What is “Planning Poker” technique? place?
21. What is a Sprint Planning Meeting, Sprint How do you reverse an array in place in Java?
Review Meeting and Sprint Retrospective How are duplicates removed from an array
Meeting? without using any library?
22. What do you mean by the term “increment”?
23. What are standard or common metrics for 2. Linked List Programming Interview Questions
Agile? Explain.
24. What is Scrum? Write its advantages. How do you find the middle element of a singly
25. What are different roles in Scrum? linked list in one pass?
26. What do you mean by Scrum Master? What How do you check if a given linked list contains a
are the responsibilities of Scrum Master? cycle? How do you find the starting node of the
27. What are the main artifacts of Scrum cycle?
Framework? How do you reverse a linked list?

37
How do you reverse a singly linked list without How do you print all nodes of a given binary tree
recursion? using inorder traversal without recursion?
How are duplicate nodes removed in an unsorted How do you implement a post-order traversal
linked list? algorithm?
How do you find the length of a singly linked list? How do you traverse a binary tree in post-order
How do you find the third node from the end in a traversal without recursion?
singly linked list? How are all leaves of a binary search tree
How do you find the sum of two linked lists using printed?
Stack? How do you count a number of leaf nodes in a
given binary tree?
3. String Coding Interview Questions How do you perform a binary search in a given
array?
How do you print duplicate characters from a
string? 5. Miscellaneous Coding Interview Questions
How do you check if two strings are anagrams of
each other? How is a bubble sort algorithm implemented?
How do you print the first non-repeated How is an iterative quicksort algorithm
character from a string? implemented?
How can a given string be reversed using How do you implement an insertion sort
recursion? algorithm?
How do you check if a string contains only digits? How is a merge sort algorithm implemented?
How are duplicate characters found in a string? How do you implement a bucket sort algorithm?
How do you count a number of vowels and How do you implement a counting sort
consonants in a given string? algorithm?
How do you count the occurrence of a given How is a radix sort algorithm implemented?
character in a string? How do you swap two numbers without using the
How do you find all permutations of a string? third variable?
How do you reverse words in a given sentence How do you check if two rectangles overlap with
without using any library method? each other?
How do you check if two strings are a rotation of How do you design a vending machine?
each other?
How do you check if a given string is a Data Structure and Algorithm Interview
palindrome? Questions

4. Binary Tree Coding Interview Questions Arrays

How is a binary search tree implemented? 1. Rotate Array


How do you perform preorder traversal in a given 2. Contains Duplicate
binary tree? 3. Find Peak Element
How do you traverse a given binary tree in pre- 4. Maximum Subarray
order without recursion? 5. Kth Largest Element in an Array
How do you perform an in-order traversal in a 6. Find All Duplicates in an Array
given binary tree? 7. Longest Increasing Subsequence
8. Rotate Image, matrix
38
9. Shuffle an Array 26. Serialize and Deserialize BT
10. Find Min in Rotated Array 27. And many other tree problems
11. Search in Rotated Array
Maths
Linked List
1. Integer Break
1. Singly Linked List Implementation 2. Reverse Bits
2. Doubly Linked List Implementation 3. Palindrome Number
3. Delete Node in a Linked List 4. Math.pow
4. Palindrome Linked List 5. Jug and Water Problem
5. Reverse Linked List 6. Sieve of Eratosthenes
6. Intersection of Two Linked Lists 7. Fermat's primality
7. Linked List Cycle 8. Evaluate Reverse Polish Notation
8. Remove Nth Node From End of List
9. Merge Sort List Stack & Queue
10. Find Linked List Cycle
11. Merge k Sorted Lists 1. Min Stack
2. Min Queue
Binary Tree 3. Implement Stack Using Queue
1. Binary Tree Level Order Traversal 4. Implement Queue Using Stack
2. Sum of Left Leaves 5. Sort Stack
3. Invert Binary Tree 6. Dynamic Programming
4. Binary Search Tree Iterator 7. Fibonacci Numbers
5. Binary Tree Postorder Traversal 8. Word Break
6. Binary Tree Preorder Traversal 9. Subset Sum
7. Flatten Binary Tree to Linked List 10. 0/1 Knapsack Problem
8. Symmetric Tree 11. Shortest Palindrome (KMP)
9. Binary Tree Inorder Traversal 12. Minimum Square Sum
10. Same Tree 13. Maximum weight transformation of a String
11. Maximum Depth of Binary Tree 14. Coin Change
12. Balanced Binary Tree 15. Union Find
13. Minimum Depth of Binary Tree 16. Permutations
14. Sorted List to Balanced Binary Search Tree 17. Subsets
15. Validate Binary Search Tree
16. Sorted List to Balanced BST Algorithms
17. Kth Smallest Element in a BST
18. Binary Tree Zigzag Level Order Traversal 1. Sorting And Searching
19. Delete Node in a BST 2. Bubble Sort
20. Lowest Common Ancestor of BST 3. Insertion Sort
21. Binary Tree Left Side View 4. Selection Sort
22. Binary Tree Right Side View 5. Counting Sort
23. Mode in BST 6. Binary Search , Lower & Upper Bounds
24. Most Frequent Subtree Sum 7. MergeSort
25. Find Largest Element in Each Row 8. QuickSort
39
Graphs 2)**Single Number**
Given an array of integers, every element appears
1. Breadth First Search (BFS) twice except for one. Find that single one.
2. Depth First Search (DFS) Note:Your algorithm should have a linear runtime
3. Prim's Minimum Spanning Tree (MST) complexity. Could you implement it without using
4. KrusKal's Minimum Spanning Tree (MST) extra memory?
5. Topological Sorting
6. Shortest Path Dijsktra 3)**Delete Node in a Linked List**
7. Shortest Path Bellman-Ford Write a function to delete a node (except the tail)
8. A* Heuristic Path Finding in a singly linked list, given only access to that
9. Is Graph Bipartite node.
10. Is Graph Connected Supposed the linked list is 1 -> 2 -> 3 -> 4 and you
11. Cycle Detection are given the third node with value 3, the linked
12. Undirected Graph Bridge Detection list should become 1 -> 2 -> 4 after calling your
function.
String
4)**Maximum Depth of Binary Tree**
1. Rabin Karp Subsequence search Given a binary tree, find its maximum depth.
2. Ransom Note The maximum depth is the number of nodes
3. Reverse String along the longest path from the root node down
4. Longest Common Prefix to the farthest leaf node.
5. Is Anagram
6. Needle and Haystack 5)**Minimum Depth of Binary Tree**
7. Word Break Given a binary tree, find its minimum depth.
8. Meta Strings The minimum depth is the number of nodes
along the shortest path from the root node down
Trees to the nearest leaf node.

1. Binary Search Tree (recursive) 6)**Binary Tree Level Order Traversal I**
2. Binary Search Tree (iterative) Given a binary tree, return the level order
3. AVL Tree traversal of its nodes' values. (ie, from left to
4. Trie (Prefix tree) right, level by level).
5. Hashed Array Tree For example:Given binary tree
6. LRU Cache [3,9,20,null,null,15,7],
[
Easy Level [3],
[9,20],
1)**Hamming Distance** [15,7]
The Hamming distance between two integers is ]
the number of positions at which the
corresponding bits are different. 7)**Binary Tree Level Order Traversal II**
Given two integers x and y, calculate the
Hamming distance.
40
Given a binary tree, return the bottom-up level Both numbers with value 2 are both considered
order traversal of its nodes' values. (ie, from left as second maximum.
to right, level by level from leaf to root).
For example:Given binary tree Input: [1, 2]
[3,9,20,null,null,15,7], Output: 2
[ Explanation: The third maximum does not exist,
[15,7], so the maximum (2) is returned instead.
[9,20],
[3] Input: [3, 2, 1]
] Output: 1
Explanation: The third maximum is 1.
8)** Invert a binary tree.**
13)**Two Sum**
9) **Same Tree** Given an array of integers, return indices of the
Given two binary trees, write a function to check two numbers such that they add up to a specific
if they are equal or not. target.
Two binary trees are considered equal if they are You may assume that each input would have
structurally identical and the nodes have the exactly one solution.
same value.
14)**Contains Duplicate II**
10)**Path Sum** Given an array of integers and an integer k, find
Given a binary tree and a sum, determine if the out whether there are two distinct indices i and j
tree has a root-to-leaf path such that adding up in the array such that nums[i] = nums[j] and the
all the values along the path equals the given difference between i and j is at most k.
sum.

11)**Ransom Note** 15)**Best Time to Buy and Sell Stock**


Given an arbitrary ransom note string and Say you have an array for which the ith element is
another string containing letters from all the the price of a given stock on day i.
magazines, write a function that will return true if If you were only permitted to complete at most
the ransom note can be constructed from the one transaction (ie, buy one and sell one share of
magazines ; otherwise, it will return false. the stock), design an algorithm to find the
Each letter in the magazine string can only be maximum profit.
used once in your ransom note. Input: [7, 1, 5, 3, 6, 4]
Output: 5
12)**Third Maximum Number**
Given a non-empty array of integers, return the 16) **Remove Element**
third maximum number in this array. If it does Given an array and a value, remove all instances
not exist, return the maximum number. The time of that value in place and return the new length.
complexity must be in O(n). Do not allocate extra space for another array, you
Input: [2, 2, 3, 1] must do this in place with constant memory.
Output: 1 The order of elements can be changed. It doesn't
Explanation: Note that the third maximum here matter what you leave beyond the new length.
means the third maximum distinct number.
41
17) **Move Zeroes** Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return
Given an array nums, write a function to move all [2, 2].
0's to the end of it while maintaining the relative Note:
order of the non-zero elements. Each element in the result should appear as many
For example, given nums = [0, 1, 0, 3, 12], after times as it shows in both arrays.
calling your function, nums should be [1, 3, 12, 0, The result can be in any order.
0]. Follow up:
You must do this in-place without making a copy What if the given array is already sorted? How
of the array. would you optimize your algorithm?
Minimize the total number of operations. What if nums1's size is small compared to
nums2's size? Which algorithm is better?
18)**Merge Sorted Arrays** What if elements of nums2 are stored on disk,
Given two sorted integer arrays nums1 and and the memory is limited such that you cannot
nums2, merge nums2 into nums1 as one sorted load all elements into the memory at once?
array.
Note: 23)**Intersection of Two Arrays II**
You may assume that nums1 has enough space Given two arrays, write a function to compute
(size that is greater or equal to m + n) to hold their intersection.
additional elements from nums2. The number of Example:
elements initialized in nums1 and nums2 are m Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return
and n respectively. [2, 2].
Note:
19)**Reverse Array** Each element in the result should appear as many
times as it shows in both arrays.
20)**Two Sum II - Input array is sorted** The result can be in any order.
Given an array of integers that is already sorted in Follow up:
ascending order, find two numbers such that they What if the given array is already sorted? How
add up to a specific target number. would you optimize your algorithm?
The function twoSum should return indices of the What if nums1's size is small compared to
two numbers such that they add up to the target, nums2's size? Which algorithm is better?
where index1 must be less than index2. Please What if elements of nums2 are stored on disk,
note that your returned answers (both index1 and the memory is limited such that you cannot
and index2) are not zero-based. load all elements into the memory at once?

21) **Intersection of Two Arrays** 24)**Valid Anagram**


Given two arrays, write a function to compute Given two strings s and t, write a function to
their intersection. determine if t is an anagram of s.
Each element in the result must be unique. The For example,
result can be in any order. s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
22)**Intersection of Two Arrays II**
Given two arrays, write a function to compute 25)**Count Primes**
their intersection. Description:
Example:
42
Count the number of prime numbers less than a Write a program to find the node at which the
non-negative number, n. intersection of two singly linked lists begins.

26)**Ugly Number** 32)**Remove Duplicates from Sorted List**


Write a program to check whether a given Given a sorted linked list, delete all duplicates
number is an ugly number. such that each element appear only once.
Ugly numbers are positive numbers whose prime For example,
factors only include 2, 3, 5. For example, 6, 8 are Given 1->1->2, return 1->2.
ugly while 14 is not ugly since it includes another Given 1->1->2->3->3, return 1->2->3.
prime factor 7.
Note that 1 is typically treated as an ugly number. 33)**Remove Linked List Elements**
Remove all elements from a linked list of integers
27)**Longest Palindrome** that have value val.
Given a string which consists of lowercase or Example
uppercase letters, find the length of the longest Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
palindromes that can be built with those letters. Return: 1 --> 2 --> 3 --> 4 --> 5
This is case sensitive, for example "Aa" is not
considered a palindrome here. 34)** Palindrome Linked List**
Given a singly linked list, determine if it is a
28) **Isomorphic Strings** palindrome.
Given two strings s and t, determine if they are Follow up:
isomorphic. Could you do it in O(n) time and O(1) space?
Two strings are isomorphic if the characters in s
can be replaced to get t. 35) **Valid Palindrome**
All occurrences of a character must be replaced Given a string, determine if it is a palindrome,
with another character while preserving the considering only alphanumeric characters and
order of characters. No two characters may map ignoring cases.
to the same character but a character may map For example,
to itself. "A man, a plan, a canal: Panama" is a palindrome.
For example, "race a car" is not a palindrome.
Given "egg", "add", return true.
Given "foo", "bar", return false. 36)**First Bad Version**
Given "paper", "title", return true. You are a product manager and currently leading
a team to develop a new product. Unfortunately,
29)**Linked List Cycle** the latest version of your product fails the quality
Given a linked list, determine if it has a cycle in it. check. Since each version is developed based on
Can you solve it without using extra space? the previous version, all the versions after a bad
version are also bad.
30)**Merge Two Sorted Lists** Suppose you have n versions [1, 2, ..., n] and you
Merge two sorted linked lists and return it as a want to find out the first bad one, which causes
new list. The new list should be made by splicing all the following ones to be bad.
together the nodes of the first two lists. You are given an API bool isBadVersion(version)
which will return whether version is bad.
31)**Intersection of Two Linked Lists** Implement a function to find the first bad version.
43
You should minimize the number of calls to the and it will automatically contact the police if two
API. adjacent houses were broken into on the same
night.
Given a list of non-negative integers representing
37)**Guess Number Higher or Lower** the amount of money of each house, determine
We are playing the Guess Game. The game is as the maximum amount of money you can rob
follows: tonight without alerting the police.
I pick a number from 1 to n. You have to guess
which number I picked. 41)** Climbing Stairs**
Every time you guess wrong, I'll tell you whether You are climbing a stair case. It takes n steps to
the number is higher or lower. reach to the top.
You call a pre-defined API guess(int num) which Each time you can either climb 1 or 2 steps. In
returns 3 possible results (-1, 1, or 0): how many distinct ways can you climb to the top?
-1 : My number is lower
1 : My number is higher 42)**Implement Queue using Stacks**
0 : Congrats! You got it! Implement the following operations of a queue
using stacks.
38) **Arranging Coins** push(x) -- Push element x to the back of queue.
You have a total of n coins that you want to form pop() -- Removes the element from in front of
in a staircase shape, where every k-th row must queue.
have exactly k coins. peek() -- Get the front element.
Given n, find the total number of full staircase empty() -- Return whether the queue is empty.
rows that can be formed. Notes:
n is a non-negative integer and fits within the You must use only standard operations of a stack
range of a 32-bit signed integer. -- which means only push to top, peek/pop from
top, size, and is empty operations are valid.
39)**Range Sum Query - Immutable** Depending on your language, stack may not be
Given an integer array nums, find the sum of the supported natively. You may simulate a stack by
elements between indices i and j (i ≤ j), inclusive. using a list or deque (double-ended queue), as
Example: long as you use only standard operations of a
Given nums = [-2, 0, 3, -5, 2, -1] stack.
sumRange(0, 2) -> 1 You may assume that all operations are valid (for
sumRange(2, 5) -> -1 example, no pop or peek operations will be called
sumRange(0, 5) -> -3 on an empty queue).
Note:
You may assume that the array does not change. 43)Sum of Left Leaves
There are many calls to sumRange function. Find the sum of all left leaves in a given binary
tree.
40)**House Robber**
You are a professional robber planning to rob 44) Binary Tree Paths
houses along a street. Each house has a certain Given a binary tree, return all root-to-leaf paths.
amount of money stashed, the only constraint For example, given the following binary tree:
stopping you from robbing each of them is that
adjacent houses have security system connected 1
44
/ \ exceed 100. Determine the perimeter of the
2 3 island.
\ [[0,1,0,0],
5 [1,1,1,0],
All root-to-leaf paths are: [0,1,0,0],
["1->2->5", "1->3"] [1,1,0,0]]

44)** Balanced Binary Tree** Answer: 16


Given a binary tree, determine if it is height-
balanced. 48)**Find the Difference**
For this problem, a height-balanced binary tree is Given two strings s and t which consist of only
defined as a binary tree in which the depth of the lowercase letters.
two subtrees of every node never differ by more String t is generated by random shuffling string s
than 1. and then add one more letter at a random
position.
45)**Find All Numbers Disappeared in an Array** Find the letter that was added in t.
Given an array of integers where 1 ≤ a[i] ≤ n (n =
size of array), some elements appear twice and 49) **Add Digit**
others appear once. Given a non-negative integer num, repeatedly
Find all the elements of [1, n] inclusive that do add all its digits until the result has only one digit.
not appear in this array. For example:
Could yu do it without extra space and in O(n) Given num = 38, the process is like: 3 + 8 = 11, 1 +
runtime? You may assume the returned list does 1 = 2. Since 2 has only one digit, return it.
not count as extra space. Follow up:
Example: Could you do it without any loop/recursion in
Input: O(1) runtime?
[4,3,2,7,8,2,3,1]
Output: 50)**Majority Element**
[5,6] Given an array of size n, find the majority
element. The majority element is the element
46)**Reverse String** that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and
47)**Island Perimeter** the majority element always exist in the array.
You are given a map in form of a two-dimensional
integer grid where 1 represents land and 0 51)**Contains Duplicate**
represents water. Grid cells are connected Given an array of integers, find if the array
horizontally/vertically (not diagonally). The grid is contains any duplicates. Your function should
completely surrounded by water, and there is return true if any value appears at least twice in
exactly one island (i.e., one or more connected the array, and it should return false if every
land cells). The island doesn't have "lakes" (water element is distinct.
inside that isn't connected to the water around
the island). One cell is a square with side length 1. 52)First Unique Character in a String
The grid is rectangular, width and height don't

45
Given a string, find the first non-repeating
character in it and return it's index. If it doesn't 57)**Reverse Bits**
exist, return -1. Reverse bits of a given 32 bits unsigned integer.
Examples: For example, given input 43261596 (represented
s = "leetcode" in binary as
return 0. 00000010100101000001111010011100), return
s = "loveleetcode", 964176192 (represented in binary as
return 2. 00111001011110000010100101000000).
Note: You may assume the string contain only Follow up:
lowercase letters. If this function is called many times, how would
you optimize it?
53) ** Power of Two**
Given an integer, write a function to determine if
it is a power of two. 58)**Assign Cookies**
Assume you are an awesome parent and want to
54) **Power of Four** give your children some cookies. But, you should
Given an integer (signed 32 bits), write a function give each child at most one cookie. Each child i
to check whether it is a power of 4. has a greed factor gi, which is the minimum size
Example: of a cookie that the child will be content with;
Given num = 16, return true. Given num = 5, and each cookie j has a size sj. If sj >= gi, we can
return false. assign the cookie j to the child i, and the child i
Follow up: Could you solve it without will be content. Your goal is to maximize the
loops/recursion? number of your content children and output the
maximum number.
55)**Reverse Integer** Note:
Reverse digits of an integer. You may assume the greed factor is always
Example1: x = 123, return 321 positive.
Example2: x = -123, return -321 You cannot assign more than one cookie to one
101 child.
Example 1:
56)**Minimum Moves to Equal Array Elements** Input: [1,2,3], [1,1]
Given a non-empty integer array of size n, find Output: 1
the minimum number of moves required to make Explanation: You have 3 children and 2 cookies.
all array elements equal, where a move is The greed factors of 3 children are 1, 2, 3.
incrementing n - 1 elements by 1. And even though you have 2 cookies, since their
Example: size is both 1, you could only make the child
Input: whose greed factor is 1 content.
[1,2,3] You need to output 1.
Output:
3
Explanation: 59) **Swap Nodes in Pairs**
Only three moves are needed (remember each Given a linked list, swap every two adjacent
move increments two elements): nodes and return its head.
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] For example,
46
Given 1->2->3->4, you should return the list as 2- You must not use any built-in BigInteger library or
>1->4->3. convert the inputs to integer directly.
Your algorithm should use only constant space.
You may not modify the values in the list, only 63)**Search Insert Position**
nodes itself can be changed. Given a sorted array and a target value, return
the index if the target is found. If not, return the
60) **NumberComplement** index where it would be if it were inserted in
Given a positive integer, output its complement order.
number. The complement strategy is to flip the You may assume no duplicates in the array.
bits of its binary representation. Here are few examples.
Note: [1,3,5,6], 5 → 2
The given integer is guaranteed to fit within the [1,3,5,6], 2 → 1
range of a 32-bit signed integer. [1,3,5,6], 7 → 4
You could assume no leading zero bit in the [1,3,5,6], 0 → 0
integer’s binary representation.
Example 1: 64)**Palindrome Number**
Input: 5 Determine if given integer is palindrome, don't
Output: 2 use extra space
Explanation: The binary representation of 5 is 101
(no leading zero bits), and its complement is 010. 65)**Lowest Common Ancestor of a Binary
So you need to output 2. Search Tree**
Given a binary search tree (BST), find the lowest
61)**Repeated Substring Pattern** common ancestor (LCA) of two given nodes in the
Given a non-empty string check if it can be BST.
constructed by taking a substring of it and
appending multiple copies of the substring According to the definition of LCA on Wikipedia:
together. You may assume the given string “The lowest common ancestor is defined
consists of lowercase English letters only and its between two nodes v and w as the lowest node
length will not exceed 10000. in T that has both v and w as descendants (where
Example 1: we allow a node to be a descendant of itself).”
Input: "abab"
Output: True _______6______
Explanation: It's the substring "ab" twice. / \
___2__ ___8__
62)**Add Strings** / \ / \
Given two non-negative integers num1 and num2 0 _4 7 9
represented as string, return the sum of num1 / \
and num2. 3 5
Note: For example, the lowest common ancestor (LCA)
The length of both num1 and num2 is < 5100. of nodes 2 and 8 is 6. Another example is LCA of
Both num1 and num2 contains only digits 0-9. nodes 2 and 4 is 2, since a node can be a
Both num1 and num2 does not contain any descendant of itself according to the LCA
leading zero. definition.

47
66)**Number of Segments in a String** The count-and-say sequence is the sequence of
Count the number of segments in a string, where integers beginning as follows:
a segment is defined to be a contiguous sequence 1, 11, 21, 1211, 111221, ...
of non-space characters. 1 is read off as "one 1" or 11.
Please note that the string does not contain any 11 is read off as "two 1s" or 21.
non-printable characters. 21 is read off as "one 2, then one 1" or 1211.
Example: Given an integer n, generate the nth sequence.
Input: "Hello, my name is John" Note: The sequence of integers will be
Output: 5 represented as a string.

67) **Largest Difference in an Array** 71)Construct the Rectangle


You have an array of integers, find the largest For a web developer, it is very important to know
difference between a[i] and a[j] where i<j how to design a web page's size. So, given a
specific rectangular web page’s area, your job by
68)**Happy Number** now is to design a rectangular web page, whose
Write an algorithm to determine if a number is length L and width W satisfy the following
"happy". requirements:
A happy number is a number defined by the 1. The area of the rectangular web page you
following process: Starting with any positive designed must equal to the given target area.
integer, replace the number by the sum of the 2. The width W should not be larger than the
squares of its digits, and repeat the process until length L, which means L >= W.
the number equals 1 (where it will stay), or it 3. The difference between length L and width W
loops endlessly in a cycle which does not include should be as small as possible.
1. Those numbers for which this process ends in 1
are happy numbers. 72)Length of Last Word
Example: 19 is a happy number Given a string s consists of upper/lower-case
1^2 + 9^2 = 82 alphabets and empty space characters ' ', return
8^2 + 2^2 = 68 the length of last word in the string.
6^2 + 8^2 = 100 If the last word does not exist, return 0.
1^2 + 0^2 + 0^2 = 1 Note: A word is defined as a character sequence
consists of non-space characters only.
69)**Max Consecutive Ones** For example,
Given a binary array, find the maximum number Given s = "Hello World",
of consecutive 1s in this array. return 5.

Example 1: 73)Best Time to Buy and Sell Stock II


Input: [1,1,0,1,1,1] Say you have an array for which the ith element is
Output: 3 the price of a given stock on day i.
Explanation: The first two digits or the last three Design an algorithm to find the maximum profit.
digits are consecutive 1s. You may complete as many transactions as you
The maximum number of consecutive 1s is 3. like (ie, buy one and sell one share of the stock
multiple times). However, you may not engage in
70)Count and Say multiple transactions at the same time (ie, you
must sell the stock before you buy again).
48
74)Longest Common Prefix 1
Write a function to find the longest common \
prefix string amongst an array of strings. 3
/
75)Add Binary 2
Given two binary strings, return their sum (also a
binary string). Output:
1
For example,
a = "11" Explanation:
b = "1" The minimum absolute difference is 1, which is
Return "100". the difference between 2 and 1 (or between 2
and 3).
76) Note: There are at least two nodes in this BST.
Given numRows, generate the first numRows of
Pascal's triangle. 79)Minimum Time Difference
For example, given numRows = 5, Given a list of 24-hour clock time points in
Return "Hour:Minutes" format, find the minimum
[ minutes difference between any two time points
[1], in the list.
[1,1],
[1,2,1], 80) Reverse String II
[1,3,3,1], Given a string and an integer k, you need to
[1,4,6,4,1] reverse the first k characters for every 2k
] characters counting from the start of the string. If
there are less than k characters left, reverse all of
77) them. If there are less than 2k but greater than or
Given an index k, return the kth row of the equal to k characters, then reverse the first k
Pascal's triangle. characters and left the other as original.
For example, given k = 3, Example:
Return [1,3,3,1]. Input: s = "abcdefg", k = 2
Note: Output: "bacdfeg"
Could you optimize your algorithm to use only Restrictions:
O(k) extra space? The string consists of lower English letters only.
Length of the given string and k will in the range
78)Minimum Absolute Difference in BST [1, 10000]
Given a binary search tree with non-negative
values, find the minimum absolute difference 81)Diameter of Binary Tree
between values of any two nodes. Given a binary tree, you need to compute the
length of the diameter of the tree. The diameter
Example: of a binary tree is the length of the longest path
between any two nodes in a tree. This path may
Input: or may not pass through the root.
49
Example: 84)Add Digits
Given a binary tree Given a non-negative integer num, repeatedly
1 add all its digits until the result has only one digit.
/\
2 3 For example:
/\
4 5 Given num = 38, the process is like: 3 + 8 = 11, 1 +
Return 3, which is the length of the path [4,2,1,3] 1 = 2. Since 2 has only one digit, return it.
or [5,2,1,3].
Follow up:
Note: The length of path between two nodes is Could you do it without any loop/recursion in
represented by the number of edges between O(1) runtime?
them.
85)Reverse Words in a String III
82)Single Element in a Sorted Array Given a string, you need to reverse the order of
Given a sorted array consisting of only integers characters in each word within a sentence while
where every element appears twice except for still preserving whitespace and initial word order.
one element which appears once. Find this single
element that appears only once. Example 1:
Input: "Let's take LeetCode contest"
Example 1: Output: "s'teL ekat edoCteeL tsetnoc"
Input: [1,1,2,3,3,4,4,8,8] Note: In the string, each word is separated by
Output: 2 single space and there will not be any extra space
Example 2: in the string.
Input: [3,3,7,7,10,11,11]
Output: 10 86)Shortest Word Distance
Note: Your solution should run in O(log n) time Given a list of words and two words word1 and
and O(1) space. word2, return the shortest distance between
these two words in the list.
83)Perfect Number
We define the Perfect Number is a positive For example,
integer that is equal to the sum of all its positive Assume that words = ["practice", "makes",
divisors except itself. "perfect", "coding", "makes"].

Now, given an integer n, write a function that Given word1 = “coding”, word2 = “practice”,
returns true when it is a perfect number and false return 3.
when it is not. Given word1 = "makes", word2 = "coding", return
Example: 1.
Input: 28
Output: True Note:
Explanation: 28 = 1 + 2 + 4 + 7 + 14 You may assume that word1 does not equal to
Note: The input number n will not exceed word2, and word1 and word2 are both in the list.
100,000,000. (1e8)
50
87)Binary Tree Tilt fill in the surrounding area until the color changes
Given a binary tree, return the tilt of the whole from the original color.
tree.
90)Find sum of all left leaves in a given Binary
The tilt of a tree node is defined as the absolute Tree
difference between the sum of all left subtree Given a Binary Tree, find sum of all left leaves in
node values and the sum of all right subtree node it.
values. Null node has tilt 0.
91) Range Addition II
The tilt of the whole tree is defined as the sum of Given an m * n matrix M initialized with all 0's
all nodes' tilt. and several update operations.

Example: Operations are represented by a 2D array, and


Input: each operation is represented by an array with
1 two positive integers a and b, which means M[i][j]
/ \ should be added by one for all 0 <= i < a and 0 <= j
2 3 < b.
Output: 1
Explanation: You need to count and return the number of
Tilt of node 2 : 0 maximum integers in the matrix after performing
Tilt of node 3 : 0 all the operations.
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1 Example 1:
Input:
88)Palindrome Permutation m = 3, n = 3
Given a string, determine if a permutation of the operations = [[2,2],[3,3]]
string could form a palindrome. Output: 4
Explanation:
For example, Initially, M =
"code" -> False, "aab" -> True, "carerac" -> True. [[0, 0, 0],
[0, 0, 0],
88)Triple Step [0, 0, 0]]
A child is running up a staircase with n steps and
can hop either 1 step, 2 steps, or 3 After performing [2,2], M =
steps at a time. Implement a method to count [[1, 1, 0],
how many possible ways the child can run up the [1, 1, 0],
stairs. [0, 0, 0]]

89) Paint Fill After performing [3,3], M =


Implement the "paint fill" function that one might [[2, 2, 1],
see on many image editing programs. [2, 2, 1],
That is, given a screen (represented by a two- [1, 1, 1]]
dimensional array of colors), a point, and a new
color, 92)Can Place Flowers
51
Suppose you have a long flowerbed in which Output: "1(2(4))(3)"
some of the plots are planted and some are not.
However, flowers cannot be planted in adjacent Explanation: Originallay it needs to be
plots - they would compete for water and both "1(2(4)())(3()())",
would die. but you need to omit all the unnecessary empty
parenthesis pairs.
Given a flowerbed (represented as an array And it will be "1(2(4))(3)".
containing 0 and 1, where 0 means empty and 1 Example 2:
means not empty), and a number n, return if n Input: Binary tree: [1,2,3,null,4]
new flowers can be planted in it without violating 1
the no-adjacent-flowers rule. / \
2 3
Example 1: \
Input: flowerbed = [1,0,0,0,1], n = 1 4
Output: True
Example 2: Output: "1(2()(4))(3)"
Input: flowerbed = [1,0,0,0,1], n = 2
Output: False Explanation: Almost the same as the first
Note: example,
The input array won't violate no-adjacent-flowers except we can't omit the first parenthesis pair to
rule. break the one-to-one mapping relationship
The input array size is in the range of [1, 20000]. between the input and the output.
n is a non-negative integer which won't exceed
the input array size. 94) Image Smoother
Given a 2D integer matrix M representing the
93)Construct String from Binary Tree gray scale of an image, you need to design a
You need to construct a string consists of smoother to make the gray scale of each cell
parenthesis and integers from a binary tree with becomes the average gray scale (rounding down)
the preorder traversing way. of all the 8 surrounding cells and itself. If a cell
has less than 8 surrounding cells, then use as
The null node needs to be represented by empty many as you can.
parenthesis pair "()". And you need to omit all the
empty parenthesis pairs that don't affect the one- Example 1:
to-one mapping relationship between the string Input:
and the original binary tree. [[1,1,1],
[1,0,1],
Example 1: [1,1,1]]
Input: Binary tree: [1,2,3,4] Output:
1 [[0, 0, 0],
/ \ [0, 0, 0],
2 3 [0, 0, 0]]
/ Explanation:
4 For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) =
floor(0.75) = 0
52
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = R=2
floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) Output:
=0 1
Note: \
The value in the given matrix is in the range of [0, 2
255]. Example 2:
The length and width of the given matrix are in Input:
the range of [1, 150]. 3
/\
95) Judge Route Circle 0 4
Initially, there is a Robot at position (0, 0). Given a \
sequence of its moves, judge if this robot makes a 2
circle, which means it moves back to the original /
place. 1

The move sequence is represented by a string. L=1


And each move is represent by a character. The R=3
valid robot moves are R (Right), L (Left), U (Up)
and D (down). The output should be true or false Output:
representing whether the robot makes a circle. 3
/
Example 1: 2
Input: "UD" /
Output: true 1
Example 2:
Input: "LL" 97)Second Minimum Node In a Binary Tree
Output: false Given a non-empty special binary tree consisting
of nodes with the non-negative value, where
96)Trim a Binary Search Tree each node in this tree has exactly two or zero
Given a binary search tree and the lowest and sub-node. If the node has two sub-nodes, then
highest boundaries as L and R, trim the tree so this node's value is the smaller value among its
that all its elements lies in [L, R] (R >= L). You two sub-nodes.
might need to change the root of the tree, so the
result should return the new root of the trimmed Given such a binary tree, you need to output the
binary search tree. second minimum value in the set made of all the
nodes' value in the whole tree.
Example 1:
Input: If no such second minimum value exists, output -
1 1 instead.
/\
0 2 Example 1:
Input:
L=1 2
53
/\ Example 1:
2 5 Input: "aba"
/\ Output: True
5 7 Example 2:
Input: "abca"
Output: 5 Output: True
Explanation: The smallest value is 2, the second Explanation: You could delete the character 'c'.
smallest value is 5.
Example 2: 100) Two Sum IV - Input is a BST
Input: Given a Binary Search Tree and a target number,
2 return true if there exist two elements in the BST
/\ such that their sum is equal to the given target.
2 2
Example 1:
Output: -1 Input:
Explanation: The smallest value is 2, but there 5
isn't any second smallest value. /\
3 6
98)Longest Continuous Increasing Subsequence /\ \
Given an unsorted array of integers, find the 2 4 7
length of longest continuous increasing
subsequence. Target = 9

Example 1: Output: True


Input: [1,3,5,4,7] Example 2:
Output: 3 Input:
Explanation: The longest continuous increasing 5
subsequence is [1,3,5], its length is 3. /\
Even though [1,3,5,7] is also an increasing 3 6
subsequence, it's not a continuous one where 5 /\ \
and 7 are separated by 4. 2 4 7
Example 2:
Input: [2,2,2,2,2] Target = 28
Output: 1
Explanation: The longest continuous increasing Output: False
subsequence is [2], its length is 1.
Note: Length of the array will not exceed 10,000. 101) Baseball Game
You're now a baseball game point recorder.

99) Valid Palindrome II Given a list of strings, each string can be one of
Given a non-empty string s, you may delete at the 4 following types:
most one character. Judge whether you can make
it a palindrome. Integer (one round's score): Directly represents
the number of points you get in this round.
54
"+" (one round's score): Represents that the Note:
points you get in this round are the sum of the The size of the input list will be between 1 and
last two valid round's points. 1000.
"D" (one round's score): Represents that the Every integer represented in the list will be
points you get in this round are the doubled data between -30000 and 30000.
of the last valid round's points.
"C" (an operation, which isn't a round's score): 102) Alternating Bits
Represents the last valid round's points you get Given a positive integer, check whether it has
were invalid and should be removed. alternating bits: namely, if two adjacent bits will
Each round's operation is permanent and could always have different values.
have an impact on the round before and the
round after. Example 1:
Input: 5
You need to return the sum of the points you Output: True
could get in all the rounds. Explanation:
The binary representation of 5 is: 101
Example 1: Example 2:
Input: ["5","2","C","D","+"] Input: 7
Output: 30 Output: False
Explanation: Explanation:
Round 1: You could get 5 points. The sum is: 5. The binary representation of 7 is: 111.
Round 2: You could get 2 points. The sum is: 7.
Operation 1: The round 2's data was invalid. The 103) Max Area of Island
sum is: 5. Given a non-empty 2D array grid of 0's and 1's, an
Round 3: You could get 10 points (the round 2's island is a group of 1's (representing land)
data has been removed). The sum is: 15. connected 4-directionally (horizontal or vertical.)
Round 4: You could get 5 + 10 = 15 points. The You may assume all four edges of the grid are
sum is: 30. surrounded by water.
Example 2:
Input: ["5","-2","4","C","D","9","+","+"] Find the maximum area of an island in the given
Output: 27 2D array. (If there is no island, the maximum area
Explanation: is 0.)
Round 1: You could get 5 points. The sum is: 5.
Round 2: You could get -2 points. The sum is: 3. Example 1:
Round 3: You could get 4 points. The sum is: 7. [[0,0,1,0,0,0,0,1,0,0,0,0,0],
Operation 1: The round 3's data is invalid. The [0,0,0,0,0,0,0,1,1,1,0,0,0],
sum is: 3. [0,1,1,0,1,0,0,0,0,0,0,0,0],
Round 4: You could get -4 points (the round 3's [0,1,0,0,1,1,0,0,1,0,1,0,0],
data has been removed). The sum is: -1. [0,1,0,0,1,1,0,0,1,1,1,0,0],
Round 5: You could get 9 points. The sum is: 8. [0,0,0,0,0,0,0,0,0,0,1,0,0],
Round 6: You could get -4 + 9 = 5 points. The sum [0,0,0,0,0,0,0,1,1,1,0,0,0],
is 13. [0,0,0,0,0,0,0,1,1,0,0,0,0]]
Round 7: You could get 9 + 5 = 14 points. The sum
is 27.
55
Given the above grid, return 6. Note the answer is equal to the sum of the numbers to the right of
not 11, because the island must be connected 4- the index.
directionally.
Example 2: If no such index exists, we should return -1. If
[[0,0,0,0,0,0,0,0]] there are multiple pivot indexes, you should
Given the above grid, return 0. return the left-most pivot index.
Note: The length of each dimension in the given
grid does not exceed 50. Example 1:
Input:
nums = [1, 7, 3, 6, 5, 6]
104)Degree of an Array Output: 3
Given a non-empty array of non-negative integers Explanation:
nums, the degree of this array is defined as the The sum of the numbers to the left of index 3
maximum frequency of any one of its elements. (nums[3] = 6) is equal to the sum of numbers to
the right of index 3.
Your task is to find the smallest possible length of Also, 3 is the first index where this occurs.
a (contiguous) subarray of nums, that has the Example 2:
same degree as nums. Input:
nums = [1, 2, 3]
Example 1: Output: -1
Input: [1, 2, 2, 3, 1] Explanation:
Output: 2 There is no index that satisfies the conditions in
Explanation: the problem statement.
The input array has a degree of 2 because both
elements 1 and 2 appear twice.
Of the subarrays that have the same degree: 106) Check whether the given string is Pangram
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, Given a string, check whether it contains all
3], [2, 2] alphabets from A to Z.
The shortest length is 2. So return 2.
Example 2: Example 1:
Input: [1,2,2,3,1,4,2] Input: The quick brown fox jumps over the lazy
Output: 6 dog
Note: Output: True
Explanation: The above sentence contains all
nums.length will be between 1 and 50,000. alphabets from A to Z. Upper Case or Lower Case
nums[i] will be an integer between 0 and 49,999. don't matter. Also, repeatition don't matter.

105)Find Pivot Element Example 2:


Given an array of integers nums, write a method Input: Hello GitHub
that returns the "pivot" index of this array. Output: False
Explanation: Only 9 alphabets are present in the
We define the pivot index as the index where the string - "b, e, g, h, i, l, o, t, u". Hence, the string is
sum of the numbers to the left of the index is not a Pangram.

56
107) 744. Find Smallest Letter Greater Than letters consists of lowercase letters, and contains
Target at least 2 unique letters.
target is a lowercase letter.
Given a list of sorted characters letters containing
only lowercase letters, and given a target letter 108) Minimum Distance Between BST Nodes
target, find the smallest element in the list that is Given a Binary Search Tree (BST) with the root
larger than the given target. node root, return the minimum difference
between the values of any two different nodes in
Letters also wrap around. For example, if the the tree.
target is target = 'z' and letters = ['a', 'b'], the
answer is 'a'. Example :

Examples: Input: root = [4,2,6,1,3,null,null]


Input: Output: 1
letters = ["c", "f", "j"] Explanation:
target = "a" Note that root is a TreeNode object, not an array.
Output: "c"
The given tree [4,2,6,1,3,null,null] is represented
Input: by the following diagram:
letters = ["c", "f", "j"]
target = "c" 4
Output: "f" / \
2 6
Input: /\
letters = ["c", "f", "j"] 1 3
target = "d"
Output: "f" while the minimum difference in this tree is 1, it
occurs between node 1 and node 2, also between
Input: node 3 and node 2.
letters = ["c", "f", "j"] Note:
target = "g"
Output: "j" The size of the BST will be between 2 and 100.
The BST is always valid, each node's value is an
Input: integer, and each node's value is different.
letters = ["c", "f", "j"]
target = "j" 109)Min Cost Climbing Stairs
Output: "c" On a staircase, the i-th step has some non-
negative cost cost[i] assigned (0 indexed).
Input:
letters = ["c", "f", "j"] Once you pay the cost, you can either climb one
target = "k" or two steps. You need to find minimum cost to
Output: "c" reach the top of the floor, and you can either
Note: start from the step with index 0, or the step with
letters has a length in range [2, 10000]. index 1.
57
Example 1: [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-
Input: cost = [10, 15, 20] .-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-
Output: 15 ","...-",".--","-..-","-.--","--.."]
Explanation: Cheapest is start on cost[1], pay that Now, given a list of words, each word can be
cost and go to the top. written as a concatenation of the Morse code of
Example 2: each letter. For example, "cab" can be written as
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] "-.-.-....-", (which is the concatenation "-.-." + "-..."
Output: 6 + ".-"). We'll call such a concatenation, the
Explanation: Cheapest is start on cost[0], and only transformation of a word.
step on 1s, skipping cost[3].
Note: Return the number of different transformations
cost will have a length in the range [2, 1000]. among all words we have.
Every cost[i] will be an integer in the range [0,
999]. Example:
Input: words = ["gin", "zen", "gig", "msg"]
110) Rotate String Output: 2
We are given two strings, A and B. Explanation:
The transformation of each word is:
A shift on A consists of taking string A and moving "gin" -> "--...-."
the leftmost character to the rightmost position. "zen" -> "--...-."
For example, if A = 'abcde', then it will be 'bcdea' "gig" -> "--...--."
after one shift on A. Return True if and only if A "msg" -> "--...--."
can become B after some number of shifts on A.
There are 2 different transformations, "--...-." and
Example 1: "--...--.".
Input: A = 'abcde', B = 'cdeab'
Output: true
Note:
Example 2:
Input: A = 'abcde', B = 'abced' The length of words will be at most 100.
Output: false Each words[i] will have length in range [1, 12].
Note: words[i] will only consist of lowercase letters.
112)Most Common Word
A and B will have length at most 100. Given a paragraph and a list of banned words,
return the most frequent word that is not in the
111)Unique Morse Code Words list of banned words. It is guaranteed there is at
International Morse Code defines a standard least one word that isn't banned, and that the
encoding where each letter is mapped to a series answer is unique.
of dots and dashes, as follows: "a" maps to ".-",
"b" maps to "-...", "c" maps to "-.-.", and so on. Words in the list of banned words are given in
lowercase, and free of punctuation. Words in the
For convenience, the full table for the 26 letters paragraph are not case sensitive. The answer is
of the English alphabet is given below: in lowercase.
58
Input: S = "a1b2"
Example: Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
Input:
paragraph = "Bob hit a ball, the hit BALL flew far Input: S = "3z4"
after it was hit." Output: ["3z4", "3Z4"]
banned = ["hit"]
Output: "ball" Input: S = "12345"
Explanation: Output: ["12345"]
"hit" occurs 3 times, but it is a banned word. Note:
"ball" occurs twice (and no other word does), so
it is the most frequent non-banned word in the S will be a string with length at most 12.
paragraph. S will consist only of letters or digits.
Note that words in the paragraph are not case
sensitive, 114)Rotated Digits
that punctuation is ignored (even if adjacent to X is a good number if after rotating each digit
words, such as "ball,"), individually by 180 degrees, we get a valid
and that "hit" isn't the answer even though it number that is different from X. Each digit must
occurs more because it is banned. be rotated - we cannot choose to leave it alone.

A number is valid if each digit remains a digit


Note: after rotation. 0, 1, and 8 rotate to themselves; 2
and 5 rotate to each other; 6 and 9 rotate to each
1 <= paragraph.length <= 1000. other, and the rest of the numbers do not rotate
1 <= banned.length <= 100. to any other number and become invalid.
1 <= banned[i].length <= 10.
The answer is unique, and written in lowercase Now given a positive number N, how many
(even if its occurrences in paragraph may have numbers X from 1 to N are good?
uppercase symbols, and even if it is a proper
noun.) Example:
paragraph only consists of letters, spaces, or the Input: 10
punctuation symbols !?',;. Output: 4
Different words in paragraph are always Explanation:
separated by a space. There are four good numbers in the range [1, 10]
There are no hyphens or hyphenated words. : 2, 5, 6, 9.
Words only consist of letters, never apostrophes Note that 1 and 10 are not good numbers, since
or other punctuation symbols. they remain unchanged after rotating.
Note:
113)Letter Case Permutation
Given a string S, we can transform every letter N will be in range [1, 10000].
individually to be lowercase or uppercase to 114) Shortest Distance to a Character
create another string. Return a list of all possible Given a string S and a character C, return an array
strings we could create. of integers representing the shortest distance
from the character C in the string.
Examples:
59
Example 1:
116)Flipping an Image
Input: S = "loveleetcode", C = 'e' Given a binary matrix A, we want to flip the
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] image horizontally, then invert it, and return the
resulting image.

Note: To flip an image horizontally means that each row


of the image is reversed. For example, flipping [1,
S string length is in [1, 10000]. 1, 0] horizontally results in [0, 1, 1].
C is a single character, and guaranteed to be in
string S. To invert an image means that each 0 is replaced
All letters in S and C are lowercase. by 1, and each 1 is replaced by 0. For example,
inverting [0, 1, 1] results in [1, 0, 0].
115)Positions of Large Groups
In a string S of lowercase letters, these letters Example 1:
form consecutive groups of the same character.
Input: [[1,1,0],[1,0,1],[0,0,0]]
For example, a string like S = "abbxxxxzyy" has Output: [[1,0,0],[0,1,0],[1,1,1]]
the groups "a", "bb", "xxxx", "z" and "yy". Explanation: First reverse each row:
[[0,1,1],[1,0,1],[0,0,0]].
Call a group large if it has 3 or more characters. Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
We would like the starting and ending positions Example 2:
of every large group.
Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
The final answer should be in lexicographic order. Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row:
[[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the image:
Example 1: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Notes:
Input: "abbxxxxzzy"
Output: [[3,6]] 1 <= A.length = A[0].length <= 20
Explanation: "xxxx" is the single large group with 0 <= A[i][j] <= 1
starting 3 and ending positions 6.
Example 2: 117)Jewels and Stones
You're given strings J representing the types of
Input: "abc" stones that are jewels, and S representing the
Output: [] stones you have. Each character in S is a type of
Explanation: We have "a","b" and "c" but no large stone you have. You want to know how many of
group. the stones you have are also jewels.
Example 3:
The letters in J are guaranteed distinct, and all
Input: "abcdddeeeeaabbbcd" characters in J and S are letters. Letters are case
Output: [[3,5],[6,9],[12,14]]
60
sensitive, so "a" is considered a different type of
stone from "A". Input: The root of a Binary Search Tree like this:
5
Example 1: / \
2 13
Input: J = "aA", S = "aAAbbbb"
Output: 3 Output: The root of a Greater Tree like this:
Example 2: 18
/ \
Input: J = "z", S = "ZZ" 20 13
Output: 0 120)Leaf-Similar Trees
Note: Consider all the leaves of a binary tree. From left
to right order, the values of those leaves form a
S and J will consist of letters and have length at leaf value sequence.
most 50.
The characters in J are distinct.

118)Average of Levels in Binary Tree For example, in the given tree above, the leaf
Given a non-empty binary tree, return the value sequence is (6, 7, 4, 9, 8).
average value of the nodes on each level in the
form of an array. Two binary trees are considered leaf-similar if
Example 1: their leaf value sequence is the same.
Input:
3 Return true if and only if the two given trees with
/\ head nodes root1 and root2 are leaf-similar.
9 20
/ \
15 7
Output: [3, 14.5, 11] Note:
Explanation:
The average value of nodes on level 0 is 3, on Both of the given trees will have between 1 and
level 1 is 14.5, and on level 2 is 11. Hence return 100 nodes.
[3, 14.5, 11].
Note: 121)Maximize Distance to Closest Person
The range of node's value is in the range of 32-bit In a row of seats, 1 represents a person sitting in
signed integer. that seat, and 0 represents that the seat is empty.

119)Convert BST to Greater Tree There is at least one empty seat, and at least one
Given a Binary Search Tree (BST), convert it to a person sitting.
Greater Tree such that every key of the original
BST is changed to the original key plus sum of all Alex wants to sit in the seat such that the
keys greater than the original key in BST. distance between him and the closest person to
him is maximized.
Example:
61
Return that maximum distance to closest person. Note that we returned a ListNode object ans,
such that:
Example 1: ans.val = 3, ans.next.val = 4, ans.next.next.val = 5,
and ans.next.next.next = NULL.
Input: [1,0,0,0,1,0,1] Example 2:
Output: 2
Explanation: Input: [1,2,3,4,5,6]
If Alex sits in the second open seat (seats[2]), Output: Node 4 from this list (Serialization:
then the closest person has distance 2. [4,5,6])
If Alex sits in any other open seat, the closest Since the list has two middle nodes with values 3
person has distance 1. and 4, we return the second one.
Thus, the maximum distance to the closest
person is 2.
Example 2: Note:

Input: [1,0,0,0] The number of nodes in the given list will be


Output: 3 between 1 and 100.
Explanation:
If Alex sits in the last seat, the closest person is 3 123)Lemonade Change
seats away. At a lemonade stand, each lemonade costs $5.
This is the maximum distance possible, so the
answer is 3. Customers are standing in a queue to buy from
Note: you, and order one at a time (in the order
specified by bills).
1 <= seats.length <= 20000
seats contains only 0s or 1s, at least one 0, and at Each customer will only buy one lemonade and
least one 1. pay with either a $5, $10, or $20 bill. You must
provide the correct change to each customer, so
122)Middle of the Linked List that the net transaction is that the customer pays
Given a non-empty, singly linked list with head $5.
node head, return a middle node of linked list.
Note that you don't have any change in hand at
If there are two middle nodes, return the second first.
middle node.
Return true if and only if you can provide every
customer with correct change.

Example 1:

Input: [1,2,3,4,5] Example 1:


Output: Node 3 from this list (Serialization:
[3,4,5]) Input: [5,5,5,10,20]
The returned node has value 3. (The judge's Output: true
serialization of this node is [3,4,5]). Explanation:
62
From the first 3 customers, we collect three $5 Output: "dc-ba"
bills in order. Example 2:
From the fourth customer, we collect a $10 bill
and give back a $5. Input: "a-bC-dEf-ghIj"
From the fifth customer, we give a $10 bill and a Output: "j-Ih-gfE-dCba"
$5 bill. Example 3:
Since all customers got correct change, we output
true. Input: "Test1ng-Leet=code-Q!"
Example 2: Output: "Qedo1ct-eeLg=ntse-T!"

Input: [5,5,10]
Output: true Note:
Example 3:
S.length <= 100
Input: [10,10] 33 <= S[i].ASCIIcode <= 122
Output: false S doesn't contain \ or "
Example 4:
Medium Level
Input: [5,5,10,10,20]
Output: false 1)**Integer to Roman**
Explanation: Given an integer, convert it to a roman numeral.
From the first two customers in order, we collect Input is guaranteed to be within the range from 1
two $5 bills. to 3999.
For the next two customers in order, we collect a
$10 bill and give back a $5 bill. 2)**Path Sum II**
For the last customer, we can't give change of Given a binary tree and a sum, find all root-to-leaf
$15 back because we only have two $10 bills. paths where each path's sum equals the given
Since not every customer received correct sum.
change, the answer is false.
3)**Kth Largest Element in an Array**
Find the kth largest element in an unsorted array.
Note: Note that it is the kth largest element in the
sorted order, not the kth distinct element.
0 <= bills.length <= 10000 For example,
bills[i] will be either 5, 10, or 20. Given [3,2,1,5,6,4] and k = 2, return 5.
124)Reverse Only Letters
Given a string S, return the "reversed" string 4)**Missing Number**
where all characters that are not a letter stay in Given an array containing n distinct numbers
the same place, and all letters reverse their taken from 0, 1, 2, ..., n, find the one that is
positions. missing from the array.
For example,
Example 1: Given nums = [0, 1, 3] return 2.
Note:
Input: "ab-cd"
63
Your algorithm should run in linear runtime 1
complexity. Could you implement it using only /\
constant extra space complexity? 2 3
The root-to-leaf path 1->2 represents the number
5)**Count Complete Tree Nodes** 12.
Given a complete binary tree, count the number The root-to-leaf path 1->3 represents the number
of nodes. 13.
Definition of a complete binary tree from Return the sum = 12 + 13 = 25.
Wikipedia:
In a complete binary tree every level, except 9) **Path Sum II**
possibly the last, is completely filled, and all Given a binary tree and a sum, find all root-to-leaf
nodes in the last level are as far left as possible. It paths where each path's sum equals the given
can have between 1 and 2h nodes inclusive at the sum.
last level h. For example:
Given the below binary tree and sum = 22,
6)**Minimum Path Sum** 5
Given a m x n grid filled with non-negative /\
numbers, find a path from top left to bottom 4 8
right which minimizes the sum of all numbers / /\
along its path. 11 13 4
Note: You can only move either down or right at / \ /\
any point in time. 7 2 5 1
return
7)**Find Peak Element** [
A peak element is an element that is greater than [5,4,11,2],
its neighbors. [5,8,4,5]
Given an input array where num[i] ≠ num[i+1], ]
find a peak element and return its index.
The array may contain multiple peaks, in that 10) **Minimum Size Subarray Sum**
case return the index to any one of the peaks is Given an array of n positive integers and a
fine. positive integer s, find the minimal length of a
You may imagine that num[-1] = num[n] = -∞. subarray of which the sum ≥ s. If there isn't one,
For example, in array [1, 2, 3, 1], 3 is a peak return 0 instead.
element and your function should return the For example, given the array [2,3,1,2,4,3] and s =
index number 2. 7,
the subarray [4,3] has the minimal length under
8) **Sum Root to Leaf Numbers** the problem constraint.
Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a 11) **Find Minimum in Rotated Sorted Array**
number. Suppose a sorted array is rotated at some pivot
An example is the root-to-leaf path 1->2->3 which unknown to you beforehand.
represents the number 123. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the total sum of all root-to-leaf numbers. Find the minimum element.
For example, You may assume no duplicate exists in the array.
64
Given a singly linked list, group all odd nodes
12)**3Sum** together followed by the even nodes. Please note
Given an array S of n integers, are there elements here we are talking about the node number and
a, b, c in S such that a + b + c = 0? Find all unique not the value in the nodes.
triplets in the array which gives the sum of zero. You should try to do it in place. The program
Note: The solution set must not contain duplicate should run in O(1) space complexity and O(nodes)
triplets. time complexity.
For example, given array S = [-1, 0, 1, 2, -1, -4], Example:
A solution set is: Given 1->2->3->4->5->NULL,
[ return 1->3->5->2->4->NULL.
[-1, 0, 1], Note:
[-1, -1, 2] The relative order inside both the even and odd
] groups should remain as it was in the input.
The first node is considered odd, the second node
13)**H-Index** even and so on ...
Given an array of citations (each citation is a non-
negative integer) of a researcher, write a function 17)**Add Two Numbers**
to compute the researcher's h-index. You are given two linked lists representing two
According to the definition of h-index on non-negative numbers. The digits are stored in
Wikipedia: "A scientist has index h if h of his/her reverse order and each of their nodes contain a
N papers have at least h citations each, and the single digit. Add the two numbers and return it as
other N − h papers have no more than h citations a linked list.
each."
For example, given citations = [3, 0, 6, 1, 5], which 18)**Add Two Numbers II**
means the researcher has 5 papers in total and You are given two linked lists representing two
each of them had received 3, 0, 6, 1, 5 citations non-negative numbers. The most significant digit
respectively. Since the researcher has 3 papers comes first and each of their nodes contain a
with at least 3 citations each and the remaining single digit. Add the two numbers and return it as
two with no more than 3 citations each, his h- a linked list.
index is 3. You may assume the two numbers do not contain
Note: If there are several possible values for h, any leading zero, except the number 0 itself.
the maximum one is taken as the h-index. Follow up:
What if you cannot modify the input lists? In
14)**Insertion Sort Linked List** other words, reversing the lists is not allowed.
Example:
15)**Remove Duplicates from Sorted List II** Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Given a sorted linked list, delete all nodes that Output: 7 -> 8 -> 0 -> 7
have duplicate numbers, leaving only distinct
numbers from the original list. 19)**Rotate List**
For example, Given a list, rotate the list to the right by k places,
Given 1->2->3->3->4->4->5, return 1->2->5. where k is non-negative.
Given 1->1->1->2->3, return 2->3. For example:
Given 1->2->3->4->5->NULL and k = 2,
16)**Odd Even Linked List** return 4->5->1->2->3->NULL.
65
Solution solution = new Solution(head);
20)**Maximum Subarray** // getRandom() should return either 1, 2, or 3
Find the contiguous subarray within an array randomly. Each element should have equal
(containing at least one number) which has the probability of returning.
largest sum. solution.getRandom();
For example, given the array [-2,1,-3,4,-1,2,1,-
5,4], 24)**Shuffle an Array**
the contiguous subarray [4,-1,2,1] has the largest Shuffle a set of numbers without duplicates.
sum = 6. Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
21)**Valid Perfect Square** Solution solution = new Solution(nums);
Given a positive integer num, write a function // Shuffle the array [1,2,3] and return its result.
which returns True if num is a perfect square else Any permutation of [1,2,3] must equally likely to
False. be returned.
Note: Do not use any built-in library function such solution.shuffle();
as sqrt. // Resets the array back to its original
configuration [1,2,3].
22)**Product of Array Except Self** solution.reset();
Given an array of n integers where n > 1, nums, // Returns the random shuffling of array [1,2,3].
return an array output such that output[i] is equal solution.shuffle();
to the product of all the elements of nums except
nums[i]. 25)**Serialize and Deserialize BST**
Solve it without division and in O(n). Serialization is the process of converting a data
For example, given [1,2,3,4], return [24,12,8,6]. structure or object into a sequence of bits so that
Follow up: it can be stored in a file or memory buffer, or
Could you solve it with constant space transmitted across a network connection link to
complexity? (Note: The output array does not be reconstructed later in the same or another
count as extra space for the purpose of space computer environment.
complexity analysis.) Design an algorithm to serialize and deserialize a
binary search tree. There is no restriction on how
23)**Linked List Random Node** your serialization/deserialization algorithm
Given a singly linked list, return a random node's should work. You just need to ensure that a
value from the linked list. Each node must have binary search tree can be serialized to a string
the same probability of being chosen. and this string can be deserialized to the original
Follow up: tree structure.
What if the linked list is extremely large and its The encoded string should be as compact as
length is unknown to you? Could you solve this possible.
efficiently without using extra space? Note: Do not use class member/global/static
Example: variables to store states. Your serialize and
// Init a singly linked list [1,2,3]. deserialize algorithms should be stateless.
ListNode head = new ListNode(1);
head.next = new ListNode(2); 26)**Binary Tree Inorder Traversal**
head.next.next = new ListNode(3);
66
Given a binary tree, return the inorder traversal The flattened tree should look like:
of its nodes' values. 1
\
For example: 2
Given binary tree [1,null,2,3], \
1 3
\ \
2 4
/ \
3 5
return [1,3,2]. \
6
Note: Recursive solution is trivial, could you do it 29)**Binary Search Tree Iterator**
iteratively? Implement an iterator over a binary search tree
(BST). Your iterator will be initialized with the
root node of a BST.
27) **Binary Tree Preorder Traversal** Calling next() will return the next smallest
Given a binary tree, return the preorder traversal number in the BST.
of its nodes' values. Note: next() and hasNext() should run in average
O(1) time and uses O(h) memory, where h is the
For example: height of the tree.
Given binary tree {1,#,2,3},
1 30)**Verify Preorder Serialization of a Binary
\ Tree**
2 One way to serialize a binary tree is to use pre-
/ order traversal. When we encounter a non-null
3 node, we record the node's value. If it is a null
return [1,2,3]. node, we record using a sentinel value such as #.
_9_
Note: Recursive solution is trivial, could you do it / \
iteratively? 3 2
/\ /\
28)**Flatten Binary Tree to Linked List** 4 1 # 6
Given a binary tree, flatten it to a linked list in- /\/\ /\
place. #### ##
For example, the above binary tree can be
For example, serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#",
Given where # represents a null node.

1 Given a string of comma separated values, verify


/\ whether it is a correct preorder traversal
2 5 serialization of a binary tree. Find an algorithm
/\ \ without reconstructing the tree.
3 4 6
67
Each comma separated value in the string must Find all the elements that appear twice in this
be either an integer or a character '#' array.
representing null pointer. Could you do it without extra space and in O(n)
runtime?
You may assume that the input format is always Example:
valid, for example it could never contain two Input:
consecutive commas such as "1,,3". [4,3,2,7,8,2,3,1]
Example 1: Output:
"9,3,4,#,#,1,#,#,2,#,6,#,#" [2,3]
Return true
Example 2: 35)**Convert Sorted List to Binary Search Tree**
"1,#" Given a singly linked list where elements are
Return false sorted in ascending order, convert it to a height
Example 3: balanced BST.
"9,#,#,1"
Return false 36) **Validate Binary Search Tree**
Given a binary tree, determine if it is a valid
31) **Top K Frequent Elements** binary search tree (BST).
Given a non-empty array of integers, return the k Assume a BST is defined as follows:
most frequent elements. The left subtree of a node contains only nodes
For example, with keys less than the node's key.
Given [1,1,1,2,2,3] and k = 2, return [1,2]. The right subtree of a node contains only nodes
Note: with keys greater than the node's key.
You may assume k is always valid, 1 ≤ k ≤ number Both the left and right subtrees must also be
of unique elements. binary search trees.
Your algorithm's time complexity must be better
than O(n log n), where n is the array's size. 37)**Convert Sorted Array to Binary Search
Tree**
32) **Merge k Sorted Lists** 38) **Clone Graph**
Clone an undirected graph. Each node in the
33) **Integer Break** graph contains a label and a list of its neighbors.
Given a positive integer n, break it into the sum
of at least two positive integers and maximize the 39)**PeekingIterator**
product of those integers. Return the maximum Given an Iterator class interface with methods:
product you can get. next() and hasNext(), design and implement a
For example, given n = 2, return 1 (2 = 1 + 1); PeekingIterator that support the peek() operation
given n = 10, return 36 (10 = 3 + 3 + 4). -- it essentially peek() at the element that will be
Note: You may assume that n is not less than 2 returned by the next call to next().
and not larger than 58. Here is an example. Assume that the iterator is
initialized to the beginning of the list: [1, 2, 3].
34) Find All Duplicates in an Array Call next() gets you 1, the first element in the list.
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of Now you call peek() and it returns 2, the next
array), some elements appear twice and others element. Calling next() after that still return 2.
appear once.
68
You call next() the final time and it returns 3, the The string S is magical because concatenating the
last element. Calling hasNext() after that should number of contiguous occurrences of characters
return false. '1' and '2' generates the string S itself.
The first few elements of string S is the following:
40)**Reconstruct Original Digits from English** S = "1221121221221121122……"
Given a non-empty string containing an out-of- If we group the consecutive '1's and '2's in S, it
order English representation of digits 0-9, output will be:
the digits in ascending order. 1 22 11 2 1 22 1 22 11 2 11 22 ......
Note: and the occurrences of '1's or '2's in each group
Input contains only lowercase English letters. are:
Input is guaranteed to be valid and can be 12 2 1 1 2 1 2 2 1 2 2 ......
transformed to its original digits. That means You can see that the occurrence sequence above
invalid inputs such as "abc" or "zerone" are not is the S itself.
permitted. Given an integer N as input, return the number of
Input length is less than 50,000. '1's in the first N number in the magical string S.
Example 1: Note: N will not exceed 100,000.
Input: "owoztneoer"
Output: "012" 43)**License Key Formatting**
Example 2: Now you are given a string S, which represents a
Input: "fviefuro" software license key which we would like to
Output: "45" format. The string S is composed of
alphanumerical characters and dashes. The
41) **Binary Tree Zigzag Level Order Traversal** dashes split the alphanumerical characters within
Given a binary tree, return the zigzag level order the string into groups. (i.e. if there are M dashes,
traversal of its nodes' values. (ie, from left to the string is split into M+1 groups). The dashes in
right, then right to left for the next level and the given string are possibly misplaced.
alternate between). We want each group of characters to be of length
For example: K (except for possibly the first group, which could
Given binary tree [3,9,20,null,null,15,7], be shorter, but still must contain at least one
3 character). To satisfy this requirement, we will
/\ reinsert dashes. Additionally, all the lower case
9 20 letters in the string must be converted to upper
/ \ case.
15 7 So, you are given a non-empty string S,
return its zigzag level order traversal as: representing a license key to format, and an
[ integer K. And you need to return the license key
[3], formatted according to the description above.
[20,9], Example 1:
[15,7] Input: S = "2-4A0r7-4k", K = 4
] Output: "24A0-R74K"
42)**Magical String** Explanation: The string S has been split into two
A magical string S consists of only '1' and '2' and parts, each part has 4 characters.
obeys the following rules:
44)**Reverse Linked List II**
69
Reverse a linked list from position m to n. Do it in- 5 4 <---
place and in one-pass. You should return [1, 3, 4].
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4, 49) **Populating Next Right Pointers in Each
return 1->4->3->2->5->NULL. Node**
Note: Given a binary tree
Given m, n satisfy the following condition: class TreeLinkNode {
1 ≤ m ≤ n ≤ length of list. TreeLinkNode left;
TreeLinkNode right;
45)**Sort List** TreeLinkNode next;
Sort a linked list in O(n log n) time using constant int val;
space complexity. }
Populate each next pointer to point to its next
46)**Reverse Words in a String** right node. If there is no next right node, the next
Given an input string, reverse the string word by pointer should be set to NULL.
word. Initially, all next pointers are set to NULL.
For example, Note:
Given s = "the sky is blue", You may only use constant extra space.
return "blue is sky the". You may assume that it is a perfect binary tree
(ie, all leaves are at the same level, and every
47) **Is Subsequence** parent has two children).
Given a string s and a string t, check if s is For example,
subsequence of t. Given the following perfect binary tree,
You may assume that there is only lower case 1
English letters in both s and t. t is potentially a / \
very long (length ~= 500,000) string, and s is a 2 3
short string (<=100). /\ /\
A subsequence of a string is a new string which is 4 5 6 7
formed from the original string by deleting some After calling your function, the tree should look
(can be none) of the characters without like:
disturbing the relative positions of the remaining 1 -> NULL
characters. (ie, "ace" is a subsequence of "abcde" / \
while "aec" is not). 2 -> 3 -> NULL
/\ /\
48)**Binary Tree Right Side View** 4->5->6->7 -> NULL
Given a binary tree, imagine yourself standing on
the right side of it, return the values of the nodes 50)**Remove K Digits**
you can see ordered from top to bottom. Given a non-negative integer num represented as
For example: a string, remove k digits from the number so that
Given the following binary tree, the new number is the smallest possible.
1 <--- Note:
/ \ The length of num is less than 10002 and will be ≥
2 3 <--- k.
\ \ The given num does not contain any leading zero.
70
Example 1: A mapping of digit to letters (just like on the
Input: num = "1432219", k = 3 telephone buttons) is given below.
Output: "1219" Input:Digit string "23"
Explanation: Remove the three digits 4, 3, and 2 Output: ["ad", "ae", "af", "bd", "be", "bf", "cd",
to form the new number 1219 which is the "ce", "cf"].
smallest.
Example 2: 54) **Word Search**
Given a 2D board and a word, find if the word
exists in the grid.
51)**Pow(x, n)** The word can be constructed from letters of
Implement pow(x, n). sequentially adjacent cell, where "adjacent" cells
are those horizontally or vertically neighboring.
52)**Battleships in a Board** The same letter cell may not be used more than
Given an 2D board, count how many different once.
battleships are in it. The battleships are For example,
represented with 'X's, empty slots are Given board =
represented with '.'s. You may assume the [
following rules: ['A','B','C','E'],
You receive a valid board, made of only ['S','F','C','S'],
battleships or empty slots. ['A','D','E','E']
Battleships can only be placed horizontally or ]
vertically. In other words, they can only be made word = "ABCCED", -> returns true,
of the shape 1xN (1 row, N columns) or Nx1 (N word = "SEE", -> returns true,
rows, 1 column), where N can be of any size. word = "ABCB", -> returns false.
At least one horizontal or vertical cell separates
between two battleships - there are no adjacent 55)**Delete Node in a BST**
battleships. Given a root node reference of a BST and a key,
Example: delete the node with the given key in the BST.
X..X Return the root node reference (possibly
...X updated) of the BST.
...X Basically, the deletion can be divided into two
In the above board there are 2 battleships. stages:
Invalid Example: Search for a node to remove.
...X If the node is found, delete the node.
XXXX Note: Time complexity should be O(height of
...X tree).
This is an invalid board that you will not receive -
as battleships will always have a cell separating 56) **Permutations**
between them. Given a collection of distinct numbers, return all
possible permutations.
53)**Letter Combinations of a Phone Number** For example,
Given a digit string, return all possible letter [1,2,3] have the following permutations:
combinations that the number could represent. [
[1,2,3],
71
[1,3,2], If n is even, replace n with n/2.
[2,1,3], If n is odd, you can replace n with either n + 1 or n
[2,3,1], - 1.
[3,1,2], What is the minimum number of replacements
[3,2,1] needed for n to become 1?
] Example 1:
57)4Sum II Input:
Given four lists A, B, C, D of integer values, 8
compute how many tuples (i, j, k, l) there are such Output:
that A[i] + B[j] + C[k] + D[l] is zero. 3
To make problem a bit easier, all A, B, C, D have Explanation:
same length of N where 0 ≤ N ≤ 500. All integers 8 -> 4 -> 2 -> 1
are in the range of -228 to 228 - 1 and the result
is guaranteed to be at most 231 - 1. 60)Linked List Cycle II
Example: Given a linked list, return the node where the
Input: cycle begins. If there is no cycle, return null.
A = [ 1, 2] Note: Do not modify the linked list.
B = [-2,-1]
C = [-1, 2] 61)**Max Consecutive Ones II**
D = [ 0, 2] Given a binary array, find the maximum number
Output: of consecutive 1s in this array if you can flip at
2 most one 0.
Explanation: Example 1:
The two tuples are: Input: [1,0,1,1,0]
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) Output: 4
+ (-1) + 2 = 0 Explanation: Flip the first zero will get the
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) maximum number of consecutive 1s.
+ (-1) + 0 = 0 After flipping, the maximum number of
consecutive 1s is 4.
58)**Gas Station** Note:
There are N gas stations along a circular route, The input array will only contain 0 and 1.
where the amount of gas at station i is gas[i]. The length of input array is a positive integer and
You have a car with an unlimited gas tank and it will not exceed 10,000
costs cost[i] of gas to travel from station i to its
next station (i+1). You begin the journey with an
empty tank at one of the gas stations. 62)**Longest Increasing Subsequence**
Return the starting gas station's index if you can Given an unsorted array of integers, find the
travel around the circuit once, otherwise return - length of longest increasing subsequence.
1. For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
59)**Integer Replacement** The longest increasing subsequence is [2, 3, 7,
Given a positive integer n and you can do 101], therefore the length is 4. Note that there
operations as follow: may be more than one LIS combination, it is only
necessary for you to return the length.
72
Your algorithm should run in O(n2) complexity. Given s =
Follow up: Could you improve it to O(n log n) "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",
time complexity? Return:
["AAAAACCCCC", "CCCCCAAAAA"].
63)Partition List
Given a linked list and a value x, partition it such 66)Sort Colors
that all nodes less than x come before nodes Given an array with n objects colored red, white
greater than or equal to x. or blue, sort them so that objects of the same
You should preserve the original relative order of color are adjacent, with the colors in the order
the nodes in each of the two partitions. red, white and blue.
For example, Here, we will use the integers 0, 1, and 2 to
Given 1->4->3->2->5->2 and x = 3, represent the color red, white, and blue
return 1->2->2->4->3->5. respectively.
Note:
64) Random Pick Index You are not suppose to use the library's sort
Given an array of integers with possible function for this problem.
duplicates, randomly output the index of a given
target number. You can assume that the given 67)Reorder List
target number must exist in the array. Given a singly linked list L: L0→L1→…→Ln-1→Ln,
Note: reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
The array size can be very large. Solution that You must do this in-place without altering the
uses too much extra space will not pass the nodes' values.
judge. For example,
Example: Given {1,2,3,4}, reorder it to {1,4,2,3}.
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums); 68)Path Sum III
// pick(3) should return either index 2, 3, or 4 You are given a binary tree in which each node
randomly. Each index should have equal contains an integer value.
probability of returning. Find the number of paths that sum to a given
solution.pick(3); value.
// pick(1) should return 0. Since in the array only The path does not need to start or end at the root
nums[0] is equal to 1. or a leaf, but it must go downwards (traveling
solution.pick(1); only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the
65)Repeated DNA Sequences values are in the range -1,000,000 to 1,000,000.
All DNA is composed of a series of nucleotides Example:
abbreviated as A, C, G, and T, for example: root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
"ACGAATTCCG". When studying DNA, it is
sometimes useful to identify repeated sequences 10
within the DNA. / \
Write a function to find all the 10-letter-long 5 -3
sequences (substrings) that occur more than once /\ \
in a DNA molecule. 3 2 11
For example, /\ \
73
3 -2 1 11000
00000
Return 3. The paths that sum to 8 are: Answer: 1
1. 5 -> 3
2. 5 -> 2 -> 1 Example 2:
3. -3 -> 11
11000
69)Unique Paths 11000
A robot is located at the top-left corner of a m x n 00100
grid (marked 'Start' in the diagram below). 00011
The robot can only move either down or right at Answer: 3
any point in time. The robot is trying to reach the
bottom-right corner of the grid (marked 'Finish' in 72) Increasing Subsequences
the diagram below). Given an integer array, your task is to find all the
How many possible unique paths are there? different possible increasing subsequences of the
given array, and the length of an increasing
70)Unique Paths II subsequence should be at least 2 .
Follow up for "Unique Paths": Example:
Now consider if some obstacles are added to the Input: [4, 6, 7, 7]
grids. How many unique paths would there be? Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7],
An obstacle and empty space is marked as 1 and [6, 7, 7], [7,7], [4,7,7]]
0 respectively in the grid. Note:
For example, The length of the given array will not exceed 15.
There is one obstacle in the middle of a 3x3 grid The range of integer in the given array is [-
as illustrated below. 100,100].
[ The given array may contain duplicates, and two
[0,0,0], equal integers should also be considered as a
[0,1,0], special case of increasing sequence.
[0,0,0]
] 73)Target Sum
The total number of unique paths is 2. You are given a list of non-negative integers, a1,
a2, ..., an, and a target, S. Now you have 2
71)Number of Islands symbols + and -. For each integer, you should
Given a 2d grid map of '1's (land) and '0's (water), choose one from + and - as its new symbol.
count the number of islands. An island is Find out how many ways to assign symbols to
surrounded by water and is formed by connecting make sum of integers equal to target S.
adjacent lands horizontally or vertically. You may Example 1:
assume all four edges of the grid are all Input: nums is [1, 1, 1, 1, 1], S is 3.
surrounded by water. Output: 5
Explanation:
Example 1: -1+1+1+1+1 = 3
+1-1+1+1+1 = 3
11110 +1+1-1+1+1 = 3
11010 +1+1+1-1+1 = 3
74
+1+1+1+1-1 = 3 The graph contains n nodes which are labeled
There are 5 ways to assign symbols to make the from 0 to n - 1. You will be given the number n
sum of nums be target 3. and a list of undirected edges (each edge is a pair
Note: of labels).
The length of the given array is positive and will You can assume that no duplicate edges will
not exceed 20. appear in edges. Since all edges are undirected,
The sum of elements in the given array will not [0, 1] is the same as [1, 0] and thus will not
exceed 1000. appear together in edges.
Your output answer is guaranteed to be fitted in a Example 1:
32-bit integer. Given n = 4, edges = [[1, 0], [1, 2], [1, 3]]
0
74)Binary Tree Left Side View |
1
75)Summary Ranges /\
Given a sorted integer array without duplicates, 2 3
return the summary of its ranges. return [1]
For example, given [0,1,2,4,5,7], return ["0-
>2","4->5","7"].
78)Course Schedule
76)Subsets II There are a total of n courses you have to take,
Given a collection of integers that might contain labeled from 0 to n - 1.
duplicates, nums, return all possible subsets. Some courses may have prerequisites, for
Note: The solution set must not contain duplicate example to take course 0 you have to first take
subsets. course 1, which is expressed as a pair: [0,1]
For example, Given the total number of courses and a list of
If nums = [1,2,2], a solution is: prerequisite pairs, is it possible for you to finish
[ all courses?
[2], For example:
[1], 2, [[1,0]]
[1,2,2], There are a total of 2 courses to take. To take
[2,2], course 1 you should have finished course 0. So it
[1,2], is possible.
[] 2, [[1,0],[0,1]]
] There are a total of 2 courses to take. To take
course 1 you should have finished course 0, and
77)Minimum Height Trees to take course 0 you should also have finished
For a undirected graph with tree characteristics, course 1. So it is impossible.
we can choose any node as the root. The result Note:
graph is then a rooted tree. Among all possible The input prerequisites is a graph represented by
rooted trees, those with minimum height are a list of edges, not adjacency matrices. Read
called minimum height trees (MHTs). Given such more about how a graph is represented.
a graph, write a function to find all the MHTs and
return a list of their root labels. 79)Course Schedule II
Format
75
There are a total of n courses you have to take,
labeled from 0 to n - 1. Given a board with m by n cells, each cell has an
Some courses may have prerequisites, for initial state live (1) or dead (0). Each cell interacts
example to take course 0 you have to first take with its eight neighbors (horizontal, vertical,
course 1, which is expressed as a pair: [0,1] diagonal) using the following four rules (taken
Given the total number of courses and a list of from the above Wikipedia article):
prerequisite pairs, return the ordering of courses
you should take to finish all courses. Any live cell with fewer than two live neighbors
There may be multiple correct orders, you just dies, as if caused by under-population.
need to return one of them. If it is impossible to Any live cell with two or three live neighbors lives
finish all courses, return an empty array. on to the next generation.
For example: Any live cell with more than three live neighbors
2, [[1,0]] dies, as if by over-population..
There are a total of 2 courses to take. To take Any dead cell with exactly three live neighbors
course 1 you should have finished course 0. So becomes a live cell, as if by reproduction.
the correct course order is [0,1] Write a function to compute the next state (after
4, [[1,0],[2,0],[3,1],[3,2]] one update) of the board given its current state.
There are a total of 4 courses to take. To take
course 3 you should have finished both courses 1 Follow up:
and 2. Both courses 1 and 2 should be taken after Could you solve it in-place? Remember that the
you finished course 0. So one correct course board needs to be updated at the same time: You
order is [0,1,2,3]. Another correct ordering cannot update some cells first and then use their
is[0,2,1,3]. updated values to update other cells.
Note: In this question, we represent the board using a
The input prerequisites is a graph represented by 2D array. In principle, the board is infinite, which
a list of edges, not adjacency matrices. Read would cause problems when the active area
more about how a graph is represented. encroaches the border of the array. How would
you address these problems?
80)Set Matrix Zeroes
Given a m x n matrix, if an element is 0, set its 82)Merge Intervals
entire row and column to 0. Do it in place. Given a collection of intervals, merge all
Follow up: overlapping intervals.
Did you use extra space? For example,
A straight forward solution using O(mn) space Given [1,3],[2,6],[8,10],[15,18],
is probably a bad idea. return [1,6],[8,10],[15,18].
A simple improvement uses O(m + n) space,
but still not the best solution. 83)Find Mode in Binary Search Tree
Could you devise a constant space solution? Given a binary search tree (BST) with duplicates,
find all the mode(s) (the most frequently
81)Game of Life occurred element) in the given BST.
According to the Wikipedia's article: "The Game Assume a BST is defined as follows:
of Life, also known simply as Life, is a cellular The left subtree of a node contains only nodes
automaton devised by the British mathematician with keys less than or equal to the node's key.
John Horton Conway in 1970."
76
The right subtree of a node contains only nodes are only for those repeat numbers, k. For
with keys greater than or equal to the node's key. example, there won't be input like 3a or 2[4].
Both the left and right subtrees must also be Examples:
binary search trees. s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
84)Teemo Attacking
In LLP world, there is a hero called Teemo and his 86)Find Right Interval
attacking can make his enemy Ashe be in Given a set of intervals, for each of the interval i,
poisoned condition. Now, given the Teemo's check if there exists an interval j whose start
attacking ascending time series towards Ashe and point is bigger than or equal to the end point of
the poisoning time duration per Teemo's the interval i, which can be called that j is on the
attacking, you need to output the total time that "right" of i.
Ashe is in poisoned condition. For any interval i, you need to store the minimum
You may assume that Teemo attacks at the very interval j's index, which means that the interval j
beginning of a specific time point, and makes has the minimum start point to build the "right"
Ashe be in poisoned condition immediately. relationship for interval i. If the interval j doesn't
Example 1: exist, store -1 for the interval i. Finally, you need
Input: [1,4], 2 output the stored value of each interval as an
Output: 4 array.
Explanation: At time point 1, Teemo starts Note:
attacking Ashe and makes Ashe be poisoned You may assume the interval's end point is always
immediately. bigger than its start point.
This poisoned status will last 2 seconds until the You may assume none of these intervals have the
end of time point 2. same start point.
And at time point 4, Teemo attacks Ashe again, Example 1:
and causes Ashe to be in poisoned status for Input: [ [1,2] ]
another 2 seconds. Output: [-1]
So you finally need to output 4. Explanation: There is only one interval in the
collection, so it outputs -1.
Example 2:
85)Decode String Input: [ [3,4], [2,3], [1,2] ]
Given an encoded string, return it's decoded Output: [-1, 0, 1]
string. Explanation: There is no satisfied "right" interval
The encoding rule is: k[encoded_string], where for [3,4].
the encoded_string inside the square brackets is For [2,3], the interval [3,4] has minimum-"right"
being repeated exactly k times. Note that k is start point;
guaranteed to be a positive integer. For [1,2], the interval [2,3] has minimum-"right"
You may assume that the input string is always start point.
valid; No extra white spaces, square brackets are
well-formed, etc. 87)Flatten Nested List Iterator
Furthermore, you may assume that the original Given a nested list of integers, implement an
data does not contain any digits and that digits iterator to flatten it.

77
Each element is either an integer, or a list -- bool search(word)
whose elements may also be integers or other search(word) can search a literal word or a
lists. regular expression string containing only letters
Example 1: a-z or .. A . means it can represent any one letter.
Given the list [[1,1],2,[1,1]], For example:
By calling next repeatedly until hasNext returns addWord("bad")
false, the order of elements returned by next addWord("dad")
should be: [1,1,2,1,1]. addWord("mad")
Example 2: search("pad") -> false
Given the list [1,[4,[6]]], search("bad") -> true
By calling next repeatedly until hasNext returns search(".ad") -> true
false, the order of elements returned by next search("b..") -> true
should be: [1,4,6]. Note:
You may assume that all words are consist of
88)Mini Parser lowercase letters a-z.
Given a nested list of integers represented as a
string, implement a parser to deserialize it. 90) Implement Trie (Prefix Tree)
Each element is either an integer, or a list -- Implement a trie with insert, search, and
whose elements may also be integers or other startsWith methods.
lists. Note:
Note: You may assume that the string is well- You may assume that all inputs are consist of
formed: lowercase letters a-z.
String is non-empty.
String does not contain white spaces. 91)Rotate Image
String contains only digits 0-9, [, - ,, ]. You are given an n x n 2D matrix representing an
Example 1: image.
Given s = "324",
You should return a NestedInteger object which Rotate the image by 90 degrees (clockwise).
contains a single integer 324.
Example 2: Follow up:
Given s = "[123,[456,[789]]]", Could you do this in-place?
Return a NestedInteger object containing a
nested list with 2 elements: 92)Search a 2D Matrix
1. An integer containing value 123. Write an efficient algorithm that searches for a
2. A nested list containing two elements: value in an m x n matrix. This matrix has the
i. An integer containing value 456. following properties:
ii. A nested list with one element:
a. An integer containing value 789. Integers in each row are sorted from left to right.
The first integer of each row is greater than the
89)Add and Search Word - Data structure design last integer of the previous row.
Design a data structure that supports the For example,
following two operations:
Consider the following matrix:
void addWord(word)
78
[ Given a matrix of m x n elements (m rows, n
[1, 3, 5, 7], columns), return all elements of the matrix in
[10, 11, 16, 20], spiral order.
[23, 30, 34, 50] For example,
] Given the following matrix:
[
93)Search a 2D Matrix II [ 1, 2, 3 ],
Write an efficient algorithm that searches for a [ 4, 5, 6 ],
value in an m x n matrix. This matrix has the [ 7, 8, 9 ]
following properties: ]
You should return [1,2,3,6,9,8,7,4,5].
Integers in each row are sorted in ascending from
left to right. 97)Spiral Matrix II
Integers in each column are sorted in ascending Given an integer n, generate a square matrix
from top to bottom. filled with elements from 1 to n2 in spiral order.
For example,
For example,
Consider the following matrix: Given n = 3,

[ You should return the following matrix:


[1, 4, 7, 11, 15], [
[2, 5, 8, 12, 19], [ 1, 2, 3 ],
[3, 6, 9, 16, 22], [ 8, 9, 4 ],
[10, 13, 14, 17, 24], [ 7, 6, 5 ]
[18, 21, 23, 26, 30] ]
] 98) Search in Rotated Sorted Array
94)Evaluate Reverse Polish Notation Suppose an array sorted in ascending order is
Evaluate the value of an arithmetic expression in rotated at some pivot unknown to you
Reverse Polish Notation. beforehand.
Valid operators are +, -, *, /. Each operand may (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
be an integer or another expression. You are given a target value to search. If found in
Some examples: the array return its index, otherwise return -1.
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 You may assume no duplicate exists in the array.
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
99) Search in Rotated Sorted Array II
95)Valid Sudoku Follow up for "Search in Rotated Sorted Array":
Determine if a Sudoku is valid, according to: What if duplicates are allowed?
Sudoku Puzzles - The Rules. Would this affect the run-time complexity? How
A valid Sudoku board (partially filled) is not and why?
necessarily solvable. Only the filled cells need to Suppose an array sorted in ascending order is
be validated. rotated at some pivot unknown to you
beforehand.
96)Spiral Matrix (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

79
Write a function to determine if a given target is /\ \
in the array. 5 3 9
The array may contain duplicates.
Output: [1, 3, 9]
100)Word Ladder
Given two words (beginWord and endWord), and 102)Find Left Most Element
a dictionary's word list, find the length of shortest Given a binary tree, find the leftmost value in the
transformation sequence from beginWord to last row of the tree.
endWord, such that:
Example 1:
Only one letter can be changed at a time. Input:
Each transformed word must exist in the word
list. Note that beginWord is not a transformed 2
word. /\
For example, 1 3

Given: Output:
beginWord = "hit" 1
endWord = "cog" Example 2:
wordList = ["hot","dot","dog","lot","log","cog"] Input:
As one shortest transformation is "hit" -> "hot" ->
"dot" -> "dog" -> "cog", 1
return its length 5. /\
2 3
Note: / /\
Return 0 if there is no such transformation 4 5 6
sequence. /
All words have the same length. 7
All words contain only lowercase alphabetic
characters. Output: 7
You may assume no duplicates in the word list.
You may assume beginWord and endWord are 103)Jump Game
non-empty and are not the same. Given an array of non-negative integers, you are
initially positioned at the first index of the array.
101)Find Largest Element in Each Row Each element in the array represents your
You need to find the largest value in each row of maximum jump length at that position.
a binary tree. Determine if you are able to reach the last index.
For example:
Example: A = [2,3,1,1,4], return true.
Input: A = [3,2,1,0,4], return false.

1 104)Triangle
/\
3 2
80
Given a triangle, find the minimum path sum
from top to bottom. Each step you may move to Example 1:
adjacent numbers on the row below. Input:
s = "abpcplea", d =
For example, given the following triangle ["ale","apple","monkey","plea"]
[
[2], Output:
[3,4], "apple"
[6,5,7], Example 2:
[4,1,8,3] Input:
] s = "abpcplea", d = ["a","b","c"]
The minimum path sum from top to bottom is 11
(i.e., 2 + 3 + 5 + 1 = 11). Output:
Bonus point if you are able to do this using only "a"
O(n) extra space, where n is the total number of 106)Lowest Common Ancestor of Binary Tree
rows in the triangle. Given a binary tree, find the lowest common
ancestor (LCA) of two given nodes in the tree.

105)Continuous Subarray Sum According to the definition of LCA on Wikipedia:


Given a list of non-negative numbers and a target “The lowest common ancestor is defined
integer k, write a function to check if the array between two nodes v and w as the lowest node
has a continuous subarray of size at least 2 that in T that has both v and w as descendants (where
sums up to the multiple of k, that is, sums up to we allow a node to be a descendant of itself).”
n*k where n is also an integer.
_______3______
Example 1: / \
Input: [23, 2, 4, 6, 7], k=6 ___5__ ___1__
Output: True / \ / \
Explanation: Because [2, 4] is a continuous 6 _2 0 8
subarray of size 2 and sums up to 6. / \
Example 2: 7 4
Input: [23, 2, 6, 4, 7], k=6 For example, the lowest common ancestor (LCA)
Output: True of nodes 5 and 1 is 3. Another example is LCA of
Explanation: Because [23, 2, 6, 4, 7] is an nodes 5 and 4 is 5, since a node can be a
continuous subarray of size 5 and sums up to 42. descendant of itself according to the LCA
definition
106) Longest Word in Dictionary through Deleting
Given a string and a string dictionary, find the 107)Compare Version Numbers
longest string in the dictionary that can be Compare two version numbers version1 and
formed by deleting some characters of the given version2.
string. If there are more than one possible results, If version1 > version2 return 1, if version1 <
return the longest word with the smallest version2 return -1, otherwise return 0.
lexicographical order. If there is no possible
result, return the empty string.
81
You may assume that the version strings are non- Output: 3
empty and contain only digits and the . character. Explanation: All the three 'B's are black lonely
The . character does not represent a decimal pixels.
point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half 110) Calculate Diameter of Binary tree.
way to version three", it is the fifth second-level
revision of the second first-level revision. 111)Construct Binary Tree From String
You need to construct a binary tree from a string
Here is an example of version numbers ordering: consisting of parenthesis and integers.

0.1 < 1.1 < 1.2 < 13.37 The whole input represents a binary tree. It
contains an integer followed by zero, one or two
108)Word Break pairs of parenthesis. The integer represents the
Given a non-empty string s and a dictionary root's value and a pair of parenthesis contains a
wordDict containing a list of non-empty words, child binary tree with the same structure.
determine if s can be segmented into a space-
separated sequence of one or more dictionary You always start to construct the left child node
words. You may assume the dictionary does not of the parent first if it exists.
contain duplicate words.
For example, given Example:
s = "leetcode", Input: "4(2(3)(1))(6(5))"
dict = ["leet", "code"]. Output: return the tree root node representing
Return true because "leetcode" can be the following tree:
segmented as "leet code".
4
/ \
109)Lonely Pixel I 2 6
Given a picture consisting of black and white /\ /
pixels, find the number of black lonely pixels. 3 15
Note:
The picture is represented by a 2D char array There will only be '(', ')', '-' and '0' ~ '9' in the
consisting of 'B' and 'W', which means black and input string.
white pixels respectively. An empty tree is represented by "" instead of "()".

A black lonely pixel is character 'B' that located at 112)Convert BST to Greater Tree
a specific position where the same row and same Given a Binary Search Tree (BST), convert it to a
column don't have any other black pixels. Greater Tree such that every key of the original
BST is changed to the original key plus sum of all
Example: keys greater than the original key in BST.
Input:
[['W', 'W', 'B'], Example:
['W', 'B', 'W'],
['B', 'W', 'W']] Input: The root of a Binary Search Tree like this:
5
82
/ \
2 13 Example:
Input:
Output: The root of a Greater Tree like this: [[1,2,2,1],
18 [3,1,2],
/ \ [1,3,2],
20 13 [2,4],
113)Non-overlapping Intervals [3,1,2],
Given a collection of intervals, find the minimum [1,3,1,1]]
number of intervals you need to remove to make Output: 2
the rest of the intervals non-overlapping. Note:
The width sum of bricks in different rows are the
Note: same and won't exceed INT_MAX.
You may assume the interval's end point is always The number of bricks in each row is in range
bigger than its start point. [1,10,000]. The height of wall is in range
Intervals like [1,2] and [2,3] have borders [1,10,000]. Total number of bricks of the wall
"touching" but they don't overlap each other. won't exceed 20,000.
Example 1:
Input: [ [1,2], [2,3], [3,4], [1,3] ] 115)Next Greater Element III
Given a positive 32-bit integer n, you need to find
Output: 1 the smallest 32-bit integer which has exactly the
same digits existing in the integer n and is greater
Explanation: [1,3] can be removed and the rest of in value than n. If no such positive 32-bit integer
intervals are non-overlapping. exists, you need to return -1.
Example 1:
114)Brick Wall Input: 12
There is a brick wall in front of you. The wall is Output: 21
rectangular and has several rows of bricks. The Example 2:
bricks have the same height but different width. Input: 21
You want to draw a vertical line from the top to Output: -1
the bottom and cross the least bricks.
116)
The brick wall is represented by a list of rows. Given a binary tree, find the largest subtree
Each row is a list of integers representing the which is a Binary Search Tree (BST), where largest
width of each brick in this row from left to right. means subtree with largest number of nodes in it.

If your line go through the edge of a brick, then Note:


the brick is not considered as crossed. You need A subtree must include all of its descendants.
to find out how to draw the line to cross the least Here's an example:
bricks and return the number of crossed bricks. 10
/\
You cannot draw a line just along one of the two 5 15
vertical edges of the wall, in which case the line /\ \
will obviously cross no bricks. 1 8 7
83
The Largest BST Subtree in this case is the
highlighted one. Given word1 = “makes”, word2 = “coding”, return
The return value is the subtree's size, which is 3. 1.
Follow up: Given word1 = "makes", word2 = "makes", return
Can you figure out ways to solve it with O(n) time 3.
complexity?
Note:
117)Shortest Word Distance II You may assume word1 and word2 are both in
This is a follow up of Shortest Word Distance. The the list.
only difference is now you are given the list of
words and your method will be called repeatedly 119)Meta Strings
many times with different parameters. How Given two strings, the task is to check whether
would you optimize it? these strings are meta strings or not. Meta strings
are the strings which can be made equal by
Design a class which receives a list of words in the exactly one swap in any of the strings.
constructor, and implements a method that takes Equal string are not considered here as Meta
two words word1 and word2 and return the strings.
shortest distance between these two words in Input : str1 = "geeks"
the list. str2 = "keegs"
Output : Yes
For example, By just swapping 'k' and 'g' in any of string,
Assume that words = ["practice", "makes", both will become same.
"perfect", "coding", "makes"].
Input : str1 = "rsting"
Given word1 = “coding”, word2 = “practice”, str2 = "string
return 3. Output : No
Given word1 = "makes", word2 = "coding", return
1. Input : str1 = "Converse"
str2 = "Conserve"
118)Shortest Word Distance 3 Output Yes
This is a follow up of Shortest Word Distance. The
only difference is now word1 could be the same 120)Longest Absolute File Path
as word2. Suppose we abstract our file system by a string in
the following manner:
Given a list of words and two words word1 and
word2, return the shortest distance between The string
these two words in the list. "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
represents:
word1 and word2 may be the same and they
represent two individual words in the list. dir
subdir1
For example, subdir2
Assume that words = ["practice", "makes", file.ext
"perfect", "coding", "makes"].
84
The directory dir contains an empty sub-directory empty list if no palindromic permutation could be
subdir1 and a sub-directory subdir2 containing a form.
file file.ext.
For example:
The string
"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\t Given s = "aabb", return ["abba", "baab"].
subdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
represents: Given s = "abc", return [].

dir 122)Next Permutation


subdir1 Total Accepted: 104657
file1.ext Total Submissions: 366915
subsubdir1 Difficulty: Medium
subdir2 Contributor: LeetCode
subsubdir2 Implement next permutation, which rearranges
file2.ext numbers into the lexicographically next greater
The directory dir contains two sub-directories permutation of numbers.
subdir1 and subdir2. subdir1 contains a file
file1.ext and an empty second-level sub-directory If such arrangement is not possible, it must
subsubdir1. subdir2 contains a second-level sub- rearrange it as the lowest possible order (ie,
directory subsubdir2 containing a file file2.ext. sorted in ascending order).

We are interested in finding the longest (number The replacement must be in-place, do not
of characters) absolute path to a file within our allocate extra memory.
file system. For example, in the second example
above, the longest absolute path is Here are some examples. Inputs are in the left-
"dir/subdir2/subsubdir2/file2.ext", and its length hand column and its corresponding outputs are in
is 32 (not including the double quotes). the right-hand column.
1,2,3 → 1,3,2
Given a string representing the file system in the 3,2,1 → 1,2,3
above format, return the length of the longest 1,1,5 → 1,5,1
absolute path to file in the abstracted file system.
If there is no file in the system, return 0. 123)Permutations II
Given a collection of numbers that might contain
Note: duplicates, return all possible unique
The name of a file contains at least a . and an permutations.
extension.
The name of a directory or sub-directory will not For example,
contain a . [1,1,2] have the following unique permutations:
[
121)Palindrome Permutation II [1,1,2],
Given a string s, return all the palindromic [1,2,1],
permutations (without duplicates) of it. Return an [2,1,1]
]
85
Show Company Tags Implement an algorithm to print all valid (e.g.,
Show Tags properly opened and closed) combinations
Show Similar Problems of n pairs of parentheses.
EXAMPLE
124)Stack of Piles Input: 3
Imagine a (literal) stack of plates. If the stack gets Output: ( ( () ) ) , ( () () ) , ( () ) () , () ( () ) , () () ()
too high, it might topple.
Therefore, in real life, we would likely start a new 128)Alien Alphabet
stack when the previous stack exceeds some Given dictionary of alien language. You need to
threshold. Implement a data structure find order of alphabets based on dictionary
SetOfStacks that mimics this. SetO-fStacks should
be 129)Flatten a Dictionary
composed of several stacks and should create a A dictionary is a type of data structure that is
new stack once the previous one exceeds supported natively in all major interpreted
capacity. languages such as JavaScript, Python, Ruby and
SetOfStacks. push() and SetOfStacks. pop() should PHP, where it’s known as an Object, Dictionary,
behave identically to a single stack Hash and Array, respectively. In simple terms, a
(that is, pop () should return the same values as it dictionary is a collection of unique keys and their
would if there were just a single stack). values. The values can typically be of any
FOLLOW UP primitive type (i.e an integer, boolean, double,
Implement a function popAt ( int index) which string etc) or other dictionaries (dictionaries can
performs a pop operation on a specific sub-stack. be nested).

125)Sort Stack Given a dictionary dict, write a function


Write a program to sort a stack such that the flattenDictionary that returns a flattened version
smallest items are on the top. You can use of it .
an additional temporary stack, but you may not
copy the elements into any other data structure If you’re using a compiled language such Java,
(such as an array). The stack supports the C++, C#, Swift and Go, you may want to use a
following operations: push, pop, peek, and is Map/Dictionary/Hash Table that maps strings
Empty. (keys) to a generic type (e.g. Object in Java,
AnyObject in Swift etc.) to allow nested
126)BST Sequences dictionaries.
A binary search tree was created by traversing
through an array from left to right 129)Combination Sum III
and inserting each element. Given a binary search
tree with distinct elements, print all possible Total Accepted: 64870
arrays that could have led to this tree Total Submissions: 147680
For example: Difficulty: Medium
2 1 3 tree Contributor: LeetCode
Output: [[2,1,3], [2,3,1]] Find all possible combinations of k numbers that
add up to a number n, given that only numbers
127)Generate Parenthesis from 1 to 9 can be used and each combination
should be a unique set of numbers.
86
Example 1: with no order requirement. You could assume
Input: k = 3, n = 7 there always exists an answer.
Output:
[[1,2,4]] Example 1:
Example 2: Input:
Input: k = 3, n = 9 ["Shogun", "Tapioca Express", "Burger King",
Output: "KFC"]
[[1,2,6], [1,3,5], [2,3,4]] ["Piatti", "The Grill at Torrey Pines", "Hungry
Hunter Steakhouse", "Shogun"]
130)Array Nesting Output: ["Shogun"]
A zero-indexed array A consisting of N different Explanation: The only restaurant they both like is
integers is given. The array contains all integers in "Shogun".
the range [0, N - 1]. Example 2:
Input:
Sets S[K] for 0 <= K < N are defined as follows: ["Shogun", "Tapioca Express", "Burger King",
"KFC"]
S[K] = { A[K], A[A[K]], A[A[A[K]]], ... }. ["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Sets S[K] are finite for each K and should NOT Explanation: The restaurant they both like and
contain duplicates. have the least index sum is "Shogun" with index
sum 1 (0+1).
Write a function that given an array A consisting Note:
of N integers, return the size of the largest set The length of both lists will be in the range of [1,
S[K] for this array. 1000].
The length of strings in both lists will be in the
Example 1: range of [1, 30].
Input: A = [5,4,0,3,1,6,2] The index is starting from 0 to the list length
Output: 4 minus 1.
Explanation: No duplicates in both lists.
A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5]
= 6, A[6] = 2. 132) Combinations
Given two integers n and k, return all possible
One of the longest S[K]: combinations of k numbers out of 1 ... n.
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
For example,
131)Minimum Index Sum of Two Lists If n = 4 and k = 2, a solution is:
Suppose Andy and Doris want to choose a
restaurant for dinner, and they both have a list of [
favorite restaurants represented by strings. [2,4],
[3,4],
You need to help them find out their common [2,3],
interest with the least list index sum. If there is a [1,2],
choice tie between answers, output all of them [1,3],
[1,4],
87
] The number of files given is in the range of
133)Find Duplicate File in System [1,20000].
Given a list of directory info including directory You may assume no files or directories share the
path, and all the files with contents in this same name in a same directory.
directory, you need to find out all the groups of You may assume each given directory info
duplicate files in the file system in terms of their represents a unique directory. Directory path and
paths. file infos are separated by a single blank space.
Follow up beyond contest:
A group of duplicate files consists of at least two Imagine you are given a real file system, how will
files that have exactly the same content. you search files? DFS or BFS ?
If the file content is very large (GB level), how will
A single directory info string in the input list has you modify your solution?
the following format: If you can only read the file by 1kb each time,
how will you modify your solution?
"root/d1/d2/.../dm f1.txt(f1_content) What is the time complexity of your modified
f2.txt(f2_content) ... fn.txt(fn_content)" solution? What is the most time consuming part
and memory consuming part of it? How to
It means there are n files (f1.txt, f2.txt ... fn.txt optimize?
with content f1_content, f2_content ... How to make sure the duplicated files you find
fn_content, respectively) in directory are not false positive?
root/d1/d2/.../dm. Note that n >= 1 and m >= 0. If
m = 0, it means the directory is just the root 134)Coin Change
directory. You are given coins of different denominations
and a total amount of money amount. Write a
The output is a list of group of duplicate file function to compute the fewest number of coins
paths. For each group, it contains all the file paths that you need to make up that amount. If that
of the files that have the same content. A file amount of money cannot be made up by any
path is a string that has the following format: combination of the coins, return -1.

"directory_path/file_name.txt" Example 1:
coins = [1, 2, 5], amount = 11
Example 1: return 3 (11 = 5 + 5 + 1)
Input:
["root/a 1.txt(abcd) 2.txt(efgh)", "root/c Example 2:
3.txt(abcd)", "root/c/d 4.txt(efgh)", "root coins = [2], amount = 3
4.txt(efgh)"] return -1.
Output:
[["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["ro Note:
ot/a/1.txt","root/c/3.txt"]] You may assume that you have an infinite
Note: number of each kind of coin.
No order is required for the final output.
You may assume the directory name, file name 135)Maximum Binary Tree
and file content only has letters and digits, and
the length of file content is in the range of [1,50].
88
Given an integer array with no duplicates. A Input:
maximum tree building on this array is defined as
follow: 1
/ \
The root is the maximum number in the array. 3 2
The left subtree is the maximum tree constructed /\ \
from left part subarray divided by the maximum 5 3 9
number.
The right subtree is the maximum tree Output: 4
constructed from right part subarray divided by Explanation: The maximum width existing in the
the maximum number. third level with the length 4 (5,3,null,9).
Construct the maximum tree by the given array Example 2:
and output the root node of this tree. Input:

Example 1: 1
Input: [3,2,1,6,0,5] /
Output: return the tree root node representing 3
the following tree: /\
5 3
6
/ \ Output: 2
3 5 Explanation: The maximum width existing in the
\ / third level with the length 2 (5,3).
2 0 Example 3:
\ Input:
1
Note: 1
The size of the given array will be in the range /\
[1,1000]. 3 2
/
136) Maximum Width of Binary Tree 5
Given a binary tree, write a function to get the
maximum width of the given tree. The width of a Output: 2
tree is the maximum width among all levels. The Explanation: The maximum width existing in the
binary tree has the same structure as a full binary second level with the length 2 (3,2).
tree, but some nodes are null. Example 4:
Input:
The width of one level is defined as the length
between the end-nodes (the leftmost and right 1
most non-null nodes in the level, where the null /\
nodes between the end-nodes are also counted 3 2
into the length calculation. / \
5 9
Example 1: / \
89
6 7
Output: 8 Output: False
Explanation:The maximum width existing in the Explanation: You can't split the tree into two
fourth level with the length 8 trees with equal sum after removing exactly one
(6,null,null,null,null,null,null,7). edge on the tree.
Note:
The range of tree node value is in the range of [-
Note: Answer will in the range of 32-bit signed 100000, 100000].
integer. 1 <= n <= 10000
Discuss
137) Equal Tree Partition
Given a binary tree with n nodes, your task is to 138) Single Number 2
check if it's possible to partition the tree to two Given an array of integers, every element appears
trees which have the equal sum of values after three times except for one, which appears exactly
removing exactly one edge on the original tree. once. Find that single one.

Example 1: Note:
Input: Your algorithm should have a linear runtime
5 complexity. Could you implement it without using
/\ extra memory?
10 10
/ \ 139)Encode and Decode TinyURL
2 3 TinyURL is a URL shortening service where you
enter a URL such as
Output: True https://leetcode.com/problems/design-tinyurl
Explanation: and it returns a short URL such as
5 http://tinyurl.com/4e9iAk.
/
10 Design the encode and decode methods for the
TinyURL service. There is no restriction on how
Sum: 15 your encode/decode algorithm should work. You
just need to ensure that a URL can be encoded to
10 a tiny URL and the tiny URL can be decoded to
/ \ the original URL.
2 3
140) Palindromic Substrings
Sum: 15 Given a string, your task is to count how many
Example 2: palindromic substrings in this string.
Input:
1 The substrings with different start indexes or end
/\ indexes are counted as different substrings even
2 10 they consist of same characters.
/ \
2 20 Example 1:
90
Input: "abc" Output: 2
Output: 3 Explanation:
Explanation: Three palindromic strings: "a", "b",
"c". The first beautiful arrangement is [1, 2]:
Example 2:
Input: "aaa" Number at the 1st position (i=1) is 1, and 1 is
Output: 6 divisible by i (i=1).
Explanation: Six palindromic strings: "a", "a", "a",
"aa", "aa", "aaa". Number at the 2nd position (i=2) is 2, and 2 is
divisible by i (i=2).
140)Queue Reconstruction by Height
Suppose you have a random list of people The second beautiful arrangement is [2, 1]:
standing in a queue. Each person is described by
a pair of integers (h, k), where h is the height of Number at the 1st position (i=1) is 2, and 2 is
the person and k is the number of people in front divisible by i (i=1).
of this person who have a height greater than or
equal to h. Write an algorithm to reconstruct the Number at the 2nd position (i=2) is 1, and i (i=2) is
queue. divisible by 1.

Note: 142)Friend Circles


The number of people is less than 1,100. There are N students in a class. Some of them are
friends, while some are not. Their friendship is
Example transitive in nature. For example, if A is a direct
friend of B, and B is a direct friend of C, then A is
Input: an indirect friend of C. And we defined a friend
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] circle is a group of students who are direct or
indirect friends.
Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] Given a N*N matrix M representing the friend
relationship between students in the class. If
141) Beautiful Arrangement M[i][j] = 1, then the ith and jth students are direct
Suppose you have N integers from 1 to N. We friends with each other, otherwise not. And you
define a beautiful arrangement as an array that is have to output the total number of friend circles
constructed by these N numbers successfully if among all the students.
one of the following is true for the ith position (1
<= i <= N) in this array: Example 1:
Input:
The number at the ith position is divisible by i. [[1,1,0],
i is divisible by the number at the ith position. [1,1,0],
Now given N, how many beautiful arrangements [0,0,1]]
can you construct? Output: 2
Explanation:The 0th and 1st students are direct
Example 1: friends, so they are in a friend circle.
Input: 2
91
The 2nd student himself is in a friend circle. So 1 <= sentence words length <= 1000
return 2.
Example 2: 144)Counting Bits
Input: Given a non negative integer number num. For
[[1,1,0], every numbers i in the range 0 ≤ i ≤ num calculate
[1,1,1], the number of 1's in their binary representation
[0,1,1]] and return them as an array.
Output: 1
Explanation:The 0th and 1st students are direct Example:
friends, the 1st and 2nd students are direct For num = 5 you should return [0,1,1,2,1,2].
friends,
so the 0th and 2nd students are indirect friends. Follow up:
All of them are in the same friend circle, so return
1. It is very easy to come up with a solution with run
Note: time O(n*sizeof(integer)). But can you do it in
N is in range [1,200]. linear time O(n) /possibly in a single pass?
M[i][i] = 1 for all students. Space complexity should be O(n).
If M[i][j] = 1, then M[j][i] = 1. Can you do it like a boss? Do it without using any
builtin function like __builtin_popcount in c++ or
143) Replace Words in any other language.
In English, we have a concept called root, which
can be followed by some other words to form 145) Find K Closest Elements
another longer word - let's call this word Given a sorted array, two integers k and x, find
successor. For example, the root an, followed by the k closest elements to x in the array. The result
other, which can form another word another. should also be sorted in ascending order. If there
is a tie, the smaller elements are always
Now, given a dictionary consisting of many roots preferred.
and a sentence. You need to replace all the
successor in the sentence with the root forming Example 1:
it. If a successor has many roots can form it, Input: [1,2,3,4,5], k=4, x=3
replace it with the root with the shortest length. Output: [1,2,3,4]
Example 2:
You need to output the sentence after the Input: [1,2,3,4,5], k=4, x=-1
replacement. Output: [1,2,3,4]
Note:
Example 1: The value k is positive and will always be smaller
Input: dict = ["cat", "bat", "rat"] than the length of the sorted array.
sentence = "the cattle was rattled by the battery" Length of the given array is positive and will not
Output: "the cat was rat by the bat" exceed 104
Note: Absolute value of elements in the array and x will
The input will only have lower-case letters. not exceed 104
1 <= dict words number <= 1000
1 <= sentence words number <= 1000 146) Find Duplicate Subtrees
1 <= root length <= 100
92
Given a binary tree, return all duplicate subtrees. Explanation: A -> B -> idle -> A -> B -> idle -> A ->
For each kind of duplicate subtrees, you only B.
need to return the root node of any one of them.
148)Minimum Number of Arrows to Burst
Two trees are duplicate if they have the same Balloons
structure with same node values. There are a number of spherical balloons spread
in two-dimensional space. For each balloon,
Example 1: provided input is the start and end coordinates of
1 the horizontal diameter. Since it's horizontal, y-
/\ coordinates don't matter and hence the x-
2 3 coordinates of start and end of the diameter
/ /\ suffice. Start is always smaller than end. There
4 2 4 will be at most 104 balloons.
/
4 An arrow can be shot up exactly vertically from
The following are two duplicate subtrees: different points along the x-axis. A balloon with
2 xstart and xend bursts by an arrow shot at x if
/ xstart ≤ x ≤ xend. There is no limit to the number
4 of arrows that can be shot. An arrow once shot
and keeps travelling up infinitely. The problem is to
4 find the minimum number of arrows that must be
Therefore, you need to return above trees' root shot to burst all balloons.
in the form of a list.
Example:
147)Task Scheduler
Given a char array representing tasks CPU need Input:
to do. It contains capital letters A to Z where [[10,16], [2,8], [1,6], [7,12]]
different letters represent different tasks.Tasks
could be done without original order. Each task Output:
could be done in one interval. For each interval, 2
CPU could finish one task or just be idle.
Explanation:
However, there is a non-negative cooling interval One way is to shoot one arrow for example at x =
n that means between two same tasks, there 6 (bursting the balloons [2,8] and [1,6]) and
must be at least n intervals that CPU are doing another arrow at x = 11 (bursting the other two
different tasks or just be idle. balloons).

You need to return the least number of intervals 148)Maximum Swap


the CPU will take to finish all the given tasks. Given a non-negative integer, you could swap
two digits at most once to get the maximum
Example 1: valued number. Return the maximum valued
Input: tasks = ['A','A','A','B','B','B'], n = 2 number you could get.
Output: 8
Example 1:
93
Input: 2736
Output: 7236 For the method insert, you'll be given a pair of
Explanation: Swap the number 2 and the number (string, integer). The string represents the key
7. and the integer represents the value. If the key
Example 2: already existed, then the original key-value pair
Input: 9973 will be overridden to the new one.
Output: 9973
Explanation: No swap. For the method sum, you'll be given a string
Note: representing the prefix, and you need to return
The given number is in the range [0, 108] the sum of all the pairs' value whose key starts
with the prefix.
149) Implement Magic Dictionary
Implement a magic directory with buildDict, and Example 1:
search methods. Input: insert("apple", 3), Output: Null
Input: sum("ap"), Output: 3
For the method buildDict, you'll be given a list of Input: insert("app", 2), Output: Null
non-repetitive words to build a dictionary. Input: sum("ap"), Output: 5

For the method search, you'll be given a word, 151)2 Keys Keyboard
and judge whether if you modify exactly one Initially on a notepad only one character 'A' is
character into another character in this word, the present. You can perform two operations on this
modified word is in the dictionary you just built. notepad for each step:

Example 1: Copy All: You can copy all the characters present
Input: buildDict(["hello", "leetcode"]), Output: on the notepad (partial copy is not allowed).
Null Paste: You can paste the characters which are
Input: search("hello"), Output: False copied last time.
Input: search("hhllo"), Output: True Given a number n. You have to get exactly n 'A'
Input: search("hell"), Output: False on the notepad by performing the minimum
Input: search("leetcoded"), Output: False number of steps permitted. Output the minimum
Note: number of steps to get n 'A'.
You may assume that all the inputs are consist of
lowercase letters a-z. Example 1:
For contest purpose, the test data is rather small Input: 3
by now. You could think about highly efficient Output: 3
algorithm after the contest. Explanation:
Please remember to RESET your class variables Intitally, we have one character 'A'.
declared in class MagicDictionary, as static/class In step 1, we use Copy All operation.
variables are persisted across multiple test cases. In step 2, we use Paste operation to get 'AA'.
Please see here for more details. In step 3, we use Paste operation to get 'AAA'.
Note:
150)Map Sum Pairs The n will be in the range [1, 1000].
Implement a MapSum class with insert, and sum
methods.
94
152)Next Closest Time multiple answers, return the answer that occurs
Given a time represented in the format last in the given 2D-array. The answer edge [u, v]
"HH:MM", form the next closest time by reusing should be in the same format, with u < v.
the current digits. There is no limit on how many
times a digit can be reused. Example 1:
Input: [[1,2], [1,3], [2,3]]
You may assume the given input string is always Output: [2,3]
valid. For example, "01:34", "12:09" are all valid. Explanation: The given undirected graph will be
"1:34", "12:9" are all invalid. like this:
1
Example 1: /\
2-3
Input: "19:34" Example 2:
Output: "19:39" Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
Explanation: The next closest time choosing from Output: [1,4]
digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes Explanation: The given undirected graph will be
later. It is not 19:33, because this occurs 23 like this:
hours and 59 minutes later. 5-1-2
Example 2: | |
4-3
Input: "23:59" Note:
Output: "22:22" The size of the input 2D-array will be between 3
Explanation: The next closest time choosing from and 1000.
digits 2, 3, 5, 9, is 22:22. It may be assumed that Every integer represented in the 2D-array will be
the returned time is next day's time since it is between 1 and N, where N is the size of the input
smaller than the input time numerically. array.

153) Redundant Connection 154)Longest Univalue Path


In this problem, a tree is an undirected graph that Given a binary tree, find the length of the longest
is connected and has no cycles. path where each node in the path has the same
value. This path may or may not pass through the
The given input is a graph that started as a tree root.
with N nodes (with distinct values 1, 2, ..., N),
with one additional edge added. The added edge Note: The length of path between two nodes is
has two different vertices chosen from 1 to N, represented by the number of edges between
and was not an edge that already existed. them.

The resulting graph is given as a 2D-array of Example 1:


edges. Each element of edges is a pair [u, v] with
u < v, that represents an undirected edge Input:
connecting nodes u and v.
5
Return an edge that can be removed so that the /\
resulting graph is a tree of N nodes. If there are 4 5
95
/\ \ Explanation:
1 1 5 Employee 1 has importance value 5, and he has
Output: two direct subordinates: employee 2 and
employee 3. They both have importance value 3.
2 So the total importance value of employee 1 is 5
Example 2: + 3 + 3 = 11.
Note:
Input: One employee has at most one direct leader and
may have several subordinates.
1 The maximum number of employees won't
/\ exceed 2000.
4 5
/\ \ 155)Top K Frequent Words
4 4 5 Given a non-empty list of words, return the k
Output: most frequent elements.

2 Your answer should be sorted by frequency from


Note: The given binary tree has not more than highest to lowest. If two words have the same
10000 nodes. The height of the tree is not more frequency, then the word with the lower
than 1000. alphabetical order comes first.

155)Employee Importance Example 1:


You are given a data structure of employee Input: ["i", "love", "leetcode", "i", "love",
information, which includes the employee's "coding"], k = 2
unique id, his importance value and his direct Output: ["i", "love"]
subordinates' id. Explanation: "i" and "love" are the two most
frequent words.
For example, employee 1 is the leader of Note that "i" comes before "love" due to a
employee 2, and employee 2 is the leader of lower alphabetical order.
employee 3. They have importance value 15, 10 Example 2:
and 5, respectively. Then employee 1 has a data Input: ["the", "day", "is", "sunny", "the", "the",
structure like [1, 15, [2]], and employee 2 has [2, "the", "sunny", "is", "is"], k = 4
10, [3]], and employee 3 has [3, 5, []]. Note that Output: ["the", "is", "sunny", "day"]
although employee 3 is also a subordinate of Explanation: "the", "is", "sunny" and "day" are
employee 1, the relationship is not direct. the four most frequent words,
with the number of occurrence being 4, 3, 2
Now given the employee information of a and 1 respectively.
company, and an employee id, you need to Note:
return the total importance value of this You may assume k is always valid, 1 ≤ k ≤ number
employee and all his subordinates. of unique elements.
Input words contain only lowercase letters.
Example 1: Follow up:
Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1 Try to solve it in O(n log k) time and O(n) extra
Output: 11 space.
96
156)Subarray Product Less Than K In C++, there are two types of comments, line
Your are given an array of positive integers nums. comments, and block comments.

Count and print the number of (contiguous) The string // denotes a line comment, which
subarrays where the product of all the elements represents that it and rest of the characters to
in the subarray is less than k. the right of it in the same line should be ignored.

Example 1: The string /* denotes a block comment, which


Input: nums = [10, 5, 2, 6], k = 100 represents that all characters until the next (non-
Output: 8 overlapping) occurrence of */ should be ignored.
Explanation: The 8 subarrays that have product (Here, occurrences happen in reading order: line
less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], by line from left to right.) To be clear, the string
[2, 6], [5, 2, 6]. /*/ does not yet end the block comment, as the
Note that [10, 5, 2] is not included as the product ending would be overlapping the beginning.
of 100 is not strictly less than k.
Note: The first effective comment takes precedence
over others: if the string // occurs in a block
0 < nums.length <= 50000. comment, it is ignored. Similarly, if the string /*
0 < nums[i] < 1000. occurs in a line or block comment, it is also
0 <= k < 10^6. ignored.
157)Maximum Length of Repeated Subarray
Given two integer arrays A and B, return the If a certain line of code is empty after removing
maximum length of an subarray that appears in comments, you must not output that line: each
both arrays. string in the answer list will be non-empty.

Example 1: There will be no control characters, single quote,


Input: or double quote characters. For example, source
A: [1,2,3,2,1] = "string s = "/* Not a comment. */";" will not be
B: [3,2,1,4,7] a test case. (Also, nothing else such as defines or
Output: 3 macros will interfere with the comments.)
Explanation:
The repeated subarray with maximum length is It is guaranteed that every open block comment
[3, 2, 1]. will eventually be closed, so /* outside of a line or
Note: block comment always starts a new comment.
1 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 100 Finally, implicit newline characters can be deleted
by block comments. Please see the examples
158)Remove Comments below for details.
Given a C++ program, remove comments from it.
The program source is an array where source[i] is After removing the comments from the source
the i-th line of the source code. This represents code, return the source code in the same format.
the result of splitting the original source code
string by the newline character \n. Example 1:
97
Input: After deletion, the implicit newline characters are
source = ["/*Test program */", "int main()", "{ ", " deleted, leaving the string "ab", which when
// variable declaration ", "int a, b, c;", "/* This is a delimited by newline characters becomes ["ab"].
test", " multiline ", " comment for ", " testing Note:
*/", "a = b + c;", "}"]
The length of source is in the range [1, 100].
The line by line code is visualized as below: The length of source[i] is in the range [0, 80].
/*Test program */ Every open block comment is eventually closed.
int main() There are no single-quote, double-quote, or
{ control characters in the source code.
// variable declaration
int a, b, c; 159)Split Linked List in Parts
/* This is a test Given a (singly) linked list with head node root,
multiline write a function to split the linked list into k
comment for consecutive linked list "parts".
testing */
a = b + c; The length of each part should be as equal as
} possible: no two parts should have a size differing
by more than 1. This may lead to some parts
Output: ["int main()","{ "," ","int a, b, c;","a = b + being null.
c;","}"]
The parts should be in order of occurrence in the
The line by line code is visualized as below: input list, and parts occurring earlier should
int main() always have a size greater than or equal parts
{ occurring later.
int a, b, c;
a = b + c; Return a List of ListNode's representing the linked
} list parts that are formed.

Explanation: Examples 1->2->3->4, k = 5 // 5 equal parts [ [1],


The string [2], [3], [4], null ]
/* Example 1:
denotes a block comment, including line 1 and Input:
lines 6-9. The string root = [1, 2, 3], k = 5
// Output: [[1],[2],[3],[],[]]
denotes line 4 as comments. Explanation:
Example 2: The input and each element of the output are
Input: ListNodes, not arrays.
source = ["a/*comment", "line", For example, the input root has root.val = 1,
"more_comment*/b"] root.next.val = 2, \root.next.next.val = 3, and
Output: ["ab"] root.next.next.next = null.
Explanation: The original source string is The first element output[0] has output[0].val = 1,
"a/*comment\nline\nmore_comment*/b", output[0].next = null.
where we have bolded the newline characters.
98
The last element output[4] is null, but it's string Explanation:
representation as a ListNode is []. There are two kinds of items, A and B. Their
Example 2: prices are $2 and $5 respectively.
Input: In special offer 1, you can pay $5 for 3A and 0B
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3 In special offer 2, you can pay $10 for 1A and 2B.
Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]] You need to buy 3A and 2B, so you may pay $10
Explanation: for 1A and 2B (special offer #2), and $4 for 2A.
The input has been split into consecutive parts Example 2:
with size difference at most 1, and earlier parts Input: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1]
are a larger size than the later parts. Output: 11
Note: Explanation:
The price of A is $2, and $3 for B, $4 for C.
The length of root will be in the range [0, 1000]. You may pay $4 for 1A and 1B, and $9 for 2A ,2B
Each value of a node in the input will be an and 1C.
integer in the range [0, 999]. You need to buy 1A ,2B and 1C, so you may pay
k will be an integer in the range [1, 50]. $4 for 1A and 1B (special offer #1), and $3 for 1B,
$4 for 1C.
160)Shopping Offers You cannot add more items, though only $9 for
In LeetCode Store, there are some kinds of items 2A ,2B and 1C.
to sell. Each item has a price. Note:
There are at most 6 kinds of items, 100 special
However, there are some special offers, and a offers.
special offer consists of one or more different For each item, you need to buy at most 6 of
kinds of items with a sale price. them.
You are not allowed to buy more items than you
You are given the each item's price, a set of want, even if that would lower the overall price.
special offers, and the number we need to buy
for each item. The job is to output the lowest 161)My Calendar I
price you have to pay for exactly certain items as Implement a MyCalendar class to store your
given, where you could make optimal use of the events. A new event can be added if adding the
special offers. event will not cause a double booking.

Each special offer is represented in the form of an Your class will have the method, book(int start,
array, the last number represents the price you int end). Formally, this represents a booking on
need to pay for this special offer, other numbers the half open interval [start, end), the range of
represents how many specific items you could get real numbers x such that start <= x < end.
if you buy this offer.
A double booking happens when two events have
You could use any of special offers as many times some non-empty intersection (ie., there is some
as you want. time that is common to both events.)

Example 1: For each call to the method MyCalendar.book,


Input: [2,5], [[3,0,5],[1,2,10]], [3,2] return true if the event can be added to the
Output: 14 calendar successfully without causing a double
99
booking. Otherwise, return false and do not add The 10 and -5 collide resulting in 10. The 5 and
the event to the calendar. 10 never collide.
Example 2:
Your class will be called like this: MyCalendar cal Input:
= new MyCalendar(); MyCalendar.book(start, asteroids = [8, -8]
end) Output: []
Example 1: Explanation:
MyCalendar(); The 8 and -8 collide exploding each other.
MyCalendar.book(10, 20); // returns true Example 3:
MyCalendar.book(15, 25); // returns false Input:
MyCalendar.book(20, 30); // returns true asteroids = [10, 2, -5]
Explanation: Output: [10]
The first event can be booked. The second can't Explanation:
because time 15 is already booked by another The 2 and -5 collide resulting in -5. The 10 and -5
event. collide resulting in 10.
The third event can be booked, as the first event Example 4:
takes every time less than 20, but not including Input:
20. asteroids = [-2, -1, 1, 2]
Note: Output: [-2, -1, 1, 2]
Explanation:
The number of calls to MyCalendar.book per test The -2 and -1 are moving left, while the 1 and 2
case will be at most 1000. are moving right.
In calls to MyCalendar.book(start, end), start and Asteroids moving the same direction never meet,
end are integers in the range [0, 10^9]. so no asteroids will meet each other.
162) Asteroid Collision Note:
We are given an array asteroids of integers
representing asteroids in a row. The length of asteroids will be at most 10000.
Each asteroid will be a non-zero integer in the
For each asteroid, the absolute value represents range [-1000, 1000]..
its size, and the sign represents its direction
(positive meaning right, negative meaning left). 163)Monotone Increasing Digits
Each asteroid moves at the same speed. Given a non-negative integer N, find the largest
number that is less than or equal to N with
Find out the state of the asteroids after all monotone increasing digits.
collisions. If two asteroids meet, the smaller one
will explode. If both are the same size, both will (Recall that an integer has monotone increasing
explode. Two asteroids moving in the same digits if and only if each pair of adjacent digits x
direction will never meet. and y satisfy x <= y.)

Example 1: Example 1:
Input: Input: N = 10
asteroids = [5, 10, -5] Output: 9
Output: [5, 10] Example 2:
Explanation: Input: N = 1234
100
Output: 1234 Return the minimum number of rabbits that
Example 3: could be in the forest.
Input: N = 332
Output: 299 Examples:
Note: N is an integer in the range [0, 10^9]. Input: answers = [1, 1, 2]
Output: 5
Explanation:
164) Daily Temperature The two rabbits that answered "1" could both be
Given a list of daily temperatures, produce a list the same color, say red.
that, for each day in the input, tells you how The rabbit than answered "2" can't be red or the
many days you would have to wait until a warmer answers would be inconsistent.
temperature. If there is no future day for which Say the rabbit that answered "2" was blue.
this is possible, put 0 instead. Then there should be 2 other blue rabbits in the
forest that didn't answer into the array.
For example, given the list temperatures = [73, The smallest possible number of rabbits in the
74, 75, 71, 69, 72, 76, 73], your output should be forest is therefore 5: 3 that answered plus 2 that
[1, 1, 4, 2, 1, 1, 0, 0]. didn't.

Note: The length of temperatures will be in the Input: answers = [10, 10, 10]
range [1, 30000]. Each temperature will be an Output: 11
integer in the range [30, 100].
Input: answers = []
Output: 0
165) 43. Multiply Strings Note:

Given two non-negative integers num1 and num2 answers will have length at most 1000.
represented as strings, return the product of Each answers[i] will be an integer in the range [0,
num1 and num2. 999].

Note: 167) K-th Symbol in Grammar


On the first row, we write a 0. Now in every
The length of both num1 and num2 is < 110. subsequent row, we look at the previous row and
Both num1 and num2 contains only digits 0-9. replace each occurrence of 0 with 01, and each
Both num1 and num2 does not contain any occurrence of 1 with 10.
leading zero.
You must not use any built-in BigInteger library or Given row N and index K, return the K-th indexed
convert the inputs to integer directly. symbol in row N. (The values of K are 1-indexed.)
(1 indexed).
166) Rabbits in Forest
In a forest, each rabbit has some color. Some Examples:
subset of rabbits (possibly all of them) tell you Input: N = 1, K = 1
how many other rabbits have the same color as Output: 0
them. Those answers are placed in an array.
Input: N = 2, K = 1
101
Output: 0 01110
00100
Input: N = 2, K = 2 00000
Output: 1
Order 3:
Input: N = 4, K = 5 0000000
Output: 1 0001000
0001000
Explanation: 0111110
row 1: 0 0001000
row 2: 01 0001000
row 3: 0110 0000000
row 4: 01101001 Example 1:
Note:
Input: N = 5, mines = [[4, 2]]
N will be an integer in the range [1, 30]. Output: 2
K will be an integer in the range [1, 2^(N-1)]. Explanation:
11111
168)Largest Plus Sign 11111
In a 2D grid from (0, 0) to (N-1, N-1), every cell 11111
contains a 1, except those cells in the given list 11111
mines which are 0. What is the largest axis- 11011
aligned plus sign of 1s contained in the grid? In the above grid, the largest plus sign can only be
Return the order of the plus sign. If there is none, order 2. One of them is marked in bold.
return 0. Example 2:

An "axis-aligned plus sign of 1s of order k" has Input: N = 2, mines = []


some center grid[x][y] = 1 along with 4 arms of Output: 1
length k-1 going up, down, left, and right, and Explanation:
made of 1s. This is demonstrated in the diagrams There is no plus sign of order 2, but there is of
below. Note that there could be 0s or 1s beyond order 1.
the arms of the plus sign, only the relevant area Example 3:
of the plus sign is checked for 1s.
Input: N = 1, mines = [[0, 0]]
Examples of Axis-Aligned Plus Signs of Order k: Output: 0
Explanation:
Order 1: There is no plus sign, so return 0.
000 Note:
010
000 N will be an integer in the range [1, 500].
mines will have length at most 5000.
Order 2: mines[i] will be length 2 and consist of integers in
00000 the range [0, N-1].
00100
102
169) Partition Labels Input:
A string S of lowercase letters is given. We want n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
to partition this string into as many parts as src = 0, dst = 2, k = 0
possible so that each letter appears in at most Output: 500
one part, and return a list of integers Explanation:
representing the size of these parts. The graph looks like this:

Example 1:
Input: S = "ababcbacadefegdehijhklij" The cheapest price from city 0 to city 2 with at
Output: [9,7,8] most 0 stop costs 500, as marked blue in the
Explanation: picture.
The partition is "ababcbaca", "defegde", "hijhklij". Note:
This is a partition so that each letter appears in at
most one part. The number of nodes n will be in range [1, 100],
A partition like "ababcbacadefegde", "hijhklij" is with nodes labeled from 0 to n - 1.
incorrect, because it splits S into less parts. The size of flights will be in range [0, n * (n - 1) /
Note: 2].
The format of each flight will be (src, dst, price).
S will have length in range [1, 500]. The price of each flight will be in the range [1,
S will consist of lowercase letters ('a' to 'z') only. 10000].
k is in the range of [0, n - 1].
170) There will not be any duplicated flights or self
There are n cities connected by m flights. Each cycles.
fight starts from city u and arrives at v with a
price w. 171)Max Chunks To Make Sorted
Given an array arr that is a permutation of [0, 1,
Now given all the cities and fights, together with ..., arr.length - 1], we split the array into some
starting city src and the destination dst, your task number of "chunks" (partitions), and individually
is to find the cheapest price from src to dst with sort each chunk. After concatenating them, the
up to k stops. If there is no such route, output -1. result equals the sorted array.

Example 1: What is the most number of chunks we could


Input: have made?
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1 Example 1:
Output: 200
Explanation: Input: arr = [4,3,2,1,0]
The graph looks like this: Output: 1
Explanation:
Splitting into two or more chunks will not return
The cheapest price from city 0 to city 2 with at the required result.
most 1 stop costs 200, as marked red in the For example, splitting into [4, 3], [2, 1, 0] will
picture. result in [3, 4, 0, 1, 2], which isn't sorted.
Example 2: Example 2:
103
Explanation:
Input: arr = [1,0,2,3,4] The graph looks like this:
Output: 4 0----1
Explanation: |\ |
We can split into two chunks, such as [1, 0], [2, 3, | \|
4]. 3----2
However, splitting into [1, 0], [2], [3], [4] is the We cannot find a way to divide the set of nodes
highest number of chunks possible. into two independent subsets.
Note:

arr will have length in range [1, 10]. Note:


arr[i] will be a permutation of [0, 1, ..., arr.length -
1]. graph will have length in range [1, 100].
graph[i] will contain integers in range [0,
172) Is Graph Bipartite? graph.length - 1].
Given a graph, return true if and only if it is graph[i] will not contain i or duplicate values.
bipartite.
173) Custom Sort String
Recall that a graph is bipartite if we can split it's S and T are strings composed of lowercase
set of nodes into two independent subsets A and letters. In S, no letter occurs more than once.
B such that every edge in the graph has one node
in A and another node in B. S was sorted in some custom order previously.
We want to permute the characters of T so that
The graph is given in the following form: graph[i] they match the order that S was sorted. More
is a list of indexes j for which the edge between specifically, if x occurs before y in S, then x should
nodes i and j exists. Each node is an integer occur before y in the returned string.
between 0 and graph.length - 1. There are no self
edges or parallel edges: graph[i] does not contain Return any permutation of T (as a string) that
i, and it doesn't contain any element twice. satisfies this property.

Example 1: Example :
Input: [[1,3], [0,2], [1,3], [0,2]] Input:
Output: true S = "cba"
Explanation: T = "abcd"
The graph looks like this: Output: "cbad"
0----1 Explanation:
| | "a", "b", "c" appear in S, so the order of "a", "b",
| | "c" should be "c", "b", and "a".
3----2 Since "d" does not appear in S, it can be at any
We can divide the vertices into two groups: {0, 2} position in T. "dcba", "cdba", "cbda" are also valid
and {1, 3}. outputs.
Example 2:
Input: [[1,2,3], [0,2], [0,1,3], [0,2]]
Output: false Note:
104
All edges times[i] = (u, v, w) will have 1 <= u, v <=
S has length at most 26, and no character is N and 1 <= w <= 100.
repeated in S.
T has length at most 200. 176)All Paths From Source to Target
S and T consist of lowercase letters only. Given a directed, acyclic graph of N nodes. Find
all possible paths from node 0 to node N-1, and
174) Number of Matching Subsequences return them in any order.
Given string S and a dictionary of words words,
find the number of words[i] that is a subsequence The graph is given as follows: the nodes are 0, 1,
of S. ..., graph.length - 1. graph[i] is a list of all nodes j
for which the edge (i, j) exists.
Example :
Input: Example:
S = "abcde" Input: [[1,2], [3], [3], []]
words = ["a", "bb", "acd", "ace"] Output: [[0,1,3],[0,2,3]]
Output: 3 Explanation: The graph looks like this:
Explanation: There are three words in words that 0--->1
are a subsequence of S: "a", "acd", "ace". | |
Note: v v
2--->3
All words in words and S will only consists of There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
lowercase letters. Note:
The length of S will be in the range of [1, 50000].
The length of words will be in the range of [1, The number of nodes in the graph will be in the
5000]. range [2, 15].
The length of words[i] will be in the range of [1, You can print different paths in any order, but
50]. you should keep the order of nodes inside one
path.
175)Network Delay Time
There are N network nodes, labelled 1 to N. 177)Find Eventual Safe States

Given times, a list of travel times as directed In a directed graph, we start at some node and
edges times[i] = (u, v, w), where u is the source every turn, walk along a directed edge of the
node, v is the target node, and w is the time it graph. If we reach a node that is terminal (that is,
takes for a signal to travel from source to target. it has no outgoing directed edges), we stop.

Now, we send a signal from a certain node K. Now, say our starting node is eventually safe if
How long will it take for all nodes to receive the and only if we must eventually walk to a terminal
signal? If it is impossible, return -1. node. More specifically, there exists a natural
number K so that for any choice of where to walk,
Note: we must have stopped at a terminal node in less
N will be in the range [1, 100]. than K steps.
K will be in the range [1, N].
The length of times will be in the range [1, 6000].
105
Which nodes are eventually safe? Return them The skyline viewed from top or bottom is: [9, 4, 8,
as an array in sorted order. 7]
The skyline viewed from left or right is: [8, 7, 9, 3]
The directed graph has N nodes with labels 0, 1,
..., N-1, where N is the length of graph. The graph The grid after increasing the height of buildings
is given in the following form: graph[i] is a list of without affecting skylines is:
labels j such that (i, j) is a directed edge of the
graph. gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
Example: [9, 4, 8, 7],
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]] [3, 3, 3, 3] ]
Output: [2,4,5,6]
Here is a diagram of the above graph. Notes:

178)Max Increase to Keep City Skyline 1 < grid.length = grid[0].length <= 50.
In a 2 dimensional array grid, each value grid[i][j] All heights grid[i][j] are in the range [0, 100].
represents the height of a building located there. All buildings in grid[i][j] occupy the entire grid
We are allowed to increase the height of any cell: that is, they are a 1 x 1 x grid[i][j] rectangular
number of buildings, by any amount (the prism.
amounts can be different for different buildings). 179)Binary Tree Pruning
Height 0 is considered to be a building as well. We are given the head node root of a binary tree,
where additionally every node's value is either a 0
At the end, the "skyline" when viewed from all or a 1.
four directions of the grid, i.e. top, bottom, left,
and right, must be the same as the skyline of the Return the same tree where every subtree (of the
original grid. A city's skyline is the outer contour given tree) not containing a 1 has been removed.
of the rectangles formed by all the buildings
when viewed from a distance. See the following (Recall that the subtree of a node X is X, plus
example. every node that is a descendant of X.)

What is the maximum total sum that the height Example 1:


of the buildings can be increased? Input: [1,null,0,0,1]
Output: [1,null,0,null,1]
Example:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]] Explanation:
Output: 35 Only the red nodes satisfy the property "every
Explanation: subtree not containing a 1".
The grid is: The diagram on the right represents the answer.
[ [3, 0, 8, 4],
[2, 4, 5, 7], The binary tree will have at most 100 nodes.
[9, 2, 6, 3], The value of each node will only be 0 or 1.
[0, 3, 1, 0] ]
180) Linked List Components

106
We are given head, the head node of a linked list For example, if the list of words is ["time", "me",
containing unique integer values. "bell"], we can write it as S = "time#bell#" and
indexes = [0, 2, 5].
We are also given the list G, a subset of the
values in the linked list. Then for each index, we will recover the word by
reading from the reference string from that index
Return the number of connected components in until we reach a "#" character.
G, where two values are connected if they appear
consecutively in the linked list. What is the length of the shortest reference
string S possible that encodes the given words?
Example 1:
Example:
Input:
head: 0->1->2->3 Input: words = ["time", "me", "bell"]
G = [0, 1, 3] Output: 10
Output: 2 Explanation: S = "time#bell#" and indexes = [0, 2,
Explanation: 5].
0 and 1 are connected, so [0, 1] and [3] are the Note:
two connected components.
Example 2: 1 <= words.length <= 2000.
1 <= words[i].length <= 7.
Input: Each word has only lowercase letters.
head: 0->1->2->3->4
G = [0, 3, 1, 4] 182)Most Profit Assigning Work
Output: 2 We have jobs: difficulty[i] is the difficulty of the
Explanation: ith job, and profit[i] is the profit of the ith job.
0 and 1 are connected, 3 and 4 are connected, so
[0, 1] and [3, 4] are the two connected Now we have some workers. worker[i] is the
components. ability of the ith worker, which means that this
Note: worker can only complete a job with difficulty at
most worker[i].
If N is the length of the linked list given by head, 1
<= N <= 10000. Every worker can be assigned at most one job,
The value of each node in the linked list will be in but one job can be completed multiple times.
the range [0, N - 1].
1 <= G.length <= 10000. For example, if 3 people attempt the same job
G is a subset of all values in the linked list. that pays $1, then the total profit will be $3. If a
worker cannot complete any job, his profit is $0.
181) Short Encoding of Words
Given a list of words, we may encode it by writing What is the most profit we can make?
a reference string S and a list of indexes A.
Example 1:

107
Input: difficulty = [2,4,6,8,10], profit =
[10,20,30,40,50], worker = [4,5,6,7] Note:
Output: 100
Explanation: Workers are assigned jobs of All numbers (including target) will be positive
difficulty [4,4,6,6] and they get profit of integers.
[20,20,30,30] seperately. The solution set must not contain duplicate
Notes: combinations.
Example 1:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000 Input: candidates = [10,1,2,7,6,1,5], target = 8,
difficulty[i], profit[i], worker[i] are in range [1, A solution set is:
10^5] [
[1, 7],
183) Consecutive Numbers Sum [1, 2, 5],
Given a positive integer N, how many ways can [2, 6],
we write it as a sum of consecutive positive [1, 1, 6]
integers? ]
Example 2:
Example 1:
Input: candidates = [2,5,2,1,2], target = 5,
Input: 5 A solution set is:
Output: 2 [
Explanation: 5 = 5 = 2 + 3 [1,2,2],
Example 2: [5]
]
Input: 9 184) Find And Replace in String
Output: 3
Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4 To some string S, we will perform some
Example 3: replacement operations that replace groups of
letters with new ones (not necessarily the same
Input: 15 size).
Output: 4
Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 Each replacement operation has 3 parameters: a
+4+5 starting index i, a source word x and a target
Note: 1 <= N <= 10 ^ 9. word y. The rule is that if x starts at position i in
the original string S, then we will replace that
183)Combination Sum II occurrence of x with y. If not, we do nothing.
Given a collection of candidate numbers
(candidates) and a target number (target), find all For example, if we have S = "abcd" and we have
unique combinations in candidates where the some replacement operation i = 2, x = "cd", y =
candidate numbers sums to target. "ffff", then because "cd" starts at position 2 in the
original string S, we will replace it with "ffff".
Each number in candidates may only be used
once in the combination.
108
Using another example on S = "abcd", if we have Formally, each room i has a list of keys rooms[i],
both the replacement operation i = 0, x = "ab", y and each key rooms[i][j] is an integer in [0, 1, ...,
= "eee", as well as another replacement N-1] where N = rooms.length. A key rooms[i][j] =
operation i = 2, x = "ec", y = "ffff", this second v opens the room with number v.
operation does nothing because in the original
string S[2] = 'c', which doesn't match x[0] = 'e'. Initially, all the rooms start locked (except for
room 0).
All these operations occur simultaneously. It's
guaranteed that there won't be any overlap in You can walk back and forth between rooms
replacement: for example, S = "abc", indexes = [0, freely.
1], sources = ["ab","bc"] is not a valid test case.
Return true if and only if you can enter every
Example 1: room.

Input: S = "abcd", indexes = [0,2], sources = Example 1:


["a","cd"], targets = ["eee","ffff"]
Output: "eeebffff" Input: [[1],[2],[3],[]]
Explanation: "a" starts at index 0 in S, so it's Output: true
replaced by "eee". Explanation:
"cd" starts at index 2 in S, so it's replaced by We start in room 0, and pick up key 1.
"ffff". We then go to room 1, and pick up key 2.
Example 2: We then go to room 2, and pick up key 3.
We then go to room 3. Since we were able to go
Input: S = "abcd", indexes = [0,2], sources = to every room, we return true.
["ab","ec"], targets = ["eee","ffff"] Example 2:
Output: "eeecd"
Explanation: "ab" starts at index 0 in S, so it's Input: [[1,3],[3,0,1],[2],[0]]
replaced by "eee". Output: false
"ec" doesn't starts at index 2 in the original S, so Explanation: We can't enter the room with
we do nothing. number 2.
Notes: Note:

0 <= indexes.length = sources.length = 1 <= rooms.length <= 1000


targets.length <= 100 0 <= rooms[i].length <= 1000
0 < indexes[i] < S.length <= 1000 The number of keys in all rooms combined is at
All characters in given inputs are lowercase most 3000.
letters.
186)Longest Palindromic Substring
185)Keys and Rooms Given a string s, find the longest palindromic
There are N rooms and you start in room 0. Each substring in s. You may assume that the
room has a distinct number in 0, 1, 2, ..., N-1, and maximum length of s is 1000.
each room may have some keys to access the
next room. Example 1:

109
Input: "babad" Input: [2,2,2]
Output: "bab" Output: 0
Note: "aba" is also a valid answer. Explanation: There is no mountain.
Example 2: Note:

Input: "cbbd" 0 <= A.length <= 10000


Output: "bb" 0 <= A[i] <= 10000
Follow up:
187)Container With Most Water
Given n non-negative integers a1, a2, ..., an, Can you solve it using only one pass?
where each represents a point at coordinate (i, Can you solve it in O(1) space?
ai). n vertical lines are drawn such that the two
endpoints of line i is at (i, ai) and (i, 0). Find two 189)Hand of Straights
lines, which together with x-axis forms a Alice has a hand of cards, given as an array of
container, such that the container contains the integers.
most water.
Now she wants to rearrange the cards into
Note: You may not slant the container and n is at groups so that each group is size W, and consists
least 2. of W consecutive cards.

188)Longest Mountain in Array Return true if and only if she can.


Let's call any (contiguous) subarray B (of A) a
mountain if the following properties hold:

B.length >= 3 Example 1:


There exists some 0 < i < B.length - 1 such that
B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > Input: hand = [1,2,3,6,2,3,4,7,8], W = 3
B[B.length - 1] Output: true
(Note that B could be any subarray of A, including Explanation: Alice's hand can be rearranged as
the entire array A.) [1,2,3],[2,3,4],[6,7,8].
Example 2:
Given an array A of integers, return the length of
the longest mountain. Input: hand = [1,2,3,4,5], W = 4
Output: false
Return 0 if there is no mountain. Explanation: Alice's hand can't be rearranged into
groups of 4.
Example 1: Note:

Input: [2,1,4,7,3,2,5] 1 <= hand.length <= 10000


Output: 5 0 <= hand[i] <= 10^9
Explanation: The largest mountain is [1,4,7,3,2] 1 <= W <= hand.length
which has length 5. 190)Shifting Letters
Example 2: We have a string S of lowercase letters, and an
integer array shifts.
110
The distance between these two cars is ignored -
Call the shift of a letter, the next letter in the they are assumed to have the same position.
alphabet, (wrapping around so that 'z' becomes
'a'). A car fleet is some non-empty set of cars driving
at the same position and same speed. Note that
For example, shift('a') = 'b', shift('t') = 'u', and a single car is also a car fleet.
shift('z') = 'a'.
If a car catches up to a car fleet right at the
Now for each shifts[i] = x, we want to shift the destination point, it will still be considered as one
first i+1 letters of S, x times. car fleet.

Return the final string after all such shifts to S are


applied. How many car fleets will arrive at the
destination?
Example 1:
Example 1:
Input: S = "abc", shifts = [3,5,9]
Output: "rpl" Input: target = 12, position = [10,8,0,5,3], speed =
Explanation: [2,4,1,1,3]
We start with "abc". Output: 3
After shifting the first 1 letters of S by 3, we have Explanation:
"dbc". The cars starting at 10 and 8 become a fleet,
After shifting the first 2 letters of S by 5, we have meeting each other at 12.
"igc". The car starting at 0 doesn't catch up to any other
After shifting the first 3 letters of S by 9, we have car, so it is a fleet by itself.
"rpl", the answer. The cars starting at 5 and 3 become a fleet,
Note: meeting each other at 6.
Note that no other cars meet these fleets before
1 <= S.length = shifts.length <= 20000 the destination, so the answer is 3.
0 <= shifts[i] <= 10 ^ 9
191)Car Fleet Note:
N cars are going to the same destination along a
one lane road. The destination is target miles 0 <= N <= 10 ^ 4
away. 0 < target <= 10 ^ 6
0 < speed[i] <= 10 ^ 6
Each car i has a constant speed speed[i] (in miles 0 <= position[i] < target
per hour), and initial position position[i] miles All initial positions are different.
towards the target along the road.
192)All Nodes Distance K in Binary Tree
A car can never pass another car ahead of it, but We are given a binary tree (with root node root),
it can catch up to it, and drive bumper to bumper a target node, and an integer value K.
at the same speed.

111
Return a list of the values of all nodes that have a Return the node with the largest depth such that
distance K from the target node. The answer can it contains all the deepest nodes in its subtree.
be returned in any order.

Example 1:
Example 1:
Input: [3,5,1,6,2,0,8,null,null,7,4]
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = Output: [2,7,4]
5, K = 2 Explanation:

Output: [7,4,1]

Explanation: We return the node with value 2, colored in


The nodes that are a distance 2 from the target yellow in the diagram.
node (with value 5) The nodes colored in blue are the deepest nodes
have values 7, 4, and 1. of the tree.
The input "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" is a
serialization of the given tree.
The output "[2, 7, 4]" is a serialization of the
Note that the inputs "root" and "target" are subtree rooted at the node with value 2.
actually TreeNodes. Both the input and output have TreeNode type.
The descriptions of the inputs above are just
serializations of these objects.
Note:

Note: The number of nodes in the tree will be between


1 and 500.
The given tree is non-empty. The values of each node are unique.
Each node in the tree has unique values 0 <= 194)Reordered Power of 2
node.val <= 500. Starting with a positive integer N, we reorder the
The target node is a node in the tree. digits in any order (including the original order)
0 <= K <= 1000. such that the leading digit is not zero.

193)Smallest Subtree with all the Deepest Nodes Return true if and only if we can do this in a way
Given a binary tree rooted at root, the depth of such that the resulting number is a power of 2.
each node is the shortest distance to the root.
Example 1:
A node is deepest if it has the largest depth
possible among any node in the entire tree. Input: 1
Output: true
The subtree of a node is that node, plus the set of Example 2:
all descendants of that node.
Input: 10
112
Output: false 1 35
Example 3: This tree is also valid:

Input: 16 5
Output: true / \
Example 4: 2 7
/\
Input: 24 1 3
Output: false \
Example 5: 4
196)Possible Bipartition
Input: 46 Given a set of N people (numbered 1, 2, ..., N), we
Output: true would like to split everyone into two groups of
any size.

Note: Each person may dislike some other people, and


they should not go into the same group.
1 <= N <= 10^9
195) Insert Into Binary Search Tree Formally, if dislikes[i] = [a, b], it means it is not
Given the root node of a binary search tree (BST) allowed to put the people numbered a and b into
and a value to be inserted into the tree, insert the the same group.
value into the BST. Return the root node of the
BST after the insertion. It is guaranteed that the Return true if and only if it is possible to split
new value does not exist in the original BST. everyone into two groups in this way.

Note that there may exist multiple valid ways for


the insertion, as long as the tree remains a BST
after insertion. You can return any of them. Example 1:

For example, Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]


Output: true
Given the tree: Explanation: group1 [1,4], group2 [2,3]
4 Example 2:
/\
2 7 Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]
/\ Output: false
1 3 Example 3:
And the value to insert: 5
You can return this binary search tree: Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
Output: false
4
/ \ Note:
2 7
/\ / 1 <= N <= 2000
113
0 <= dislikes.length <= 10000
1 <= dislikes[i][j] <= N
dislikes[i][0] < dislikes[i][1] Example 1:
There does not exist i != j for which dislikes[i] ==
dislikes[j]. Input: people = [1,2], limit = 3
Output: 1
197)Advantage Shuffle Explanation: 1 boat (1, 2)
Given two arrays A and B of equal size, the Example 2:
advantage of A with respect to B is the number of
indices i for which A[i] > B[i]. Input: people = [3,2,2,1], limit = 3
Output: 3
Return any permutation of A that maximizes its Explanation: 3 boats (1, 2), (2) and (3)
advantage with respect to B. Example 3:

Input: people = [3,5,3,4], limit = 5


Output: 4
Example 1: Explanation: 4 boats (3), (3), (4), (5)
Note:
Input: A = [2,7,11,15], B = [1,10,4,11]
Output: [2,11,7,15] 1 <= people.length <= 50000
Example 2: 1 <= people[i] <= limit <= 30000

Input: A = [12,24,8,32], B = [13,25,32,11] 199) Find and Replace Pattern


Output: [24,32,8,12] You have a list of words and a pattern, and you
want to know which words in words matches the
pattern.
Note:
A word matches the pattern if there exists a
1 <= A.length = B.length <= 10000 permutation of letters p so that after replacing
0 <= A[i] <= 10^9 every letter x in the pattern with p(x), we get the
0 <= B[i] <= 10^9 desired word.

198)Boats to Save People (Recall that a permutation of letters is a bijection


The i-th person has weight people[i], and each from letters to letters: every letter maps to
boat can carry a maximum weight of limit. another letter, and no two letters map to the
same letter.)
Each boat carries at most 2 people at the same
time, provided the sum of the weight of those Return a list of the words in words that match the
people is at most limit. given pattern.

Return the minimum number of boats to carry You may return the answer in any order.
every given person. (It is guaranteed each person
can be carried by a boat.)

114
Example 1: 201) Egg Dropping Puzzle
The following is a description of the instance of
Input: words = this famous puzzle involving n=2 eggs and a
["abc","deq","mee","aqq","dkd","ccc"], pattern = building with k=36 floors.
"abb"
Output: ["mee","aqq"] Suppose that we wish to know which stories in a
Explanation: "mee" matches the pattern because 36-story building are safe to drop eggs from, and
there is a permutation {a -> m, b -> e, ...}. which will cause the eggs to
"ccc" does not match the pattern because {a -> c, break on landing. We make a few assumptions:
b -> c, ...} is not a permutation,
since a and b map to the same letter. …..An egg that survives a fall can be used again.
…..A broken egg must be discarded.
…..The effect of a fall is the same for all eggs.
Note: …..If an egg breaks when dropped, then it would
break if dropped from a higher floor.
1 <= words.length <= 50 …..If an egg survives a fall then it would survive a
1 <= pattern.length = words[i].length <= 20 shorter fall.
…..It is not ruled out that the first-floor windows
break eggs, nor is it ruled out that the 36th-floor
200) House Robber 2 do not cause an egg to break.

A robber is planning to rob houses along a street. If only one egg is available and we wish to be sure
Each house has a certain amount of money of obtaining the right result, the experiment can
stashed. All houses at be carried out in only one way.
this place are arranged in a circle. That means the Drop the egg from the first-floor window; if it
first house is the neighbor of the last one. survives, drop it from the second floor window.
Meanwhile, adjacent houses have Continue upward until it breaks.
security system connected and it will In the worst case, this method may require 36
automatically contact the police if two adjacent droppings. Suppose 2 eggs are available. What is
houses were broken into on the same night. the least number of egg-droppings
that is guaranteed to work in all cases?
You are given a list of non-negative integers The problem is not actually to find the critical
representing the amount of money of each floor, but merely to decide floors from which eggs
house, we need to determine the maximum should be dropped so that total
amount of number of trials are minimized.
money the robber can rob tonight without
alerting the police. Here, we need to design a solution to a general
problem with n eggs and k floors.
Eg: Suppose you are given an array of money of
houses like [2,3,2] , max amount of money Eg: For 10 floors and 2 eggs, minimum number of
robber can rob is 3, as he cannot rob trials in worst case with 2 eggs and 10 floors is 4,
house 1 (money = 2) and then rob house 3 as we can first drop egg from 4th floor, if it
(money = 2), because they are adjacent houses. doesn't break, then from 7th and then from 9th
and eventually 10.
115
A complete binary tree is a binary tree in which
202)Online election every level, except possibly the last, is completely
In an election, the i-th vote was cast for filled, and all nodes are as far left as possible.
persons[i] at time times[i].
Write a data structure CBTInserter that is
Now, we would like to implement the following initialized with a complete binary tree and
query function: TopVotedCandidate.q(int t) will supports the following operations:
return the number of the person that was leading
the election at time t. CBTInserter(TreeNode root) initializes the data
structure on a given tree with head node root;
Votes cast at time t will count towards our query. CBTInserter.insert(int v) will insert a TreeNode
In the case of a tie, the most recent vote (among into the tree with value node.val = v so that the
tied candidates) wins. tree remains complete, and returns the value of
the parent of the inserted TreeNode;
CBTInserter.get_root() will return the head node
of the tree.
Example 1:

Input: Example 1:
["TopVotedCandidate","q","q","q","q","q","q"],
[[[0,1,1,0,0,1,0],[0,5,10,15,20,25,30]],[3],[12],[25] Input: inputs =
,[15],[24],[8]] ["CBTInserter","insert","get_root"], inputs =
Output: [null,0,1,1,0,0,1] [[[1]],[2],[]]
Explanation: Output: [null,1,[1,2]]
At time 3, the votes are [0], and 0 is leading. Example 2:
At time 12, the votes are [0,1,1], and 1 is leading.
At time 25, the votes are [0,1,1,0,0,1], and 1 is Input: inputs =
leading (as ties go to the most recent vote.) ["CBTInserter","insert","insert","get_root"],
This continues for 3 more queries at time 15, 24, inputs = [[[1,2,3,4,5,6]],[7],[8],[]]
and 8. Output: [null,3,4,[1,2,3,4,5,6,7,8]]

Note: Note:

1 <= persons.length = times.length <= 5000 The initial given tree is complete and contains
0 <= persons[i] <= persons.length between 1 and 1000 nodes.
times is a strictly increasing array with all CBTInserter.insert is called at most 10000 times
elements in [0, 10^9]. per test case.
TopVotedCandidate.q is called at most 10000 Every value of a given or inserted node is
times per test case. between 0 and 5000.
TopVotedCandidate.q(int t) is always called with t
>= times[0]. 204)Word Subsets
We are given two arrays A and B of words. Each
203)Complete Binary Tree Inserter word is a string of lowercase letters.
116
Now, say that word b is a subset of word a if
every letter in b occurs in a, including multiplicity. Note:
For example, "wrr" is a subset of "warrior", but is
not a subset of "world". 1 <= A.length, B.length <= 10000
1 <= A[i].length, B[i].length <= 10
Now say a word a from A is universal if for every A[i] and B[i] consist only of lowercase letters.
b in B, b is a subset of a. All words in A[i] are unique: there isn't i != j with
A[i] == A[j].
Return a list of all universal words in A. You can
return the words in any order. Hard Level

1) **Binary Tree Postorder Traversal**


Given a binary tree, return the postorder
Example 1: traversal of its nodes' values.

Input: A = For example:


["amazon","apple","facebook","google","leetcod Given binary tree {1,#,2,3},
e"], B = ["e","o"] 1
Output: ["facebook","google","leetcode"] \
Example 2: 2
/
Input: A = 3
["amazon","apple","facebook","google","leetcod return [3,2,1].
e"], B = ["l","e"] Note: Recursive solution is trivial, could you do it
Output: ["apple","google","leetcode"] iteratively?
Example 3:
2) **Copy List with Random Pointer**
Input: A = A linked list is given such that each node contains
["amazon","apple","facebook","google","leetcod an additional random pointer which could point
e"], B = ["e","oo"] to any node in the list or null.
Output: ["facebook","google"] Return a deep copy of the list.
Example 4:
3)**Populating Next Right Pointers in Each Node
Input: A = II**
["amazon","apple","facebook","google","leetcod Follow up for problem "Populating Next Right
e"], B = ["lo","eo"] Pointers in Each Node".
Output: ["google","leetcode"] What if the given tree could be any binary tree?
Example 5: Would your previous solution still work?

Input: A = 4) Diagonal traverse


["amazon","apple","facebook","google","leetcod Given a matrix of M x N elements (M rows, N
e"], B = ["ec","oc","ceo"] columns), return all elements of the matrix in
Output: ["facebook","leetcode"] diagonal order.
117
Input: For this problem, a path is defined as any
[ sequence of nodes from some starting node to
[ 1, 2, 3 ], any node in the tree along the parent-child
[ 4, 5, 6 ], connections. The path must contain at least one
[ 7, 8, 9 ] node and does not need to go through the root.
]
Output: [1,2,4,7,5,3,6,8,9] For example:
Given the below binary tree,

5)Word Ladder II 1
Given two words (beginWord and endWord), and /\
a dictionary's word list, find all shortest 2 3
transformation sequence(s) from beginWord to Return 6.
endWord, such that: 7)Shortest Palindrome
Given a string S, you are allowed to convert it to a
Only one letter can be changed at a time palindrome by adding characters in front of it.
Each transformed word must exist in the word Find and return the shortest palindrome you can
list. Note that beginWord is not a transformed find by performing this transformation.
word.
For example, For example:

Given: Given "aacecaaa", return "aaacecaaa".


beginWord = "hit"
endWord = "cog" Given "abcd", return "dcbabcd".
wordList = ["hot","dot","dog","lot","log","cog"]
Return 8)Insert Interval
[ Given a set of non-overlapping intervals, insert a
["hit","hot","dot","dog","cog"], new interval into the intervals (merge if
["hit","hot","lot","log","cog"] necessary).
]
Note: You may assume that the intervals were initially
Return an empty list if there is no such sorted according to their start times.
transformation sequence.
All words have the same length. Example 1:
All words contain only lowercase alphabetic Given intervals [1,3],[6,9], insert and merge [2,5]
characters. in as [1,5],[6,9].
You may assume no duplicates in the word list.
You may assume beginWord and endWord are Example 2:
non-empty and are not the same. Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and
merge [4,9] in as [1,2],[3,10],[12,16].
6)Binary Tree Maximum Path Sum
Given a binary tree, find the maximum path sum. This is because the new interval [4,9] overlaps
with [3,5],[6,7],[8,10].

118
9)Serialize and Deserialize Binary Tree Design and implement a data structure for Least
Serialization is the process of converting a data Recently Used (LRU) cache. It should support the
structure or object into a sequence of bits so that following operations: get and put.
it can be stored in a file or memory buffer, or
transmitted across a network connection link to get(key) - Get the value (will always be positive)
be reconstructed later in the same or another of the key if the key exists in the cache, otherwise
computer environment. return -1.
put(key, value) - Set or insert the value if the key
Design an algorithm to serialize and deserialize a is not already present. When the cache reached
binary tree. There is no restriction on how your its capacity, it should invalidate the least recently
serialization/deserialization algorithm should used item before inserting a new item.
work. You just need to ensure that a binary tree
can be serialized to a string and this string can be Follow up:
deserialized to the original tree structure. Could you do both operations in O(1) time
complexity?
For example, you may serialize the following tree
Example:
1
/\ LRUCache cache = new LRUCache( 2 /* capacity
2 3 */ );
/\
4 5 cache.put(1, 1);
as "[1,2,3,null,null,4,5]", just the same as how cache.put(2, 2);
LeetCode OJ serializes a binary tree. You do not cache.get(1); // returns 1
necessarily need to follow this format, so please cache.put(3, 3); // evicts key 2
be creative and come up with different cache.get(2); // returns -1 (not found)
approaches yourself. cache.put(4, 4); // evicts key 1
Note: Do not use class member/global/static cache.get(1); // returns -1 (not found)
variables to store states. Your serialize and cache.get(3); // returns 3
deserialize algorithms should be stateless. cache.get(4); // returns 4

10)Trapping Rain Water 12)Cut Off Trees for Golf Event


Given n non-negative integers representing an You are asked to cut off trees in a forest for a golf
elevation map where the width of each bar is 1, event. The forest is represented as a non-
compute how much water it is able to trap after negative 2D map, in this map:
raining.
0 represents the obstacle can't be reached.
For example, 1 represents the ground can be walked through.
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. The place with number bigger than 1 represents a
tree can be walked through, and this positive
11)LRU Cache number represents the tree's height.
You are asked to cut off all the trees in this forest
in the order of tree's height - always cut off the
tree with lowest height first. And after cutting,
119
the original place has the tree will become a grass A move consists of taking a point (x, y) and
(value 1). transforming it to either (x, x+y) or (x+y, y).

You will start from the point (0, 0) and you should Given a starting point (sx, sy) and a target point
output the minimum steps you need to walk to (tx, ty), return True if and only if a sequence of
cut off all the trees. If you can't cut off all the moves exists to transform the point (sx, sy) to (tx,
trees, output -1 in that situation. ty). Otherwise, return False.

You are guaranteed that no two trees have the Examples:


same height and there is at least one tree needs Input: sx = 1, sy = 1, tx = 3, ty = 5
to be cut off. Output: True
Explanation:
Example 1: One series of moves that transforms the starting
Input: point to the target is:
[ (1, 1) -> (1, 2)
[1,2,3], (1, 2) -> (3, 2)
[0,0,4], (3, 2) -> (3, 5)
[7,6,5]
] Input: sx = 1, sy = 1, tx = 2, ty = 2
Output: 6 Output: False
Example 2:
Input: Input: sx = 1, sy = 1, tx = 1, ty = 1
[ Output: True
[1,2,3],
[0,0,0], Note:
[7,6,5]
] sx, sy, tx, ty will all be integers in the range [1,
Output: -1 10^9].
Example 3:
Input: 14) First Missing Positive
[ Given an unsorted integer array, find the first
[2,3,4], missing positive integer.
[0,0,5],
[8,7,6] For example,
] Given [1,2,0] return 3,
Output: 6 and [3,4,-1,1] return 2.
Explanation: You started from the point (0,0) and
you can cut off the tree in (0,0) directly without Your algorithm should run in O(n) time and uses
walking. constant space.
Hint: size of the given matrix will not exceed
50x50. 14)768. Max Chunks To Make Sorted II
This question is the same as "Max Chunks to
13) Reaching Points Make Sorted" except the integers of the given
array are not necessarily distinct, the input array
120
could be up to length 2000, and the elements if and only if the elevation of both squares
could be up to 10**8. individually are at most t. You can swim infinite
distance in zero time. Of course, you must stay
Given an array arr of integers (not necessarily within the boundaries of the grid during your
distinct), we split the array into some number of swim.
"chunks" (partitions), and individually sort each
chunk. After concatenating them, the result You start at the top left square (0, 0). What is the
equals the sorted array. least time until you can reach the bottom right
square (N-1, N-1)?
What is the most number of chunks we could
have made? Example 1:

Example 1: Input: [[0,2],[1,3]]


Output: 3
Input: arr = [5,4,3,2,1] Explanation:
Output: 1 At time 0, you are in grid location (0, 0).
Explanation: You cannot go anywhere else because 4-
Splitting into two or more chunks will not return directionally adjacent neighbors have a higher
the required result. elevation than t = 0.
For example, splitting into [5, 4], [3, 2, 1] will
result in [4, 5, 1, 2, 3], which isn't sorted. You cannot reach point (1, 1) until time 3.
Example 2: When the depth of water is 3, we can swim
anywhere inside the grid.
Input: arr = [2,1,3,4,4] Example 2:
Output: 4
Explanation: Input:
We can split into two chunks, such as [2, 1], [3, 4, [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,1
4]. 7,18,19,20],[10,9,8,7,6]]
However, splitting into [2, 1], [3], [4], [4] is the Output: 16
highest number of chunks possible. Explanation:
Note: 0 1 2 3 4
24 23 22 21 5
arr will have length in range [1, 2000]. 12 13 14 15 16
arr[i] will be an integer in range [0, 10**8]. 11 17 18 19 20
10 9 8 7 6

The final route is marked in bold.


15) Swim in Rising Water We need to wait until time 16 so that (0, 0) and
On an N x N grid, each square grid[i][j] represents (4, 4) are connected.
the elevation at that point (i,j). Note:

Now rain starts to fall. At time t, the depth of the 2 <= N <= 50.
water everywhere is t. You can swim from a grid[i][j] is a permutation of [0, ..., N*N - 1].
square to another 4-directionally adjacent square
121
16) Find K-th Smallest Pair Distance
Given an integer array, return the k-th smallest Example 1:
distance among all the pairs. The distance of a
pair (A, B) is defined as the absolute difference Input: ["tars","rats","arts","star"]
between A and B. Output: 2
Note:
Example 1:
Input: A.length <= 2000
nums = [1,3,1] A[i].length <= 1000
k=1 A.length * A[i].length <= 20000
Output: 0 All words in A consist of lowercase letters only.
Explanation: All words in A have the same length and are
Here are all the pairs: anagrams of each other.
(1,3) -> 2 The judging time limit has been increased for this
(1,1) -> 0 question.
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its 18) Interleaving String
distance is 0. Given s1, s2, s3, find whether s3 is formed by the
Note: interleaving of s1 and s2.
2 <= len(nums) <= 10000.
0 <= nums[i] < 1000000. Example 1:
1 <= k <= len(nums) * (len(nums) - 1) / 2.
Input: s1 = "aabcc", s2 = "dbbca", s3 =
17)Similar String Groups "aadbbcbcac"
Two strings X and Y are similar if we can swap Output: true
two letters (in different positions) of X, so that it Example 2:
equals Y.
Input: s1 = "aabcc", s2 = "dbbca", s3 =
For example, "tars" and "rats" are similar "aadbbbaccc"
(swapping at positions 0 and 2), and "rats" and Output: false
"arts" are similar, but "star" is not similar to
"tars", "rats", or "arts". 19)Maximum Frequency Stack
Implement FreqStack, a class which simulates the
Together, these form two connected groups by operation of a stack-like data structure.
similarity: {"tars", "rats", "arts"} and {"star"}.
Notice that "tars" and "arts" are in the same FreqStack has two functions:
group even though they are not similar.
Formally, each group is such that a word is in the push(int x), which pushes an integer x onto the
group if and only if it is similar to at least one stack.
other word in the group. pop(), which removes and returns the most
frequent element in the stack.
We are given a list A of unique strings. Every If there is a tie for most frequent element, the
string in A is an anagram of every other string in element closest to the top of the stack is
A. How many groups are there? removed and returned.
122
Example 1:

Input:
["FreqStack","push","push","push","push","push"
,"push","pop","pop","pop","pop"],
[[],[5],[7],[5],[7],[4],[5],[],[],[],[]]
Output: [null,null,null,null,null,null,null,5,7,5,4]
Explanation:
After making six .push operations, the stack is
[5,7,5,7,4,5] from bottom to top. Then:

pop() -> returns 5, as 5 is the most frequent.


The stack becomes [5,7,5,7,4].

pop() -> returns 7, as 5 and 7 is the most


frequent, but 7 is closest to the top.
The stack becomes [5,7,5,4].

pop() -> returns 5.


The stack becomes [5,7,4].

pop() -> returns 4.


The stack becomes [5,7].

Note:

Calls to FreqStack.push(int x) will be such that 0


<= x <= 10^9.
It is guaranteed that FreqStack.pop() won't be
called if the stack has zero elements.
The total number of FreqStack.push calls will not
exceed 10000 in a single test case.
The total number of FreqStack.pop calls will not
exceed 10000 in a single test case.
The total number of FreqStack.push and
FreqStack.pop calls will not exceed 150000 across
all test cases.

123

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy