Interview Questions Part 1
Interview Questions Part 1
Interview Questions Part 1
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
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.
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.
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.
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.
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 :
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:
Example 1:
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.
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,
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.
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.
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).
"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.
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.
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.
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: 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].
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: 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.)
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.
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:
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]
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.
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
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:
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
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.
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:
Note:
123