112 Manual Testing Interview Questions Answers 1656817516 2
112 Manual Testing Interview Questions Answers 1656817516 2
3. Defects detected earlier phase of SDLC results in lesser cost and resource
utilization of correction.
1. After test case execution – The testing phase can be stopped when one
complete cycle of test cases is executed after the last known bug fix with the
agreed-upon value of pass-percentage
2. Once the testing deadline is met – Testing can be stopped after deadlines
get met with no high priority issues left in the system.
3. Based on Mean Time Between Failure (MTBF) – MTBF is the time interval
between two inherent failures. Based on stakeholder’s decisions, if the MTBF is
quite large, one can stop the testing phase.
4. Based on code coverage value – The testing phase can be stopped when
the automated code coverage reaches a specific threshold value with sufficient
pass-percentage and no critical bug.
Ques.4. What is Quality Assurance and what are the different activities
involved in Quality assurance?
Ques.5. What is Quality Control and what are the different types of
testing involved in QC.
Answers the question – “Are we building the Answers the question – “Are we building the
4.
product right?” right product?”
Errors found during verification require lesser Errors found during validation require more
5. cost/resources to get fixed as compared to be cost/resources. Later the error is discovered
found during the validation phase. higher is the cost to fix it.
Ans. SDLC stands for Software Development Life Cycle. It refers to all the
activities performed during software development – requirement gathering,
requirement analysis, designing, coding or implementation, testing,
deployment, and maintenance.
Ques.8. Explain the STLC – Software Testing life cycle.
Ans. The software testing life cycle refers to all the activities performed during
testing of a software product. The phases include-
• Requirement analysis and validation – In this phase, the requirements
documents are analyzed and validated and the scope of testing is
defined.
• Test planning – In this phase, test plan strategy is defined, estimation of
test effort is defined along with automation strategy, and tool selection
is done.
• Test Design and Analysis – Here, test cases are designed, test data is
prepared and automation scripts are implemented.
• Test environment setup – A test environment closely simulating the
real-world environment is prepared.
• Test execution – The test cases are prepared, bugs are reported and
retested once resolved.
• Test closure and reporting – A test closure report is prepared to have
the final test results summary, learning, and test metrics.
• Black box testing – In black-box testing, the tester need not have any
knowledge of the internal architecture or implementation of the system.
The tester interacts with the system through the interface providing input
and validating the received output.
• White box testing – In white box testing, the tester analyses the internal
architecture of the system as well as the quality of source code on
different parameters like code optimization, code coverage, reusability,
etc.
• Gray box testing – In gray box testing, the tester has partial access to the
internal architecture of the system e.g. the tester may have access to the
design documents or database structure. This information helps the tester
to test the application better.
Ques.33. Explain the bug life cycle or the different states of a bug.
Ans. A bug goes through the following phases in software development-
• New – A bug or defect when detected is in New state.
• Assigned – The newly detected bug when assigned to the
corresponding developer is in the Assigned state.
• Open – When the developer works on the bug, the bug lies in the Open
state.
• Rejected/Not a bug – A bug lies in rejected state in case the developer
feels the bug is not genuine.
• Deferred – A deferred bug is one, fix of which is deferred for some
time(for the next releases) based on the urgency and criticality of the
bug.
• Fixed – When a bug is resolved by the developer it is marked as fixed.
• Test – When fixed the bug is assigned to the tester and during this time
the bug is marked as in Test.
• Reopened – If the tester is not satisfied with the issue resolution the bug
is moved to the Reopened state.
• Verified – After the Test phase, if the tester feels the bug is resolved, it is
marked as verified.
• Closed – After the bug is verified, it is moved to Closed status.
Ans. Test design techniques are different standards of test designing that allow
systematic and widely accepted test cases. The different test design techniques
can be categorized as static test design techniques and dynamic test design
techniques.
1. Static Test Design Techniques – The test design techniques which involves
testing without executing the code. The various static test design
techniques can be further divided into two parts manual and using tools-
For example, for testing a Square program (a program that prints the square
of a number), the equivalence classes can be-
Set of Negative numbers, whole numbers, decimal numbers, set of large
numbers, etc.
Ans. Boundary value analysis is a software testing technique for designing test
cases wherein the boundary values of the classes of the equivalence class
partitioning are taken as input to the test cases e.g. if the test data lies in the
range of 0-100, the boundary value analysis will include test data – 0,1, 99, 100.
Decision tables are particularly helpful in designing test cases for complex
business scenarios involving verification of application with multiple
combinations of input.
Ans. A use case testing is a black-box testing approach in which testing is carried
out using use cases. A use case scenario is seen as an interaction between the
application and actors(users). These use cases are used for depicting
requirements and hence can also serve as a basis for acceptance testing.
The higher the test coverage, the more the part of the software gets covered by
test cases and hence, the more effective will be the testing.
Ans. Structure-based test design techniques are also referred to as white box
testing. In these techniques, the knowledge of code or internal architecture of
the system is required to carry out the testing. The various kinds of testing
structure-based or white testing techniques are-
• Statement testing – A white box testing technique in which the test
scripts are designed to execute the application’s code statements. Its
coverage is measured as the line of code or statements executed by test
scripts.
Ans. Decision testing or branch testing is a white box testing approach in which
test coverage is measured by the percentage of decision points(e.g. if-else
conditions) executed out of the total decision points in the application.
Also, check – Top SQL Queries Asked in Interviews
Ans. Testing is primarily performed by the testing team in order to find the
defects in the system. Whereas, debugging is an activity performed by the
development team. In debugging the cause of the defect is located and fixed.
Thus removing the defect and preventing any future occurrence of the defect
as well.
Another difference between the two is – testing can be done without any
internal knowledge of software architecture. Whereas debugging requires
knowledge of software architecture and coding.
Whereas a masked defect is an existing defect that has not yet caused any
failure because another error has masked it or prevented it from getting
discovered.
Ans. Test Metric is a quantitative analysis that helps in monitoring the progress
of a software project. Every project has its own timeline so to ensure the delivery
of the project on time requires setting deliverables at different intervals and this
aspect of measuring the progress is provided by test metrics.
Ans. Context-driven testing is the type of testing that involves adopting the
test practices, methodologies and at times customizing them based on the
context of the project.
In this type of testing, instead of following best practices, we follow what
works best for the project based on the skills, experience, and judgment of the
testing team. For details check – Context-driven methodology by James Bach
Table of Contents
What is API? 4
HTTP - Fundamentals 9
What is an Cookies? 10
What is Authentication? 10
API stands for the Application Programming Interface, They are basically a collection of functions and
procedures which allows us to communicate two application or library.
For example, It like a connector as seen in the picture. All data connects to our organization through API.
In one line, API is its an interface between different software programs or service.
Simple Examples is,
Suppose you go to a restaurant.
API is the messenger that takes your order(waiter) and tells the system(kitchen) what to do (to prepare food)
and in return gives back the response you asked for (waiter returns with the ordered food).
Source - Quora. https://www.quora.com/What-is-an-API
Type of APIs :-
What is API Testing?
API testing is testing that APIs and its integration with the services.
It is one of the most challenging type of testing, If we miss the certain cases in API Testing that can cause a
very big problem in production after full integration and it will hard to debug in production environment..
The REST architectural style describes six constraints. These constraints, put on the architecture, were initially
communicated by Roy Fielding in his doctoral dissertation and defines the basis of RESTful-style.
1. Uniform Interface
2. Stateless
3. Cacheable
4. Client-Server
5. Layered System
6. Code on Demand
Uniform Interface
The uniform interface constraint defines the interface between clients and servers.
In other terms,
First constraint of the REST API states that the Client and server has to communicate and agree to certain
rules based on resources(they should communicate with same resource like json, xml, html , txt) and with
proper encoding like UTF-8 extra.
Another point they should communicate with the Self-descriptive Messages e.g Use the same MIME types.
Stateless
APIs in REST are stateless and Client and server doesn’t worry about the state of the request or response..
Cacheable
According to the World Wide Web, clients can cache responses. Responses should therefore, implicitly or
explicitly, define themselves as cacheable. Its upto server when they want the cache to expired etc.
Client-Server
Client and Server are two different entity, It means that servers and clients may also be replaced and
developed independently, as long as the interface is not altered.
Layered System.
It means that the between client and server there can be any number of layered systems it does not matter.
Code on Demand
Server can store the Code or logic to themselves and transfer it whenever needed rather client side logic.
If any API fulfill all the constraints then we can it REST API.
Difference between REST API vs SOAP API.
We have already discussed REST API , Lets now Learn what is SOAP API.
SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs that run on disparate
operating systems or services like frontend or backend to communicate using Hypertext Transfer Protocol
(HTTP) and its Extensible Markup Language (XML).
SOAP uses WSDL is an XML format for describing network services as a set of endpoints operating on
messages containing either document-oriented or procedure-oriented information.
● Validate the keys with the Min. and Max range of APIs (e.g maximum and minimum length)
● Have a Testcase to do XML,JSON Schema validation.
● Keys verification. If we have JSON, XML apis we should verify it's that all the keys are coming.
● Verify that how the APIs error codes handled.
● Right now, Internet uses millions of APIs and they should be tested thoroughly.
Above image shows the architecture of an application and notice that API Testing is important part..
Now…
HTTP - Fundamentals
HTTP is an application layer protocol designed within the framework of the Internet protocol suite.
There is Client which perform a request resource which can be HTMLPage, file extra from Server and server
perform the response to the client back using the same protocol known as HTTP.
HTTP is a stateless protocol. In other words, the current request does not know what has been done in the
previous requests.
What is an Cookies?
Cookies are usually small text files, given ID tags that are stored on your computer's browser directory or
program data subfolders.
What is Authentication?
Authentication is a process of presenting your credentials like username, password or another secret key to
the system and the system to validate your credentials or you. In the API terms Authentication is used to
protect the content over web mean only a valid user with valid credentials can access that API endpoint.
These credentials tell the system about who you are. Which enables the system to ensures and confirms a
user’s identity. Here system can be anything, it can be a computer, phone, bank or any physical office
premises.
OAuth- Authentication protocol that allows you to approve one application interacting with another on your
behalf without giving away your password.
E.g OAuth 1, 2.
Just for more information, URL can be broken down into the further chunks like protocol, host , post and query
params. More discussion is out of scope for URL
.
HTTP POST Method Explained -
Now we have a HTTP Methods knowledge lets understand what are Cookie and authentication.
Before that take a look into the example api that can available freely.
https://api.chucknorris.io/jokes/random
● Runscope.com
● Postman CI/CD
● Katalon using CI/CD
● SoapUI CI/CD
● Rest Assured CI/CD
It is an API Testing tool used by developers and Testers to perform API Testing with lots of different features
like Global variables, mock request, Environment and monitoring of APIs.
You can learn more about a postman in my full Video lecture series here. Download and install it.
P.S – This article assumes that you have some experience with Postman. If not please go through my previous
tutorials.
Web Services
SOAP (Simple Object Access Protocol) is a standard protocol defined by the W3C standards
for sending and receiving web service requests and responses.
REST (REpresentational State Transfer) is the web standards-based architecture that uses
HTTP. Unlike SOAP-based Web services, there is no official standard for RESTful Web
CRUD Create, Read, Update & Delete
HTTP Request Methods
GET It fetches the information from the server. Moreover, it is the most commonly used
method which does not have a request body. Every time you open a website, the Get
request fires to retrieve the website contents. Additionally, it is equivalent to the
POST It works to send data to the server. User may add or update data using the Post
request. They send the information that needs to update in the request body.
PUT It is similar to the Post method since it updates the data. The only difference is that
we use it when we have to replace an existing entity completely
PATCH It s again similar to Post and Put methods, but user use it when they have to update
some data partially. Moreover, unlike the Post and Put methods, user may send only
the entity that needs updation in the request body with the Patch method.
HEAD It is similar to the Get method, but it retrieves only the header data and not the
entire response body. User use it when they need to check the document's file size
without downloading the document.
DELETE It deletes the server's representations of resources through the specific URL.
Additionally, just like the Get method, it does not have a request body.
OPTIONS It is not a widely used method when compared to other ones. It returns data
specifying the different methods and the operations supported by the server at the
HTTP Response Status Codes
Code Description
1xx informational response, request was received, continuing process
100 Continue: The client can continue with the request as long as it doesn't get rejected.
101 Switching Protocols: The server is switching protocols.
102 Processing, It indicates that the server has received and is processing the request, but
no response is available yet.
103 Early Hints, it primarily intended to be used with the Link header, letting the user
agent start preloading resources while the server prepares a response.
2xx Success, request was successfully received, understood, and accepted
200 OK: The request succeeded
201 Created: The request succeeded, and a new resource was created as a result. This is
typically the response sent after POST requests, or some PUT requests.
202 Accepted: Request accepted for processing, but in progress
203 Non-Authoritative Information: The information in the entity header is not from an
original source but a third-party
204 No Content: Response with status code and header but no response body
205 Reset Content: The form for the transaction should clear for additional input
206 Partial Content: Response with partial data as specified in Range header
207 Multi-Status, Conveys information about multiple resources, for situations where
multiple status codes might be appropriate.
3xx Redirection, further action needed in order to complete the request
300 Multiple Choices: Response with a list for the user to select and go to a location
301 Moved Permanently: Requested page moved to a new url
302 Found: Requested page moved to a temporary new URL
303 See Other: One can find the Requested page under a different URL
305 Use Proxy: Requested URL need to access through the proxy mentioned in the
Location header
307 Temporary Redirect: Requested page moved to a temporary new URL
308 Permanent Redirect: This means that the resource is now permanently located at
another URI, specified by the Location: HTTP Response header.
4xx Client Error, request contains bad syntax or cannot be fulfilled
400 Bad Request: Server unable to understand the request
401 Unauthorized: Requested content needs authentication credentials
403 Forbidden: Access is forbidden
404 Not Found: Server is unable to find the requested page
405 Method Not Allowed: Method in the request is not allowed
407 Proxy Authentication Required: Need to authenticate with a proxy server
408 Request Timeout: The request took a long time as expected by the server
409 Conflict: Error in completing request due to a conflict
411 Length Required: We require the "Content-Length" for the request to process
415 Unsupported Media Type: Unsupported media-type
417 Expectation Failed, it means the expectation indicated by the Expect request header
field cannot be met by the server.
421 Misdirected Request, request was directed at a server that is not able to produce a
423 response.
Locked, the resource that is being accessed is locked
429 Too Many Requests,user has sent too many requests in a given amount of time
5xx Server Error, the server failed to fulfil an apparently valid request
500 Internal Server Error: Request not completed due to server error
501 Not Implemented: Server doesn't support the functionality
502 Bad Gateway: Invalid response from an upstream server to the server. Hence, the
request not complete
503 Service Unavailable: The server is temporarily down
504 Gateway Timeout: The gateway has timed out
505 HTTP Version Not Supported: Unsupported HTTP protocol version
507 Insufficient Storage, method could not be performed on the resource because the
server is unable to store the representation needed to successfully complete the
511 Network Authentication Required, it indicates that the client needs to authenticate
to gain network access
Cheat Sheet for API Testing with Postman
Author Haradhan Pal
YouTube https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Top API Testing Tools
Katalon Studio Postman
SoapUI Rest-Assured
CITRUS Karate
ReadyAPI Airborne
Jmeter apigee
API Terminologies
API Application Programming Interface (API) is software that acts as an intermediary for
two apps to communicate with each other.
HTTP Hypertext Transfer Protocol is the collection of rules for the transmission of data on
the World Wide Web, like graphic images, text, video, sound, and other multimedia
HTTPS The S in HTTPS stands for "secure." HTTPS uses TLS (or SSL) to encrypt HTTP requests
and responses
URI Uniform Resource Identifier is a string identifier that refers to a resource on the
internet. It is a string of characters that is used to identify any resource on the internet
using location, name, or both.
URL Uniform Resource Locator is used to find the location of the resource on the web. It is
a reference for a resource and a way to access that resource. A URL always shows a
unique resource, and it can be an HTML page, a CSS document, an image, etc.
Layers of API Testing
Three separate layers Presentation (or user interface) layer, the business layer, and the database layer for
modeling and manipulating data.
HTTP Important Response Status Codes
Code Description
1xx informational response, request was received, continuing process
100 Continue: The client can continue with the request as long as it doesn't get rejected.
Web Services
SOAP (Simple Object Access Protocol) is a standard protocol defined by the W3C standards
for sending and receiving web service requests and responses.
REST (REpresentational State Transfer) is the web standards-based architecture that uses
HTTP. Unlike SOAP-based Web services, there is no official standard for RESTful Web
APIs.
CRUD Create, Read, Update & Delete
HTTP Request Methods
GET It fetches the information from the server. Moreover, it is the most commonly used
method which does not have a request body. Every time you open a website, the Get
request fires to retrieve the website contents. Additionally, it is equivalent to the read
operation.
POST It works to send data to the server. User may add or update data using the Post
request. They send the information that needs to update in the request body.
PUT It is similar to the Post method since it updates the data. The only difference is that we
use it when we have to replace an existing entity completely
PATCH It s again similar to Post and Put methods, but user use it when they have to update
some data partially. Moreover, unlike the Post and Put methods, user may send only
the entity that needs updation in the request body with the Patch method.
HEAD It is similar to the Get method, but it retrieves only the header data and not the entire
response body. User use it when they need to check the document's file size without
downloading the document.
DELETE It deletes the server's representations of resources through the specific URL.
Additionally, just like the Get method, it does not have a request body.
OPTIONS It is not a widely used method when compared to other ones. It returns data
specifying the different methods and the operations supported by the server at the
given URL.
Author Haradhan Pal
YouTube https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Checklist for Testing of
Web Application
Web Testing in simple terms is checking your web application for potential bugs be-
fore its made live or before code is moved into the production environment.
During this stage issues such as that of web application security, the functioning of
the site, its access to regular users and its ability to handle traffic is checked.
Functionality testing
What is Functional Testing ?
01. Testing the features and operational behavior of a product to ensure they corre-
spond to its specifications.
02. Testing that ignores the internal mechanism of a system or component and focus-
es solely on the outputs generated in response to selected inputs and execution
conditions.
Test Cookies are working as expected. Cookies are small files used by websites to
primarily remember active user sessions so you do not need to log in every time
you visit a website. Cookie Testing will include
01. Testing cookies (sessions) are deleted either when cache is cleared or when they
reach their expiry.
02. Delete cookies (sessions) and test that login credentials are asked for when you
next visit the site.
Test HTML and CSS to ensure that search engines can crawl your site easily. This
will include
01. Checking for Syntax Errors
02. Readable Color Schemas
03. Standard Compliance. Ensure standards such W3C, OASIS, IETF, ISO, ECMA, or
WS-I are followed.
usability testing
What is Usability Testing ?
01. Usability testing is nothing but the User-friendliness check.
02. In Usability testing, the application flow is tested so that a new user can un-
derstand the application easily.
03. Basically, system navigation is checked in Usability testing.
Database testing
Database is one critical component of your web application and stress must be laid
to test it thoroughly. Testing activities will include-
01. Test if any errors are shown while executing queries.
02. Data Integrity is maintained while creating, updating or deleting data in data-
base.
03. Check response time of queries and fine tune them if necessary.
04. Test data retrieved from your database is shown accurately in your web appli-
cation.
To perform the Database testing, the tester should be aware of the below men-
tioned points:
01. The tester should understand the functional requirements, business logic, ap-
plication flow and database design thoroughly.
02. The tester should figure out the tables, triggers, store procedures, views and
cursors used for the application.
03. The tester should understand the logic of the triggers, store procedures, views
and cursors created.
04. The tester should figure out the tables which get affected when insert update
and delete (DML) operations are performed through the web or desktop appli-
cations.
Test Scenarios for Database Testing
01. Verify the database name: The database name should match with the specifica-
tions.
02. Verify the Tables, columns, column types and defaults. All things should match
with the specifications.
03. Verify whether the column allows a null or not.
04. Verify the Primary and foreign key of each table.
05. Verify the Stored Procedure.
06. Test whether the Stored procedure is installed or not.
07. Verify the Stored procedure name
08. Verify the parameter names, types and number of parameters.
09. Test the parameters if they are required or not.
10. Test the stored procedure by deleting some parameters
11. Test when the output is zero, the zero records should be affected.
12. Test the stored procedure by writing simple SQL queries.
13. Test whether the stored procedure returns the values
14. Test the stored procedure with sample input data.
15. Verify the behavior of each flag in the table.
16. Verify the data gets properly saved into the database after the each page submi-
sion.
17. Verify the data if the DML (Update, delete and insert) operations are performed.
18. Check the length of every field. The field length in the back end and front end
must be same.
19. Verify the database names of QA, UAT and production. The names should
beunique.
20. Verify the encrypted data in the database.
21. Verify the database size. Also test the response time of each query executed.
22. Verify the data displayed on the front end and make sure it is same in the back
end.
23. Verify the data validity by inserting the invalid data in the database.
24. Verify the Triggers.
compatibility testing
The rendering of web elements like buttons, text fields etc. changes with change
in Operating System. Make sure your website works fine for various combination
of Operating systems such as Windows, Linux, Mac and Browsers such as Firefox,
Internet Explorer, Safari etc.
Web Testing in simple terms is checking your web application for potential bugs be-
fore its made live or before code is moved into the production environment.
During this stage issues such as that of web application security, the functioning of
the site, its access to regular users and its ability to handle traffic is checked.
Functionality testing
What is Functional Testing ?
01. Testing the features and operational behavior of a product to ensure they corre-
spond to its specifications.
02. Testing that ignores the internal mechanism of a system or component and focus-
es solely on the outputs generated in response to selected inputs and execution
conditions.
Test Cookies are working as expected. Cookies are small files used by websites to
primarily remember active user sessions so you do not need to log in every time
you visit a website. Cookie Testing will include
01. Testing cookies (sessions) are deleted either when cache is cleared or when they
reach their expiry.
02. Delete cookies (sessions) and test that login credentials are asked for when you
next visit the site.
Test HTML and CSS to ensure that search engines can crawl your site easily. This
will include
01. Checking for Syntax Errors
02. Readable Color Schemas
03. Standard Compliance. Ensure standards such W3C, OASIS, IETF, ISO, ECMA, or
WS-I are followed.
usability testing
What is Usability Testing ?
01. Usability testing is nothing but the User-friendliness check.
02. In Usability testing, the application flow is tested so that a new user can un-
derstand the application easily.
03. Basically, system navigation is checked in Usability testing.
Database testing
Database is one critical component of your web application and stress must be laid
to test it thoroughly. Testing activities will include-
01. Test if any errors are shown while executing queries.
02. Data Integrity is maintained while creating, updating or deleting data in data-
base.
03. Check response time of queries and fine tune them if necessary.
04. Test data retrieved from your database is shown accurately in your web appli-
cation.
To perform the Database testing, the tester should be aware of the below men-
tioned points:
01. The tester should understand the functional requirements, business logic, ap-
plication flow and database design thoroughly.
02. The tester should figure out the tables, triggers, store procedures, views and
cursors used for the application.
03. The tester should understand the logic of the triggers, store procedures, views
and cursors created.
04. The tester should figure out the tables which get affected when insert update
and delete (DML) operations are performed through the web or desktop appli-
cations.
Test Scenarios for Database Testing
01. Verify the database name: The database name should match with the specifica-
tions.
02. Verify the Tables, columns, column types and defaults. All things should match
with the specifications.
03. Verify whether the column allows a null or not.
04. Verify the Primary and foreign key of each table.
05. Verify the Stored Procedure.
06. Test whether the Stored procedure is installed or not.
07. Verify the Stored procedure name
08. Verify the parameter names, types and number of parameters.
09. Test the parameters if they are required or not.
10. Test the stored procedure by deleting some parameters
11. Test when the output is zero, the zero records should be affected.
12. Test the stored procedure by writing simple SQL queries.
13. Test whether the stored procedure returns the values
14. Test the stored procedure with sample input data.
15. Verify the behavior of each flag in the table.
16. Verify the data gets properly saved into the database after the each page submi-
sion.
17. Verify the data if the DML (Update, delete and insert) operations are performed.
18. Check the length of every field. The field length in the back end and front end
must be same.
19. Verify the database names of QA, UAT and production. The names should
beunique.
20. Verify the encrypted data in the database.
21. Verify the database size. Also test the response time of each query executed.
22. Verify the data displayed on the front end and make sure it is same in the back
end.
23. Verify the data validity by inserting the invalid data in the database.
24. Verify the Triggers.
compatibility testing
The rendering of web elements like buttons, text fields etc. changes with change
in Operating System. Make sure your website works fine for various combination
of Operating systems such as Windows, Linux, Mac and Browsers such as Firefox,
Internet Explorer, Safari etc.
What is Database?
Database is a collection of interrelated data.
What is DBMS?
DBMS (Database Management System) is software used to create, manage, and organize
databases.
What is RDBMS?
● RDBMS (Relational Database Management System) - is a DBMS based on the
concept of tables (also called relations).
● Data is organized into tables (also known as relations) with rows (records) and
columns (attributes).
● Eg - MySQL, PostgreSQL, Oracle etc.
What is SQL?
SQL is Structured Query Language - used to store, manipulate and retrieve data from
RDBMS.
(It is not a database, it is a language used to interact with database)
*Note - SQL keywords are NOT case sensitive. Eg: select is the same as SELECT in SQL.
*Note - CHAR is for fixed length & VARCHAR is for variable length strings. Generally,
VARCHAR is better as it only occupies necessary memory & works more efficiently.
We can also use UNSIGNED with datatypes when we only have positive values to add.
Eg - UNSIGNED INT
2. DDL (Data Definition Language) : Used to create, alter, and delete database objects
like tables, indexes, etc. (CREATE, DROP, ALTER, RENAME, TRUNCATE)
4. DCL (Data Control Language): Used to grant & revoke permissions. (GRANT,
REVOKE)
DDL commands enable you to create, modify, and delete database objects like tables,
indexes, constraints, and more.
● CREATE TABLE:
● ALTER TABLE:
● DROP TABLE:
○ Used to delete an existing table along with its data and structure.
○ Example: DROP TABLE employees;
● CREATE INDEX:
● DROP INDEX:
● CREATE CONSTRAINT:
● DROP CONSTRAINT:
● TRUNCATE TABLE:
○ Used to delete the data inside a table, but not the table itself.
○ Syntax – TRUNCATE TABLE table_name
DQL (Data Query Language) is a subset of SQL focused on retrieving data from databases.
The SELECT statement is the foundation of DQL and allows us to extract specific columns
from a table.
● SELECT:
Here, column1, column2, ... are the field names of the table.
If you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
● WHERE:
= : Equal
> : Greater than
< : Less than
>= : Greater than or equal
<= : Less than or equal
<> : Not equal.
- The WHERE clause can be combined with AND, OR, and NOT operators.
- The AND and OR operators are used to filter records based on more than one
condition:
- The AND operator displays a record if all the conditions separated by AND are
TRUE.
Syntax:
SELECT column1, column2, ... FROM table_name WHERE condition1 AND condition2 AND
condition3 ...;
Example:
● DISTINCT:
● LIKE:
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
● IN:
● BETWEEN:
● IS NULL:
● AS:
● ORDER BY
The ORDER BY clause allows you to sort the result set of a query based on one or more
columns.
Basic Syntax:
- The ORDER BY clause is used after the SELECT statement to sort query results.
- Syntax: SELECT column1, column2 FROM table_name ORDER BY column1
[ASC|DESC];
- You can sort by multiple columns by listing them sequentially in the ORDER BY
clause.
- Rows are first sorted based on the first column, and for rows with equal values,
subsequent columns are used for further sorting.
- Example: SELECT first_name, last_name FROM employees ORDER BY last_name,
first_name;
Sorting by Expressions:
- By default, NULL values are considered the smallest in ascending order and the
largest in descending order.
- You can control the sorting behaviour of NULL values using the NULLS FIRST or
NULLS LAST options.
- Example: SELECT column_name FROM table_name ORDER BY column_name
NULLS LAST;
Sorting by Position:
- Instead of specifying column names, you can sort by column positions in the ORDER
BY clause.
- Example: SELECT product_name, price FROM products ORDER BY 2 DESC, 1
ASC;
● GROUP BY
The GROUP BY clause in SQL is used to group rows from a table based on one or more
columns.
Syntax:
- The GROUP BY clause follows the SELECT statement and is used to group rows
based on specified columns.
- Aggregation Functions:
○ Aggregation functions (e.g., COUNT, SUM, AVG, MAX, MIN) are often used
with GROUP BY to calculate values for each group.
○ Example: SELECT department, AVG(salary) FROM employees GROUP BY
department;
- Grouping by Multiple Columns:
○ You can group by multiple columns by listing them in the GROUP BY clause.
○ This creates a hierarchical grouping based on the specified columns.
○ Example: SELECT department, gender, AVG(salary) FROM employees
GROUP BY department, gender;
- HAVING Clause:
○ You can use both GROUP BY and ORDER BY in the same query to control
the order of grouped results.
○ Example: SELECT department, COUNT(*) FROM employees GROUP BY
department ORDER BY COUNT(*) DESC;
● AGGREGATE FUNCTIONS
These are used to perform calculations on groups of rows or entire result sets. They provide
insights into data by summarising and processing information.
- COUNT():
Counts the number of rows in a group or result set.
- SUM():
Calculates the sum of numeric values in a group or result set.
- AVG():
Computes the average of numeric values in a group or result set.
- MAX():
Finds the maximum value in a group or result set.
- MIN():
Retrieves the minimum value in a group or result set.
Data Manipulation Language (DML) in SQL encompasses commands that manipulate data
within a database. DML allows you to insert, update, and delete records, ensuring the
accuracy and currency of your data.
● INSERT:
● UPDATE:
● DELETE:
DCL commands are used to control who can access the data, modify the data, or perform
administrative tasks within a database.
DCL is an important aspect of database security, ensuring that data remains protected and
only authorised users have the necessary privileges.
There are two main DCL commands in SQL: GRANT and REVOKE.
1. GRANT:
The GRANT command is used to provide specific privileges or permissions to users or roles.
Privileges can include the ability to perform various actions on tables, views, procedures,
and other database objects.
Syntax:
GRANT privilege_type
ON object_name
TO user_or_role;
In this syntax:
2. REVOKE:
The REVOKE command is used to remove or revoke specific privileges or permissions that
have been previously granted to users or roles.
Syntax:
REVOKE privilege_type
ON object_name
FROM user_or_role;
In this syntax:
Example: Revoking the SELECT privilege on the "Employees" table from the "Analyst" user:
DCL plays a crucial role in ensuring the security and integrity of a database system.
By controlling access and permissions, DCL helps prevent unauthorised users from
tampering with or accessing sensitive data. Proper use of GRANT and REVOKE commands
ensures that only users who require specific privileges can perform certain actions on
database objects.
Transaction Control Language (TCL) deals with the management of transactions within a
database.
TCL commands are used to control the initiation, execution, and termination of transactions,
which are sequences of one or more SQL statements that are executed as a single unit of
work.
Transactions ensure data consistency, integrity, and reliability in a database by grouping
related operations together and either committing or rolling back changes based on the
success or failure of those operations.
There are three main TCL commands in SQL: COMMIT, ROLLBACK, and SAVEPOINT.
1. COMMIT:
The COMMIT command is used to permanently save the changes made during a
transaction.
It makes all the changes applied to the database since the last COMMIT or ROLLBACK
command permanent.
Once a COMMIT is executed, the transaction is considered successful, and the changes are
made permanent.
UPDATE Employees
SET Salary = Salary * 1.10
WHERE Department = 'Sales';
COMMIT;
2. ROLLBACK:
ROLLBACK is typically used when an error occurs during the execution of a transaction,
ensuring that the database remains in a consistent state.
BEGIN;
UPDATE Inventory
SET Quantity = Quantity - 10
WHERE ProductID = 101;
ROLLBACK;
3. SAVEPOINT:
The SAVEPOINT command creates a named point within a transaction, allowing you to set a
point to which you can later ROLLBACK if needed.
SAVEPOINTs are useful when you want to undo part of a transaction while preserving other
changes.
BEGIN;
UPDATE Accounts
SET Balance = Balance - 100
WHERE AccountID = 123;
SAVEPOINT before_withdrawal;
UPDATE Accounts
SET Balance = Balance + 100
WHERE AccountID = 456;
ROLLBACK TO before_withdrawal;
COMMIT;
Transaction Control Language (TCL) commands are vital for managing the integrity and
consistency of a database's data.
They allow you to group related changes into transactions, and in the event of errors, either
commit those changes or roll them back to maintain data integrity.
TCL commands are used in combination with Data Manipulation Language (DML) and other
SQL commands to ensure that the database remains in a reliable state despite unforeseen
errors or issues.
JOINS
In a DBMS, a join is an operation that combines rows from two or more tables based on a
related column between them.
Joins are used to retrieve data from multiple tables by linking them together using a common
key or column.
Types of Joins:
1. Inner Join
2. Outer Join
3. Cross Join
4. Self Join
1) Inner Join
An inner join combines data from two or more tables based on a specified condition, known
as the join condition.
The result of an inner join includes only the rows where the join condition is met in all
participating tables.
It essentially filters out non-matching rows and returns only the rows that have matching
values in both tables.
Syntax:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
Here:
● columns refers to the specific columns you want to retrieve from the tables.
● table1 and table2 are the names of the tables you are joining.
● column is the common column used to match rows between the tables.
● The ON clause specifies the join condition, where you define how the tables are
related.
Customers Table:
CustomerID CustomerName
1 Alice
2 Bob
3 Carol
Orders Table:
102 3 Smartphone
103 2 Headphones
Result:
CustomerName Product
Alice Laptop
Bob Headphones
Carol Smartphone
2) Outer Join
Outer joins combine data from two or more tables based on a specified condition, just like
inner joins. However, unlike inner joins, outer joins also include rows that do not have
matching values in both tables.
Outer joins are particularly useful when you want to include data from one table even if there
is no corresponding match in the other table.
Types:
There are three types of outer joins: left outer join, right outer join, and full outer join.
A left outer join returns all the rows from the left table and the matching rows from the right
table.
If there is no match in the right table, the result will still include the left table's row with NULL
values in the right table's columns.
Example:
Result:
CustomerName Product
Alice Laptop
Bob Headphones
Carol Smartphone
NULL Monitor
In this example, the left outer join includes all rows from the Customers table.
Since there is no matching customer for the order with OrderID 103 (Monitor), the result
includes a row with NULL values in the CustomerName column.
A right outer join is similar to a left outer join, but it returns all rows from the right table and
the matching rows from the left table.
If there is no match in the left table, the result will still include the right table's row with NULL
values in the left table's columns.
Result:
CustomerName Product
Alice Laptop
Carol Smartphone
Bob Headphones
NULL Keyboard
Here, the right outer join includes all rows from the Orders table. Since there is no matching
order for the customer with CustomerID 4, the result includes a row with NULL values in the
CustomerName column.
A full outer join returns all rows from both the left and right tables, including matches and
non-matches.
If there's no match, NULL values appear in columns from the table where there's no
corresponding value.
Result:
CustomerName Product
Alice Laptop
Bob Headphones
Carol Smartphone
NULL Monitor
NULL Keyboard
In this full outer join example, all rows from both tables are included in the result. Both
non-matching rows from the Customers and Orders tables are represented with NULL
values.
3) Cross Join
A cross join, also known as a Cartesian product, is a type of join operation in a Database
Management System (DBMS) that combines every row from one table with every row from
another table.
Unlike other join types, a cross join does not require a specific condition to match rows
between the tables. Instead, it generates a result set that contains all possible combinations
of rows from both tables.
Cross joins can lead to a large result set, especially when the participating tables have many
rows.
Syntax:
SELECT columns
FROM table1
CROSS JOIN table2;
In this syntax:
● columns refers to the specific columns you want to retrieve from the cross-joined
tables.
● table1 and table2 are the names of the tables you want to combine using a cross
join.
Students Table:
StudentID StudentName
1 Alice
2 Bob
Courses Table:
CourseID CourseName
101 Maths
102 Science
Result:
StudentName CourseName
Alice Maths
Alice Science
Bob Maths
Bob Science
In this example, the cross join between the Students and Courses tables generates all
possible combinations of rows from both tables. As a result, each student is paired with each
course, leading to a total of four rows in the result set.
4) Self Join
This technique is useful when a table contains hierarchical or related data and you need to
compare or analyse rows within the same table.
Self joins are commonly used to find relationships, hierarchies, or patterns within a single
table.
In a self join, you treat the table as if it were two separate tables, referring to them with
different aliases.
Syntax:
SELECT columns
FROM table1 AS alias1
JOIN table1 AS alias2 ON alias1.column = alias2.column;
In this syntax:
● columns refers to the specific columns you want to retrieve from the self-joined table.
● table1 is the name of the table you're joining with itself.
● alias1 and alias2 are aliases you assign to the table instances for differentiation.
● column is the column you use as the join condition to link rows from the same table.
Example: Consider an Employees table that contains information about employees and their
managers.
Employees Table:
1 Alice 3
2 Bob 3
3 Carol NULL
4 David 1
Result:
Employee Manager
Alice Carol
Bob Carol
David Alice
In this example, the self join is performed on the Employees table to find the relationship
between employees and their managers. The join condition connects the ManagerID column
in the e1 alias (representing employees) with the EmployeeID column in the e2 alias
(representing managers).
SET OPERATIONS
Set operations in SQL are used to combine or manipulate the result sets of multiple SELECT
queries.
They allow you to perform operations similar to those in set theory, such as union,
intersection, and difference, on the data retrieved from different tables or queries.
Set operations provide powerful tools for managing and manipulating data, enabling you to
analyse and combine information in various ways.
● UNION
● INTERSECT
● EXCEPT (or MINUS)
● UNION ALL
1. UNION:
The UNION operator combines the result sets of two or more SELECT queries into a single
result set.
It removes duplicates by default, meaning that if there are identical rows in the result sets,
only one instance of each row will appear in the final result.
Example:
CustomerID CustomerName
1 Alice
2 Bob
Suppliers Table:
SupplierID SupplierName
101 SupplierA
102 SupplierB
UNION Query:
Result:
CustomerName
Alice
Bob
SupplierA
SupplierB
2. INTERSECT:
The INTERSECT operator returns the common rows that exist in the result sets of two or
more SELECT queries.
Result:
CustomerName
In this example, there are no common names between customers and suppliers, so the
result is an empty set.
The EXCEPT operator (also known as MINUS in some databases) returns the distinct rows
that are present in the result set of the first SELECT query but not in the result set of the
second SELECT query.
Result:
CustomerName
Alice
Bob
In this example, the names "Alice" and "Bob" are customers but not suppliers, so they
appear in the result set.
4. UNION ALL:
The UNION ALL operator performs the same function as the UNION operator but does not
remove duplicates from the result set. It simply concatenates all rows from the different
result sets.
Example: Using the same tables as before.
Result:
CustomerName
Alice
Bob
SupplierA
SupplierB
duplicates. conditions.
Usage Scenarios analysing related data from from different tables based on
Result sets may have different Result sets can have different
Result Set
column names, but data types and column names, data types, and
Structure
counts must match. counts.
SUB QUERIES
Subqueries, also known as nested queries or inner queries, allow you to use the result of
one query (the inner query) as the input for another query (the outer query).
Subqueries are often used to retrieve data that will be used for filtering, comparison, or
calculation within the context of a larger query.
They are a way to break down complex tasks into smaller, manageable steps.
Syntax:
SELECT columns
FROM table
WHERE column OPERATOR (SELECT column FROM table WHERE condition);
In this syntax:
● columns refers to the specific columns you want to retrieve from the outer query.
● table is the name of the table you're querying.
● column is the column you're applying the operator to in the outer query.
● OPERATOR is a comparison operator such as =, >, <, IN, NOT IN, etc.
● (SELECT column FROM table WHERE condition) is the subquery that provides the
input for the comparison.
Products Table:
1 Laptop 1000
2 Smartphone 500
3 Headphones 50
Orders Table:
101 1 2
102 3 1
For Example: Retrieve the product names and quantities for orders with a total cost greater
than the average price of all products.
Result:
ProductName Quantity
Laptop 2
Not used for combining rows; Combines rows from different tables
Combining Rows
used to filter or evaluate data. based on specified join conditions.
Test Scenarios
Test Script
Test
Scenarios
A Test Scenario is any functionality that
can be tested. It is also called Test
Condition or Test Possibility.
01
Test
Cases
It is a document that contains the steps
that have to be executed; it has been
planned earlier.
02
Test
Script
It is written in a programming language
and it’s a short program used to test
part of the functionality of the software
system. In other words, a written set of
steps that should be performed
manually.
03
Software Testing
Cyber Security
www.precisetestingsolution.com
Email Sentences and Phrases
in different situations
Basics Email
Design and preparation by Eng. \ Mustafa Gouda
Formal / Neutral Informal
Dear Mr/Ms/Mrs Dupuis Hi/Hello Mary
Name
Dear Mary Mary,... (or no name at all)
Thank you for your email of ... Thanks for your email.
Previous
Further to your last email, ... Re your email, ...
contact
I apologize for not getting in contact with Sorry I haven’t written for ages, but I’ve
you before now. been really busy.
I am writing in connection with ... Just a short note about ...
I am writing with regard to ... I’m writing about ...
Reason for
In reply to your email, here are ... Here’s the ... you wanted.
writing
Your name was given to me by ... I got your name from ...
We would like to point out that ... Please note that ...
I’m writing to let you know that ... Just a note to say ...
Giving We are able to confirm that ... We can confirm that ...
information I am delighted to tell you that ... Good news!
We regret to inform you that ... Unfortunately, ...
Please find attached my report. I’ve attached ...
Attachments
I’m sending you ... as a pdf file. Here is the ... you wanted.
Could you give me some information
Can you tell me a little more about ...
Asking for about ...
I’d like to know ...
information I would like to know ...
Please send me ...
I’m interested in receiving/finding out ...
I’d be grateful if you could ...
Please could you ...
I wonder if you could ...
Could you ...?
Requests Do you think I could have ... ?
Can I have ...?
Thank you in advance for your help in this
I’d appreciate your help on this.
matter.
I will ... I’ll ...
Promising
I’ll investigate the matter. I’ll look into it.
action
I will contact you again shortly. I’ll get back to you soon.
Would you like me to ...?
Do you want me to ...?
If you wish, I would be happy to ...
Offering help Shall I ...?
Let me know whether you would like me
Let me know if you’d like me to ...
to ...
Thank you for your help.
Thanks again for ...
Do not hesitate to contact us again if you
Final Let me know if you need anything else.
require any further information.
comments Just give me a call if you have any
Please feel free to contact me if you have
questions. My number is ...
any questions. My direct line is ...
I’m looking forward to ... (+ ing) Looking forward to ... (+ ing)
Give my regards to ... Best wishes to ..
Close
Best wishes Speak to/see you soon.
Regards Bye (for now)/All the best
Negotiating a project
Asking for information What are your usual charges (fees/rates) for ...?
Checking understanding
Did you get my last message sent on ...?
Technical Sorry, you forgot to attach the file. Can you send it again?
problems I got your email, but I can’t open the attachment.
Did you mean to send this? I don’t want to open it in case it’s got a virus.
I’m not sure what you meant by ...? could you clarify?
Asking for
Which ... do you mean? / Are you sure about that?
clarification
I don’t understand this point. Can you explain in a little more detail?
Sorry, what I meant was ..., not ...
Giving I thought ..., but I may be wrong. / I’ll check and get back to you.
clarification The correct information is given below. Please amend your records accordingly.
Sorry, forget my last email. You’re right.
Close I hope this clarifies the situation. / Get back to me if there’s anything else.
Arrangements Meetings
Formal / Neutral Informal
I’m writing to arrange a time for our
Reason for Just a quick note to arrange a time to meet.
meeting.
writing When would suit you?
What time would be convenient for you?
Suggesting Could we meet on (day) in the (morning) at How about (day) at (time)?
time/place (time)? Are you free sometime next week?
I would be able to attend the meeting on
I’m free Thursday am.
Saying when Thursday morning.
I won’t be around until after lunch.
you are/ are I’m out of the office until 2pm.
Any time after hat is okay.
not free Any time after that would be fine.
Sorry, can’t make it next Monday.
I’m afraid I can’t manage next Monday.
I’d like to confirm ... Thursday is good for me.
Confirming That’s fine. I will call/email you tomorrow to That should be okay. I’ll get back to you if
confirm the details. there’s a problem.
This is to let you know that I will not be able Re our meeting next week, I’m afraid I can’t
Changing to attend the next meeting next Thursday. make Thursday.
arrangements I wonder if we could move it to ...? How about ... instead?
I apologize for any inconvenience caused. Sorry for the inconvenience.
I look forward to meeting you in Brussels.
See you in Brussels.
Close Let me know if you need to change the
Give me a call if anything changes.
arrangements.
Invitations
Design and preparation by Eng. \ Mustafa Gouda
Formal / Neutral Informal
We would be very pleased if you could come
to ...
I’m writing to invite you to ...
I would like to invite you to ... / attend our ...
Inviting Would you like to come to ...?
Please let me know if you will be able to
Please let me know if you can make it.
attend.
Writing Styles
Formal / Neutral Informal
Thank you for your email received 12 Feb.
With regard/reference to ... Thanks for the email.
I would be grateful if you could ... Re ...
We regret to advise you that ... Please could you ...
Please accept our apologies for ... I’m sorry to tell you that ...
I was wondering if you could ... I’m sorry for ...
We note that you have not ... Could you ...?
Example We would like to remind you that ... You haven’t ...
phrases It is necessary for me to ... Don’t forget that ...
It is possible that I will ... I need to ...
Would you like me to ...? I might ...
However, .../In addition, ... / Therefore, ... Shall I ...?
If you require any further information, But, ... / Also, ... / So, ...
please do not hesitate to contact me. If you’d like more details, let me know.
I look forward to meeting you next week See you next week.
Direct / Indirect
Design and preparation by Eng. \ Mustafa Gouda
Direct Indirect: polite / diplomatic
Can you ...? Could you ...?
Requests
Please could you ... I was wondering if you could ...
Asking for Can I ...? Is it all right if ...?
permission Could I ...? I wonder if I could ...?
Offering help Can I ...? / Shall I ...? Would you like me to ..? / Do you need any help with ...?
Making a What about ... (+ing)? Why don’t we ...?
suggestion Shall we ...? Perhaps we should ...?
I’m afraid there is a small problem.
It seems there is a slight problem.
There is a problem. That might be quite expensive.
That will be very expensive. Won’t that be a bit expensive?
Softening a
We can’t do that . I’m not sure we can do that.
strong
That gives us very little time. Actually, that doesn’t give us much time. Wouldn’t it be
comment
It will be better to ask Heidi. better to ask Heidi?
I disagree. I can see what you’re saying, but ...
Don’t you think that ...?
To be honest, I think it might be better to ...
I hope that you will deal with this matter promptly as it is causing me considerable
Close inconvenience.
Apologizing (supplier)
Open I am writing in relation to your recent complaint.
I was very concerned to learn about ... Please accept my sincere apologies.
Apologizing I would like to apologize for the inconvenience you have suffered.
We appreciate that this has caused you considerable inconvenience, but we cannot accept
Denying
any responsibility in this matter.
responsibility
Can you leave it with me? I’ll look into the matter and get back to you tomorrow.
I have looked into the matter and ...
I have spoken to the staff involved, and ...
Promising
We will send replacement items / give you a refund immediately.
action
I can assure you that this will not happen again.
We’re having a temporary problem with ... . We’re doing everything we can to sort it out.
Giving advice
Formal/Neutral Informal
I was sorry to hear about your current
I’m sorry you’re having such a hard time at the
Open difficulties.
moment.
I think it might be a good idea to ...
Giving I think you should ...
Have you thought of ... (+ing)?
advice What about ... (+ing)?
This would mean that ...
Result That way, ...
I think this option would be preferable
Options to ... (+ing) I think it’s better than ... (+ing)
Close
I hope I have been of some help. I hope I’ve helped a bit.
Special situations
Just a quick note to say many thanks for ...
Thanks I really appreciate everything that you have done.
Good luck with ...I would like to take this opportunity to wish you every success
Good luck in the future.
Job Application
Greeting Dear Sir/Madam
Reason for With reference to your advertisement on the ... website, I am interested in applying
writing for the post of...
Your
background I am 26 years old and am currently studying for a degree in ... at ... University.
and For the last two months I have been working as a ... at ... .
experience
I am interested in this job because ...
The job itself
I feel that I would be well-suited for this job/have a lot of experience in ...
Referring to I have attached my CV as a Word document. You will notice that I ... as well as ... .
your CV You will also notice that ... .
I would be grateful if you would consider my application.
You will see from my CV that two people can be contacted as references, one is ...
Final
and the other is from ... .
comments
I am available for interview in .../ by phone any weekday afternoon, and you can
email me or telephone me on the number below.
I look forward to hearing from you soon.
Close
Yours faithfully
Linking words
Sequence Firstly / secondly / finally
Talking generally In general / usually / on the whole
Contrast However / nevertheless / on the other hand
Adding another point In addition / moreover / on another point
Examples For example / for instance / e.g.
Alternatives Either ... or ... / alternatively / instead of ...
Real (surprising) situation In fact, / actually, / as a matter of fact
Something is obvious Clearly / obviously / of course
Most important point Especially / above all / in particular
Rephrasing In other words / that is to say / i.e.
Result/consequence As a result / therefore / for this reason
New topic In relation to / regarding / with reference to
1 of
1 of 246
288
Contents
3 Isomorphic Strings 21
4 Word Ladder 23
5 Word Ladder II 25
8 Wildcard Matching 33
10 Merge Intervals 39
11 Insert Interval 41
12 Two Sum 43
15 3Sum 49
16 4Sum 53
17 3Sum Closest 55
20 Valid Parentheses 61
2 | 531
2 of
2 of 246
288
Contents
22 Implement strStr() 65
26 Valid Palindrome 77
27 ZigZag Conversion 81
28 Add Binary 83
30 Triangle 87
31 Contains Duplicate 89
32 Contains Duplicate II 91
3 of
3 of 246
288
Contents
58 Candy 149
68 Get Target Number Using Number List and Arithmetic Operations 169
4 of
4 of 246
288
Contents
5 of
5 of 246
288
Contents
6 of
6 of 246
288
1 Rotate Array in Java
You may have been using Java for a while. Do you think a simple Java array question
can be a challenge? Let’s use the following problem to test.
Problem: Rotate an array of n elements to the right by k steps. For example, with n
= 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. How many different
ways do you know to solve this problem?
In a straightforward way, we can create a new array and then copy elements to the
new array. Then change the original array by using System.arraycopy().
public void rotate(int[] nums, int k) {
if(k > nums.length)
k=k%nums.length;
int j=0;
for(int i=k; i<nums.length; i++){
result[i] = nums[j];
j++;
}
Space is O(n) and time is O(n). You can check out the difference between Sys-
tem.arraycopy() and Arrays.copyOf().
13 | 531
7 of
7 of 246
288
1 Rotate Array in Java
Can we do this in O(1) space and in O(n) time? The following solution does.
Assuming we are given 1,2,3,4,5,6 and order 2. The basic idea is:
1. Divide the array two parts: 1,2,3,4 and 5, 6
2. Reverse first part: 4,3,2,1,5,6
3. Reverse second part: 4,3,2,1,6,5
4. Reverse the whole array: 5,6,1,2,3,4
8 of
8 of 246
288
1 Rotate Array in Java
reverse(arr, 0, a-1);
reverse(arr, a, arr.length-1);
reverse(arr, 0, arr.length-1);
9 of
9 of 246
288
2 Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid op-
erators are +, -, *, /. Each operand may be an integer or another expression. For
example:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
This problem can be solved by using a stack. We can loop through each element in the
given array. When it is a number, push it to the stack. When it is an operator, pop two
numbers from the stack, do the calculation, and push back the result.
The following is the code. However, this code contains compilation errors in leet-
code. Why?
public class Test {
17 | 531
11 of
10 of 246
288
2 Evaluate Reverse Polish Notation
returnValue = Integer.valueOf(stack.pop());
return returnValue;
}
}
The problem is that switch string statement is only available from JDK 1.7. Leetcode
apparently use a JDK version below 1.7.
If you want to use switch statement, you can convert the above by using the following
code which use the index of a string "+-*/".
public class Solution {
public int evalRPN(String[] tokens) {
int returnValue = 0;
12 of
11 of 246
288
2 Evaluate Reverse Polish Notation
for(String t : tokens){
if(!operators.contains(t)){
stack.push(t);
}else{
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
int index = operators.indexOf(t);
switch(index){
case 0:
stack.push(String.valueOf(a+b));
break;
case 1:
stack.push(String.valueOf(b-a));
break;
case 2:
stack.push(String.valueOf(a*b));
break;
case 3:
stack.push(String.valueOf(b/a));
break;
}
}
}
returnValue = Integer.valueOf(stack.pop());
return returnValue;
}
}
13 of
12 of 246
288
3 Isomorphic Strings
Given two strings s and t, determine if they are isomorphic. Two strings are isomor-
phic if the characters in s can be replaced to get t.
For example,"egg" and "add" are isomorphic, "foo" and "bar" are not.
3.1 Analysis
We need to define a method which accepts a map & a value, and returns the value’s
key in the map.
if(s.length() != t.length())
return false;
return true;
}
21 | 531
15 of
13 of 246
288
3 Isomorphic Strings
return null;
}
16 of
14 of 246
288
4 Word Ladder
Given two words (start and end), and a dictionary, find the length of shortest transfor-
mation sequence from start to end, such that only one letter can be changed at a time
and each intermediate word must exist in the dictionary. For example, given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
One shortest transformation is "hit" ->"hot" ->"dot" ->"dog" ->"cog", the program
should return its length 5.
4.1 Analysis
UPDATED on 06/07/2015.
So we quickly realize that this is a search problem, and breath-first search guarantees
the optimal solution.
class WordNode{
String word;
int numSteps;
23 | 531
17 of
15 of 246
288
4 Word Ladder
wordDict.add(endWord);
while(!queue.isEmpty()){
WordNode top = queue.remove();
String word = top.word;
if(word.equals(endWord)){
return top.numSteps;
}
arr[i]=temp;
}
}
}
return 0;
}
}
18 of
16 of 246
288
5 Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation
sequence(s) from start to end, such that: 1) Only one letter can be changed at a time,
2) Each intermediate word must exist in the dictionary.
For example, given: start = "hit", end = "cog", and dict = ["hot","dot","dog","lot","log"],
return:
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
5.1 Analysis
class WordNode{
String word;
int numSteps;
WordNode pre;
25 | 531
19 of
17 of 246
288
5 Word Ladder II
dict.add(end);
int minStep = 0;
int preNumSteps = 0;
while(!queue.isEmpty()){
WordNode top = queue.remove();
String word = top.word;
int currNumSteps = top.numSteps;
if(word.equals(end)){
if(minStep == 0){
minStep = top.numSteps;
}
preNumSteps = currNumSteps;
20 of
18 of 246
288
5 Word Ladder II
arr[i]=temp;
}
}
return result;
}
}
21 of
19 of 246
288
6 Median of Two Sorted Arrays
There are two sorted arrays A and B of size m and n respectively. Find the median of the
two sorted arrays. The overall run time complexity should be O(log (m+n)).
if ((m + n) % 2 != 0) // odd
return (double) findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1);
else { // even
return (findKth(A, B, (m + n) / 2, 0, m - 1, 0, n - 1)
+ findKth(A, B, (m + n) / 2 - 1, 0, m - 1, 0, n - 1)) * 0.5;
}
}
29 | 531
23 of
20 of 246
288
6 Median of Two Sorted Arrays
Solution 1 is a general solution to find the kth element. We can also come up with a
simpler solution which only finds the median of two sorted arrays for this particular
problem. Thanks to Gunner86. The description of the algorithm is awesome!
1) Calculate the medians m1 and m2 of the input arrays ar1[] and ar2[]
respectively.
2) If m1 and m2 both are equal then we are done, and return m1 (or m2)
3) If m1 is greater than m2, then median is present in one of the below two
subarrays.
a) From first element of ar1 to m1 (ar1[0...|_n/2_|])
b) From m2 to last element of ar2 (ar2[|_n/2_|...n-1])
4) If m2 is greater than m1, then median is present in one of the below two
subarrays.
a) From m1 to last element of ar1 (ar1[|_n/2_|...n-1])
b) From first element of ar2 to m2 (ar2[0...|_n/2_|])
5) Repeat the above process until size of both the subarrays becomes 2.
6) If size of the two arrays is 2 then use below formula to get the median.
Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2
24 of
21 of 246
288
7 Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element
in the sorted order, not the kth distinct element.
For example, given [3,2,1,5,6,4] and k = 2, return 5.
Note: You may assume k is always valid, 1 ≤ k ≤ array’s length.
Time is O(nlog(n))
This problem can also be solve by using the quickselect approach, which is similar to
quicksort.
public int findKthLargest(int[] nums, int k) {
if (k < 1 || nums == null) {
return 0;
}
while (true) {
31 | 531
25 of
22 of 246
288
7 Kth Largest Element in an Array
if (left == right) {
break;
}
if (k == left + 1) {
return pivot;
} else if (k < left + 1) {
return getKth(k, nums, start, left - 1);
} else {
return getKth(k, nums, left + 1, end);
}
}
We can use a min heap to solve this problem. The heap stores the top k elements.
Whenever the size is greater than k, delete the min. Time complexity is O(nlog(k)).
Space complexity is O(k) for storing the top k numbers.
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> q = new PriorityQueue<Integer>(k);
for(int i: nums){
q.offer(i);
if(q.size()>k){
q.poll();
}
}
return q.peek();
}
26 of
23 of 246
288
8 Wildcard Matching
Implement wildcard pattern matching with support for ’?’ and ’*’.
return j == p.length();
}
33 | 531
27 of
24 of 246
288
9 Regular Expression Matching in Java
Implement regular expression matching with support for ’.’ and ’*’.
’.’ Matches any single character. ’*’ Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be: bool isMatch(const char *s, const char *p)
Some examples: isMatch("aa","a") return false isMatch("aa","aa") return true isMatch("aaa","aa")
return false isMatch("aa", "a*") return true isMatch("aa", ".*") return true isMatch("ab",
".*") return true isMatch("aab", "c*a*b") return true
9.1 Analysis
First of all, this is one of the most difficulty problems. It is hard to think through all
different cases. The problem should be simplified to handle 2 basic cases:
For the 1st case, if the first char of pattern is not ".", the first char of pattern and
string should be the same. Then continue to match the remaining part.
For the 2nd case, if the first char of pattern is "." or first char of pattern == the first i
char of string, continue to match the remaining part.
if(p.length() == 0)
return s.length() == 0;
}else{
35 | 531
29 of
25 of 246
288
9 Regular Expression Matching in Java
int i = -1;
while(i<len && (i < 0 || p.charAt(0) == ’.’ || p.charAt(0) ==
s.charAt(i))){
if(isMatch(s.substring(i+1), p.substring(2)))
return true;
i++;
}
return false;
}
}
}
// special case
if (p.length() == 1) {
30 of
26 of 246
288
9 Regular Expression Matching in Java
return false;
} else {
return isMatch(s.substring(1), p.substring(1));
}
}
//case 2.2: a char & ’*’ can stand for 1 or more preceding element,
//so try every sub string
int i = 0;
while (i<s.length() && (s.charAt(i)==p.charAt(0) || p.charAt(0)==’.’)){
if (isMatch(s.substring(i + 1), p.substring(2))) {
return true;
}
i++;
}
return false;
}
}
31 of
27 of 246
288
10 Merge Intervals
Problem:
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
The key to solve this problem is defining a Comparator first to sort the arraylist of
Intevals. And then merge some intervals.
The take-away message from this problem is utilizing the advantage of sorted list/ar-
ray.
class Interval {
int start;
int end;
Interval() {
start = 0;
end = 0;
}
Interval(int s, int e) {
start = s;
end = e;
}
}
39 | 531
33 of
28 of 246
288
10 Merge Intervals
result.add(prev);
return result;
}
}
34 of
29 of 246
288
11 Insert Interval
Problem:
Given a set of non-overlapping & sorted intervals, insert a new interval into the intervals
(merge if necessary).
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as
[1,2],[3,10],[12,16].
41 | 531
35 of
30 of 246
288
11 Insert Interval
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class Solution {
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval
newInterval) {
result.add(newInterval);
return result;
}
}
36 of
31 of 246
288
12 Two Sum
Given an array of integers, find two numbers such that they add up to a specific target
number.
The function twoSum should return indices of the two numbers such that they add
up to the target, where index1 must be less than index2. Please note that your returned
answers (both index1 and index2) are not zero-based.
For example:
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
This problem is pretty straightforward. We can simply examine every possible pair of
numbers in this integer array.
Time complexity in worst case: O(n2̂).
public static int[] twoSum(int[] numbers, int target) {
int[] ret = new int[2];
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] == target) {
ret[0] = i + 1;
ret[1] = j + 1;
}
}
}
return ret;
}
Can we do better?
43 | 531
37 of
32 of 246
288
12 Two Sum
return result;
}
}
Time complexity depends on the put and get operations of HashMap which is nor-
mally O(1).
Time complexity of this solution is O(n).
38 of
33 of 246
288
13 Two Sum II Input array is sorted
int i = 0;
int j = numbers.length - 1;
while (i < j) {
int x = numbers[i] + numbers[j];
if (x < target) {
++i;
} else if (x > target) {
j--;
} else {
return new int[] { i + 1, j + 1 };
}
}
return null;
}
45 | 531
39 of
34 of 246
288
14 Two Sum III Data structure design
Design and implement a TwoSum class. It should support the following operations:
add and find.
add - Add the number to an internal data structure. find - Find if there exists any
pair of numbers which sum is equal to the value.
For example,
add(1);
add(3);
add(5);
find(4) -> true
find(7) -> false
Since the desired class need add and get operations, HashMap is a good option for
this purpose.
public class TwoSum {
private HashMap<Integer, Integer> elements = new HashMap<Integer,
Integer>();
47 | 531
41 of
35 of 246
288
14 Two Sum III Data structure design
}
}
42 of
36 of 246
288
15 3Sum
Problem:
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
Naive solution is 3 loops, and this gives time complexity O(n3̂). Apparently this is not
an acceptable solution, but a discussion can start from here.
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
//sort array
Arrays.sort(num);
each.add(num[i]);
each.add(num[j]);
each.add(num[k]);
result.add(each);
each.clear();
}
49 | 531
43 of
37 of 246
288
15 3Sum
}
}
}
return result;
}
}
* The solution also does not handle duplicates. Therefore, it is not only time ineffi-
cient, but also incorrect.
Result:
Submission Result: Output Limit Exceeded
A better solution is using two pointers instead of one. This makes time complexity of
O(n2̂).
To avoid duplicate, we can take advantage of sorted arrays, i.e., move pointers by
>1 to use same element only once.
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (num.length < 3)
return result;
// sort array
Arrays.sort(num);
int start = i + 1;
int end = num.length - 1;
result.add(temp);
44 of
38 of 246
288
15 3Sum
start++;
end--;
//avoid duplicate solutions
while (start < end && num[end] == num[end + 1])
end--;
}
}
return result;
}
45 of
39 of 246
288
16 4Sum
16.1 Thoughts
while (k < l) {
int sum = num[i] + num[j] + num[k] + num[l];
53 | 531
47 of
40 of 246
288
16 4Sum
temp.add(num[j]);
temp.add(num[k]);
temp.add(num[l]);
if (!hashSet.contains(temp)) {
hashSet.add(temp);
result.add(temp);
}
k++;
l--;
}
}
}
}
return result;
}
Here is the hashCode method of ArrayList. It makes sure that if all elements of two
lists are the same, then the hash code of the two lists will be the same. Since each
element in the ArrayList is Integer, same integer has same hash code.
int hashCode = 1;
Iterator<E> i = list.iterator();
while (i.hasNext()) {
E obj = i.next();
hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
}
48 of
41 of 246
288
17 3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a
given number, target. Return the sum of the three integers. You may assume that each
input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
17.1 Analysis
This problem is similar to 2 Sum. This kind of problem can be solved by using a
similar approach, i.e., two pointers from both left and right.
Arrays.sort(nums);
55 | 531
49 of
42 of 246
288
17 3Sum Closest
return result;
}
50 of
43 of 246
288
18 String to Integer (atoi)
18.1 Analysis
// calculate value
while (str.length() > i && str.charAt(i) >= ’0’ && str.charAt(i) <= ’9’) {
result = result * 10 + (str.charAt(i) - ’0’);
57 | 531
51 of
44 of 246
288
18 String to Integer (atoi)
i++;
}
if (flag == ’-’)
result = -result;
52 of
45 of 246
288
19 Merge Sorted Array
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note: You may assume that A has enough space to hold additional elements from
B. The number of elements initialized in A and B are m and n respectively.
19.1 Analysis
The key to solve this problem is moving element of A and B backwards. If B has some
elements left after A is done, also need to handle that case.
The takeaway message from this problem is that the loop condition. This kind of
condition is also used for merging two sorted linked list.
The loop condition also can use m+n like the following.
59 | 531
53 of
46 of 246
288
19 Merge Sorted Array
while (k >= 0) {
if (j < 0 || (i >= 0 && A[i] > B[j]))
A[k--] = A[i--];
else
A[k--] = B[j--];
}
}
54 of
47 of 246
288
20 Valid Parentheses
Given a string containing just the characters ’(’, ’)’, ’’, ’’, ’[’ and ’]’, determine if the
input string is valid. The brackets must close in the correct order, "()" and "()[]" are all
valid but "(]" and "([)]" are not.
20.1 Analysis
if (map.keySet().contains(curr)) {
stack.push(curr);
} else if (map.values().contains(curr)) {
if (!stack.empty() && map.get(stack.peek()) == curr) {
stack.pop();
} else {
return false;
}
}
}
return stack.empty();
}
61 | 531
55 of
48 of 246
288
21 Longest Valid Parentheses
Given a string containing just the characters ’(’ and ’)’, find the length of the longest
valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2. An-
other example is ")()())", where the longest valid parentheses substring is "()()", which
has length = 4.
21.1 Analysis
This problem is similar with Valid Parentheses, which can be solved by using a stack.
return result;
63 | 531
57 of
49 of 246
288
21 Longest Valid Parentheses
58 of
50 of 246
288
22 Implement strStr()
Problem:
Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1
if needle is not part of haystack.
if(needle.length() == 0)
return 0;
int m = i;
for(int j=0; j<needle.length(); j++){
if(needle.charAt(j)==haystack.charAt(m)){
if(j==needle.length()-1)
return i;
m++;
}else{
break;
}
}
}
return -1;
}
65 | 531
59 of
51 of 246
288
22 Implement strStr()
return 0;
int h = haystack.length();
int n = needle.length();
if (n > h)
return -1;
if (n == 0)
return 0;
while (i <= h - n) {
int success = 1;
for (int j = 0; j < n; j++) {
if (needle.charAt(0) != haystack.charAt(i)) {
success = 0;
i++;
break;
} else if (needle.charAt(j) != haystack.charAt(i + j)) {
success = 0;
i = i + j - next[j - 1];
break;
}
}
if (success == 1)
return i;
}
return -1;
}
if (needle.charAt(index) == needle.charAt(i)) {
next[i] = next[i - 1] + 1;
} else {
next[i] = 0;
}
}
60 of
52 of 246
288
22 Implement strStr()
return next;
}
61 of
53 of 246
288
23 Minimum Size Subarray Sum
Given an array of n positive integers and a positive integer s, find the minimal length
of a subarray of which the sum ≥ s. If there isn’t one, return 0 instead.
For example, given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal
length of 2 under the problem constraint.
23.1 Analysis
We can use 2 points to mark the left and right boundaries of the sliding window. When
the sum is greater than the target, shift the left pointer; when the sum is less than the
target, shift the right pointer.
int start=0;
int sum=0;
int i=0;
boolean exists = false;
while(i<=nums.length){
if(sum>=s){
exists=true; //mark if there exists such a subarray
if(start==i-1){
return 1;
}
}else{
if(i==nums.length)
break;
69 | 531
63 of
54 of 246
288
23 Minimum Size Subarray Sum
sum = sum+nums[i];
i++;
}
}
if(exists)
return result;
else
return 0;
}
int i = 0;
int sum = nums[0];
if(j<nums.length){
sum = sum + nums[j];
}else{
return result;
}
}
}else{
//if sum is large enough, move left cursor
if(sum >= s){
result = Math.min(j-i+1, result);
sum = sum - nums[i];
i++;
64 of
55 of 246
288
23 Minimum Size Subarray Sum
if(j<nums.length){
sum = sum + nums[j];
}else{
if(i==0){
return 0;
}else{
return result;
}
}
}
}
}
return result;
}
65 of
56 of 246
288
24 Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not,
return the index where it would be if it were inserted in order. You may assume no
duplicates in the array.
Here are few examples.
[1,3,5,6], 5 -> 2
[1,3,5,6], 2 -> 1
[1,3,5,6], 7 -> 4
[1,3,5,6], 0 -> 0
24.1 Solution 1
Naively, we can just iterate the array and compare target with ith and (i+1)th element.
Time complexity is O(n)
public class Solution {
public int searchInsert(int[] A, int target) {
if(A==null) return 0;
return A.length;
}
}
24.2 Solution 2
This also looks like a binary search problem. We should try to make the complexity to
be O(log(n)).
public class Solution {
public int searchInsert(int[] A, int target) {
73 | 531
67 of
57 of 246
288
24 Search Insert Position
if(A==null||A.length==0)
return 0;
return searchInsert(A,target,0,A.length-1);
}
if(target==A[mid])
return mid;
else if(target<A[mid])
return start<mid?searchInsert(A,target,start,mid-1):start;
else
return end>mid?searchInsert(A,target,mid+1,end):(end+1);
}
}
68 of
58 of 246
288
25 Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements
sequence.
For example, given [100, 4, 200, 1, 3, 2], the longest consecutive elements sequence
should be [1, 2, 3, 4]. Its length is 4.
Your algorithm should run in O(n) complexity.
25.1 Analysis
Because it requires O(n) complexity, we can not solve the problem by sorting the array
first. Sorting takes at least O(nlogn) time.
We can use a HashSet to add and remove elements. HashSet is implemented by using
a hash table. Elements are not ordered. The add, remove and contains methods have
constant time complexity O(1).
public static int longestConsecutive(int[] num) {
// if array is empty, return 0
if (num.length == 0) {
return 0;
}
while (set.contains(left)) {
count++;
set.remove(left);
left--;
}
75 | 531
69 of
59 of 246
288
25 Longest Consecutive Sequence
while (set.contains(right)) {
count++;
set.remove(right);
right++;
}
return max;
}
After an element is checked, it should be removed from the set. Otherwise, time
complexity would be O(mn) in which m is the average length of all consecutive se-
quences.
To clearly see the time complexity, I suggest you use some simple examples and
manually execute the program. For example, given an array 1,2,4,5,3, the program
time is m. m is the length of longest consecutive sequence.
70 of
60 of 246
288
26 Valid Palindrome
26.1 Thoughts
From start and end loop though the string, i.e., char array. If it is not alpha or num-
ber, increase or decrease pointers. Compare the alpha and numeric characters. The
solution below is pretty straightforward.
int i=0;
int j=len-1;
while(i<j){
char left, right;
77 | 531
71 of
61 of 246
288
26 Valid Palindrome
right = charArray[j];
}
if(i >= j)
break;
left = charArray[i];
right = charArray[j];
if(!isSame(left, right)){
return false;
}
i++;
j--;
}
return true;
}
72 of
62 of 246
288
26 Valid Palindrome
int index = 0;
while (index < len / 2) {
stack.push(s.charAt(index));
index++;
}
if (len % 2 == 1)
index++;
return true;
}
In the discussion below, April and Frank use two pointers to solve this problem. This
solution looks really simple.
public class ValidPalindrome {
public static boolean isValidPalindrome(String s){
if(s==null||s.length()==0) return false;
s = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
System.out.println(s);
73 of
63 of 246
288
26 Valid Palindrome
return true;
}
System.out.println(isValidPalindrome(str));
}
}
74 of
64 of 246
288
27 ZigZag Conversion
And then read line by line: "PAHNAPLSIIGYIR" Write the a method convert("PAYPALISHIRING",
3) which returns "PAHNAPLSIIGYIR".
81 | 531
75 of
65 of 246
288
27 ZigZag Conversion
}
}
return sb.toString();
}
76 of
66 of 246
288
28 Add Binary
Given two binary strings, return their sum (also a binary string).
For example, a = "11", b = "1", the return is "100".
int pa = a.length()-1;
int pb = b.length()-1;
int flag = 0;
StringBuilder sb = new StringBuilder();
while(pa >= 0 || pb >=0){
int va = 0;
int vb = 0;
if(flag == 1){
83 | 531
77 of
67 of 246
288
28 Add Binary
sb.append("1");
}
78 of
68 of 246
288
29 Length of Last Word
Very simple question. We just need a flag to mark the start of letters from the end. If
a letter starts and the next character is not a letter, return the length.
public int lengthOfLastWord(String s) {
if(s==null || s.length() == 0)
return 0;
int result = 0;
int len = s.length();
return result;
}
85 | 531
79 of
69 of 246
288
30 Triangle
Given a triangle, find the minimum path sum from top to bottom. Each step you may
move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
This solution gets wrong answer! I will try to make it work later.
public class Solution {
public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
if (triangle.size() == 1) {
return Math.min(minTotal, triangle.get(0).get(0));
}
int a, b;
87 | 531
81 of
70 of 246
288
30 Triangle
}else{
a = temp[j] + triangle.get(i + 1).get(j);
b = temp[j] + triangle.get(i + 1).get(j + 1);
return minTotal;
}
}
return total[0];
}
82 of
71 of 246
288
31 Contains Duplicate
Given an array of integers, find if the array contains any duplicates. Your function
should return true if any value appears at least twice in the array, and it should return
false if every element is distinct.
return false;
}
89 | 531
83 of
72 of 246
288
32 Contains Duplicate II
Given an array of integers and an integer k, return true if and only if there are two
distinct indices i and j in the array such that nums[i] = nums[j] and the difference
between i and j is at most k.
91 | 531
85 of
73 of 246
288
32 Contains Duplicate II
map.put(nums[i], i);
}
return false;
}
86 of
74 of 246
288
33 Contains Duplicate III
Given an array of integers, find out whether there are two distinct indices i and j in
the array such that the difference between nums[i] and nums[j] is at most t and the
difference between i and j is at most k.
set.add(c);
if (i >= k)
set.remove(nums[i - k]);
}
return false;
}
93 | 531
87 of
75 of 246
288
33 Contains Duplicate III
if (!subSet.isEmpty())
return true;
set.add((long) nums[j]);
if (j >= k) {
set.remove((long) nums[j - k]);
}
}
return false;
}
88 of
76 of 246
288
34 Remove Duplicates from Sorted Array
Given a sorted array, remove the duplicates in place such that each element appear
only once and return the new length. Do not allocate extra space for another array,
you must do this in place with constant memory.
For example, given input array A = [1,1,2], your function should return length = 2,
and A is now [1,2].
34.1 Thoughts
The problem is pretty straightforward. It returns the length of array with unique
elements, but the original array need to be changed also. This problem should be
reviewed with Remove Duplicates from Sorted Array II.
34.2 Solution 1
int j = 0;
int i = 1;
return j + 1;
}
This method returns the number of unique elements, but does not change the orig-
inal array correctly. For example, if the input array is 1, 2, 2, 3, 3, the array will be
changed to 1, 2, 3, 3, 3. The correct result should be 1, 2, 3. Because array’s size can
95 | 531
89 of
77 of 246
288
34 Remove Duplicates from Sorted Array
not be changed once created, there is no way we can return the original array with
correct results.
34.3 Solution 2
int j = 0;
int i = 1;
return B;
}
34.4 Solution 3
If we only want to count the number of unique elements, the following method is
good enough.
// Count the number of unique elements
public static int countUnique(int[] A) {
int count = 0;
for (int i = 0; i < A.length - 1; i++) {
if (A[i] == A[i + 1]) {
count++;
90 of
78 of 246
288
34 Remove Duplicates from Sorted Array
}
}
return (A.length - count);
}
91 of
79 of 246
288
35 Remove Duplicates from Sorted Array
II
Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?
For example, given sorted array A = [1,1,1,2,2,3], your function should return length
= 5, and A is now [1,1,2,2,3].
Given the method signature "public int removeDuplicates(int[] A)", it seems that we
should write a method that returns a integer and that’s it. After typing the following
solution:
public class Solution {
public int removeDuplicates(int[] A) {
if(A == null || A.length == 0)
return 0;
if(curr == pre){
if(!flag){
flag = true;
continue;
}else{
count++;
}
}else{
pre = curr;
flag = false;
}
}
99 | 531
93 of
80 of 246
288
35 Remove Duplicates from Sorted Array II
We can not change the given array’s size, so we only change the first k elements of the
array which has duplicates removed.
public class Solution {
public int removeDuplicates(int[] A) {
if (A == null || A.length == 0)
return 0;
if (curr == pre) {
if (!flag) {
flag = true;
A[o++] = curr;
continue;
} else {
count++;
}
} else {
pre = curr;
A[o++] = curr;
flag = false;
}
}
94 of
81 of 246
288
35 Remove Duplicates from Sorted Array II
return prev + 1;
}
}
95 of
82 of 246
288
36 Longest Substring Without Repeating
Characters
Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for "abcabcbb" is "abc",
which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
The first solution is like the problem of "determine if a string has all unique characters"
in CC 150. We can use a flag array to track the existing characters for the longest
substring without repeating characters.
public int lengthOfLongestSubstring(String s) {
if(s==null)
return 0;
boolean[] flag = new boolean[256];
int result = 0;
int start = 0;
char[] arr = s.toCharArray();
103 | 531
97 of
83 of 246
288
36 Longest Substring Without Repeating Characters
return result;
}
This solution is from Tia. It is easier to understand than the first solution.
The basic idea is using a hash table to track existing characters and their posi-
tion. When a repeated character occurs, check from the previously repeated character.
However, the time complexity is higher - O(n3̂).
public static int lengthOfLongestSubstring(String s) {
if(s==null)
return 0;
char[] arr = s.toCharArray();
int pre = 0;
When loop hits the second "a", the HashMap contains the following:
a 0
b 1
c 2
d 3
The index i is set to 0 and incremented by 1, so the loop start from second element
again.
98 of
84 of 246
288
37 Longest Substring Which Contains 2
Unique Characters
In this solution, a hashmap is used to track the unique elements in the map. When a
third character is added to the map, the left pointer needs to move right.
You can use "abac" to walk through this solution.
public int lengthOfLongestSubstringTwoDistinct(String s) {
int max=0;
HashMap<Character,Integer> map = new HashMap<Character, Integer>();
int start=0;
if(map.size()>2){
max = Math.max(max, i-start);
while(map.size()>2){
char t = s.charAt(start);
int count = map.get(t);
if(count>1){
map.put(t, count-1);
}else{
map.remove(t);
}
start++;
}
105 | 531
99 of
85 of 246
288
37 Longest Substring Which Contains 2 Unique Characters
}
}
return max;
}
Now if this question is extended to be "the longest substring that contains k unique
characters", what should we do?
if(map.size()>k){
max = Math.max(max, i-start);
while(map.size()>k){
char t = s.charAt(start);
int count = map.get(t);
if(count>1){
map.put(t, count-1);
}else{
map.remove(t);
}
start++;
}
}
}
return max;
}
86 of
100 of246
288
37 Longest Substring Which Contains 2 Unique Characters
Time is O(n).
87 of
101 of246
288
38 Substring with Concatenation of All
Words
You are given a string, s, and a list of words, words, that are all of the same length.
Find all starting indices of substring(s) in s that is a concatenation of each word in
words exactly once and without any intervening characters.
For example, given: s="barfoothefoobarman" & words=["foo", "bar"], return [0,9].
38.1 Analysis
This problem is similar (almost the same) to Longest Substring Which Contains 2
Unique Characters.
Since each word in the dictionary has the same length, each of them can be treated
as a single character.
//frequency of words
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(String w: words){
if(map.containsKey(w)){
map.put(w, map.get(w)+1);
}else{
map.put(w, 1);
}
}
109 | 531
88 of
103 of246
288
38 Substring with Concatenation of All Words
count++;
while(currentMap.get(sub)>map.get(sub)){
String left = s.substring(start, start+len);
currentMap.put(left, currentMap.get(left)-1);
count--;
start = start + len;
}
if(count==words.length){
result.add(start); //add to result
return result;
}
89 of
104 of246
288
39 Minimum Window Substring
Given a string S and a string T, find the minimum window in S which will contain all
the characters in T in complexity O(n).
For example, S = "ADOBECODEBANC", T = "ABC", Minimum window is "BANC".
if(target.containsKey(c)){
if(map.containsKey(c)){
if(map.get(c)<target.get(c)){
count++;
}
map.put(c,map.get(c)+1);
}else{
map.put(c,1);
count++;
111 | 531
90 of
105 of246
288
39 Minimum Window Substring
}
}
if(count == t.length()){
char sc = s.charAt(left);
while (!map.containsKey(sc) || map.get(sc) > target.get(sc)) {
if (map.containsKey(sc) && map.get(sc) > target.get(sc))
map.put(sc, map.get(sc) - 1);
left++;
sc = s.charAt(left);
}
return result;
}
91 of
106 of246
288
40 Reverse Words in a String
This problem is pretty straightforward. We first split the string to words array, and
then iterate through the array and add each element to a new string. Note: String-
Builder should be used to avoid creating too many Strings. If the string is very long,
using String is not scalable since String is immutable and too many objects will be
created and garbage collected.
class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
113 | 531
92 of
107 of246
288
41 Find Minimum in Rotated Sorted
Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1
2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.You may assume no duplicate exists in the array.
41.1 Analysis
This problem is a binary search and the key is breaking the array to two parts, so that
we only need to work on half of the array each time.
If we pick the middle element, we can compare the middle element with the leftmost
(or rightmost) element. If the middle element is less than leftmost, the left half should
be selected; if the middle element is greater than the leftmost (or rightmost), the right
half should be selected. Using recursion or iteration, this problem can be solved in
time log(n).
In addition, in any rotated sorted array, the rightmost element should be less than
the left-most element, otherwise, the sorted array is not rotated and we can simply
pick the leftmost element as the minimum.
// not rotated
if (num[left] < num[right]) {
return num[left];
115 | 531
93 of
109 of246
288
41 Find Minimum in Rotated Sorted Array
// go right side
} else if (num[middle] > num[left]) {
return findMin(num, middle, right);
// go left side
} else {
return findMin(num, left, middle);
}
}
int left=0;
int right=nums.length-1;
//not rotated
if(nums[left]<nums[right])
return nums[left];
return nums[left];
}
94 of
110 of246
288
42 Find Minimum in Rotated Sorted
Array II
42.1 Problem
Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are al-
lowed?
Would this affect the run-time complexity? How and why?
This is a follow-up problem of finding minimum element in rotated sorted array with-
out duplicate elements. We only need to add one more condition, which checks if
the left-most element and the right-most element are equal. If they are we can simply
drop one of them. In my solution below, I drop the left element whenever the left-most
equals to the right-most.
public int findMin(int[] num) {
return findMin(num, 0, num.length-1);
}
117 | 531
95 of
111 of246
288
42 Find Minimum in Rotated Sorted Array II
}else{
return findMin(num, left, middle);
}
}
96 of
112 of246
288
43 Search in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1
2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, other-
wise return -1. You may assume no duplicate exists in the array.
public int binarySearch(int[] nums, int left, int right, int target){
if(left>right)
return -1;
if(target == nums[mid])
return mid;
119 | 531
97 of
113 of246
288
43 Search in Rotated Sorted Array
int left = 0;
int right= nums.length-1;
while(left<=right){
int mid = left + (right-left)/2;
if(target==nums[mid])
return mid;
if(nums[left]<=nums[mid]){
if(nums[left]<=target&& target<nums[mid]){
right=mid-1;
}else{
left=mid+1;
}
}else{
if(nums[mid]<target&& target<=nums[right]){
left=mid+1;
}else{
right=mid-1;
}
}
}
return -1;
}
98 of
114 of246
288
44 Search in Rotated Sorted Array II
Follow up for "Search in Rotated Sorted Array": what if duplicates are allowed? Write
a function to determine if a given target is in the array.
while(left<=right){
int mid = (left+right)/2;
if(nums[mid]==target)
return true;
if(nums[left]<nums[mid]){
if(nums[left]<=target&& target<nums[mid]){
right=mid-1;
}else{
left=mid+1;
}
}else if(nums[left]>nums[mid]){
if(nums[mid]<target&&target<=nums[right]){
left=mid+1;
}else{
right=mid-1;
}
}else{
left++;
}
}
return false;
}
121 | 531
99 of
115 of246
288
45 Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in
constant time.
push(x) – Push element x onto stack. pop() – Removes the element on top of the
stack. top() – Get the top element. getMin() – Retrieve the minimum element in the
stack.
45.1 Analysis
UPDATED ON 6/17/2015
To make constant time of getMin(), we need to keep track of the minimum element
for each element in the stack.
Define a node class that holds element value, min value, and pointer to elements below
it.
class Node {
int value;
int min;
Node next;
Node(int x) {
value = x;
next = null;
min = x;
}
}
class MinStack {
Node head;
123 | 531
117 of
100 of 246
288
45 Min Stack
head = temp;
}
}
return head.value;
}
return head.min;
}
}
118 of
101 of 246
288
46 Majority Element
Given an array of size n, find the majority element. The majority element is the element
that appears more than # n/2 $ times. (assume that the array is non-empty and the
majority element always exist in the array.)
We can sort the array first, which takes time of nlog(n). Then scan once to find the
longest consecutive substrings.
public class Solution {
public int majorityElement(int[] num) {
if(num.length==1){
return num[0];
}
Arrays.sort(num);
int prev=num[0];
int count=1;
for(int i=1; i<num.length; i++){
if(num[i] == prev){
count++;
if(count > num.length/2) return num[i];
}else{
count=1;
prev = num[i];
}
}
return 0;
}
}
Thanks to SK. His/her solution is much efficient and simpler. Since the majority al-
ways take more than a half space, the middle element is guaranteed to be the majority.
Sorting array takes nlog(n). So the time complexity of this solution is nlog(n). Cheers!
125 | 531
119 of
102 of 246
288
46 Majority Element
Arrays.sort(num);
return num[num.length / 2];
}
return result;
}
120 of
103 of 246
288
47 Majority Element II
Given an integer array of size n, find all elements that appear more than # n/3 $ times.
The algorithm should run in linear time and in O(1) space.
return result;
}
for(int i: nums){
127 | 531
121 of
104 of 246
288
47 Majority Element II
c1=c2=0;
for(int i: nums){
if(i==n1.intValue()){
c1++;
}else if(i==n2.intValue()){
c2++;
}
}
if(c1>nums.length/3)
result.add(n1);
if(c2>nums.length/3)
result.add(n2);
return result;
}
122 of
105 of 246
288
48 Remove Element
Given an array and a value, remove all instances of that value in place and return the
new length. (Note: The order of elements can be changed. It doesn’t matter what you
leave beyond the new length.)
j++;
}
return i;
}
129 | 531
123 of
106 of 246
288
49 Largest Rectangle in Histogram
Given n non-negative integers representing the histogram’s bar height where the width
of each bar is 1, find the area of largest rectangle in the histogram.
49.1 Analysis
The key to solve this problem is to maintain a stack to store bars’ indexes. The stack
only keeps the increasing bars.
131 | 531
125 of
107 of 246
288
49 Largest Rectangle in Histogram
int max = 0;
int i = 0;
while (!stack.isEmpty()) {
int p = stack.pop();
int h = height[p];
int w = stack.isEmpty() ? i : i - stack.peek() - 1;
max = Math.max(h * w, max);
}
return max;
}
126 of
108 of 246
288
50 Longest Common Prefix
50.1 Problem
Write a function to find the longest common prefix string amongst an array of strings.
50.2 Analysis
To solve this problem, we need to find the two loop conditions. One is the length of
the shortest string. The other is iteration over every element of the string array.
int minLen=Integer.MAX_VALUE;
for(String str: strs){
if(minLen > str.length())
minLen = str.length();
}
if(minLen == 0) return "";
if(strs[i].charAt(j) != prev){
return strs[i].substring(0, j);
}
}
}
return strs[0].substring(0,minLen);
}
133 | 531
127 of
109 of 246
288
51 Largest Number
Given a list of non negative integers, arrange them such that they form the largest
number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. (Note:
The result may be very large, so you need to return a string instead of an integer.)
51.1 Analysis
This problem can be solve by simply sorting strings, not sorting integer. Define a
comparator to compare strings by concat() right-to-left or left-to-right.
}
});
return sb.toString();
}
135 | 531
129 of
110 of 246
288
52 Simplify Path
//stack.push(path.substring(0,1));
int start = 0;
for(int i=1; i<path.length(); i++){
if(path.charAt(i) == ’/’){
stack.push(path.substring(start, i));
start = i;
}else if(i==path.length()-1){
stack.push(path.substring(start));
}
}
if(top.equals("/.") || top.equals("/")){
//nothing
}else if(top.equals("/..")){
back++;
}else{
if(back > 0){
137 | 531
131 of
111 of 246
288
52 Simplify Path
back--;
}else{
result.push(top);
}
}
}
return sb.toString();
}
132 of
112 of 246
288
53 Compare Version Numbers
53.1 Problem
Compare two version numbers version1 and version2. If version1 >version2 return 1,
if version1 <version2 return -1, otherwise return 0. You may assume that the version
strings are non-empty and contain only digits and the . character. The . character does
not represent a decimal point and is used to separate number sequences. Here is an
example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37
The tricky part of the problem is to handle cases like 1.0 and 1. They should be equal.
public int compareVersion(String version1, String version2) {
String[] arr1 = version1.split("\\.");
String[] arr2 = version2.split("\\.");
int i=0;
while(i<arr1.length || i<arr2.length){
if(i<arr1.length && i<arr2.length){
if(Integer.parseInt(arr1[i]) < Integer.parseInt(arr2[i])){
return -1;
}else if(Integer.parseInt(arr1[i]) > Integer.parseInt(arr2[i])){
return 1;
}
} else if(i<arr1.length){
if(Integer.parseInt(arr1[i]) != 0){
return 1;
}
} else if(i<arr2.length){
if(Integer.parseInt(arr2[i]) != 0){
return -1;
}
}
i++;
}
return 0;
139 | 531
133 of
113 of 246
288
53 Compare Version Numbers
134 of
114 of 246
288
54 Gas Station
There are N gas stations along a circular route, where the amount of gas at station i is
gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from
station i to its next station (i+1). You begin the journey with an empty tank at one of
the gas stations.
Return the starting gas station’s index if you can travel around the circuit once,
otherwise return -1.
54.1 Analysis
To solve this problem, we need to understand and use the following 2 facts: 1) if the
sum of gas >= the sum of cost, then the circle can be completed. 2) if A can not reach
C in a the sequence of A–>B–>C, then B can not make it either.
Proof of fact 2:
If gas[A] < cost[A], then A can not even reach B.
So to reach C from A, gas[A] must >= cost[A].
Given that A can not reach C, we have gas[A] + gas[B] < cost[A] + cost[B],
and gas[A] >= cost[A],
Therefore, gas[B] < cost[B], i.e., B can not reach C.
141 | 531
135 of
115 of 246
288
54 Gas Station
136 of
116 of 246
288
55 Pascal’s Triangle
Given numRows, generate the first numRows of Pascal’s triangle. For example, given
numRows = 5, the result should be:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
cur.add(1); //first
for (int j = 0; j < pre.size() - 1; j++) {
cur.add(pre.get(j) + pre.get(j + 1)); //middle
}
cur.add(1);//last
result.add(cur);
pre = cur;
}
return result;
}
143 | 531
137 of
117 of 246
288
56 Pascal’s Triangle II
Given an index k, return the kth row of the Pascal’s triangle. For example, when k =
3, the row is [1,3,3,1].
56.1 Analysis
This problem is related to Pascal’s Triangle which gets all rows of Pascal’s triangle. In
this problem, only one row is required to return.
if (rowIndex < 0)
return result;
result.add(1);
for (int i = 1; i <= rowIndex; i++) {
for (int j = result.size() - 2; j >= 0; j--) {
result.set(j + 1, result.get(j) + result.get(j + 1));
}
result.add(1);
}
return result;
}
145 | 531
139 of
118 of 246
288
57 Container With Most Water
57.1 Problem
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordi-
nate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai)
and (i, 0). Find two lines, which together with x-axis forms a container, such that the
container contains the most water.
57.2 Analysis
Initially we can assume the result is 0. Then we scan from both sides. If leftHeight
<rightHeight, move right and find a value that is greater than leftHeight. Similarily,
if leftHeight >rightHeight, move left and find a value that is greater than rightHeight.
Additionally, keep tracking the max value.
int max = 0;
int left = 0;
int right = height.length - 1;
147 | 531
141 of
119 of 246
288
57 Container With Most Water
return max;
}
142 of
120 of 246
288
58 Candy
There are N children standing in a line. Each child is assigned a rating value. You are
giving candies to these children subjected to the following requirements:
1. Each child must have at least one candy. 2. Children with a higher rating get
more candies than their neighbors.
What is the minimum candies you must give?
58.1 Analysis
149 | 531
143 of
121 of 246
288
58 Candy
return result;
}
144 of
122 of 246
288
59 Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each
bar is 1, compute how much water it is able to trap after raining.
For example, given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
59.1 Analysis
This problem is similar to Candy. It can be solve by scanning from both sides and
then get the total.
if(height==null || height.length<=2)
return result;
151 | 531
145 of
123 of 246
288
59 Trapping Rain Water
right[i]=height[i];
max = height[i];
}
}
//calculate totoal
for(int i=0; i<height.length; i++){
result+= Math.min(left[i],right[i])-height[i];
}
return result;
}
146 of
124 of 246
288
60 Count and Say
60.1 Problem
The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21,
1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
The problem can be solved by using a simple iteration. See Java solution below:
public String countAndSay(int n) {
if (n <= 0)
return null;
while (i < n) {
StringBuilder sb = new StringBuilder();
int count = 1;
for (int j = 1; j < result.length(); j++) {
if (result.charAt(j) == result.charAt(j - 1)) {
count++;
} else {
sb.append(count);
sb.append(result.charAt(j - 1));
count = 1;
}
}
sb.append(count);
sb.append(result.charAt(result.length() - 1));
result = sb.toString();
i++;
}
153 | 531
147 of
125 of 246
288
60 Count and Say
return result;
}
148 of
126 of 246
288
61 Search for a Range
Given a sorted array of integers, find the starting and ending position of a given target
value. Your algorithm’s runtime complexity must be in the order of O(log n). If the
target is not found in the array, return [-1, -1]. For example, given [5, 7, 7, 8, 8, 10] and
target value 8, return [3, 4].
61.1 Analysis
Based on the requirement of O(log n), this is a binary search problem apparently.
return arr;
}
public void binarySearch(int[] nums, int left, int right, int target, int[]
arr){
if(right<left)
return;
155 | 531
149 of
127 of 246
288
61 Search for a Range
if(nums[mid]<target){
binarySearch(nums, mid+1, right, target, arr);
}else if(nums[mid]>target){
binarySearch(nums, left, mid-1, target, arr);
}else{
arr[0]=mid;
arr[1]=mid;
150 of
128 of 246
288
62 Basic Calculator
62.1 Analysis
This problem can be solved by using a stack. We keep pushing element to the stack,
when ’)" is met, calculate the expression up to the first "(".
if (i == arr.length - 1) {
stack.push(sb.toString());
}
} else {
if (sb.length() > 0) {
stack.push(sb.toString());
sb = new StringBuilder();
}
if (arr[i] != ’)’) {
stack.push(new String(new char[] { arr[i] }));
157 | 531
151 of
129 of 246
288
62 Basic Calculator
} else {
// when meet ’)’, pop and calculate
ArrayList<String> t = new ArrayList<String>();
while (!stack.isEmpty()) {
String top = stack.pop();
if (top.equals("(")) {
break;
} else {
t.add(0, top);
}
}
int temp = 0;
if (t.size() == 1) {
temp = Integer.valueOf(t.get(0));
} else {
for (int j = t.size() - 1; j > 0; j = j - 2) {
if (t.get(j - 1).equals("-")) {
temp += 0 - Integer.valueOf(t.get(j));
} else {
temp += Integer.valueOf(t.get(j));
}
}
temp += Integer.valueOf(t.get(0));
}
stack.push(String.valueOf(temp));
}
}
}
int temp = 0;
for (int i = t.size() - 1; i > 0; i = i - 2) {
if (t.get(i - 1).equals("-")) {
temp += 0 - Integer.valueOf(t.get(i));
} else {
temp += Integer.valueOf(t.get(i));
}
}
temp += Integer.valueOf(t.get(0));
return temp;
}
152 of
130 of 246
288
63 Group Anagrams
Given an array of strings, return all groups of strings that are anagrams.
63.1 Analysis
An anagram is a type of word play, the result of rearranging the letters of a word or
phrase to produce a new word or phrase, using all the original letters exactly once; for
example Torchwood can be rearranged into Doctor Who.
If two strings are anagram to each other, their sorted sequence is the same.
Updated on 5/1/2016.
if(map.containsKey(ns)){
map.get(ns).add(str);
}else{
ArrayList<String> al = new ArrayList<String>();
al.add(str);
map.put(ns, al);
}
}
result.addAll(map.values());
return result;
}
159 | 531
153 of
131 of 246
288
63 Group Anagrams
If average length of verbs is m and words array length is n, then the time is O(n*m*log(m)).
154 of
132 of 246
288
64 Shortest Palindrome
64.1 Analysis
We can solve this problem by using one of the methods which is used to solve the
longest palindrome substring problem.
Specifically, we can start from the center and scan two sides. If read the left bound-
ary, then the shortest palindrome is identified.
return result;
}
161 | 531
155 of
133 of 246
288
64 Shortest Palindrome
return sb.append(s).toString();
}
156 of
134 of 246
288
65 Rectangle Area
Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle
is defined by its bottom left corner and top right corner coordinates.
65.1 Analysis
This problem can be converted as a overlap internal problem. On the x-axis, there are
(A,C) and (E,G); on the y-axis, there are (F,H) and (B,D). If they do not have overlap,
the total area is the sum of 2 rectangle areas. If they have overlap, the total area should
minus the overlap area.
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int
H) {
if(C<E||G<A )
return (G-E)*(H-F) + (C-A)*(D-B);
if(D<F || H<B)
return (G-E)*(H-F) + (C-A)*(D-B);
163 | 531
157 of
135 of 246
288
66 Summary Ranges
Given a sorted integer array without duplicates, return the summary of its ranges for
consecutive numbers.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
66.1 Analysis
if(nums.length==1){
result.add(nums[0]+"");
}
if(i==nums.length-1){
result.add(nums[i]+"");
}
first = nums[i];
}
165 | 531
159 of
136 of 246
288
66 Summary Ranges
pre = nums[i];
}
return result;
}
160 of
137 of 246
288
67 Increasing Triplet Subsequence
67.1 Analysis
This problem can be converted to be finding if there is a sequence such that the_smallest_so_far
<the_second_smallest_so_far <current. We use x, y and z to denote the 3 number re-
spectively.
if (x >= z) {
x = z;// update x to be a smaller value
} else if (y >= z) {
y = z; // update y to be a smaller value
} else {
return true;
}
}
return false;
}
167 | 531
161 of
138 of 246
288
68 Get Target Number Using Number List
and Arithmetic Operations
Given a list of numbers and a target number, write a program to determine whether
the target number can be calculated by applying "+-*/" operations to the number list?
You can assume () is automatically added when necessary.
For example, given 1,2,3,4 and 21, return true. Because (1+2)*(3+4)=21
68.1 Analysis
This is a partition problem which can be solved by using depth first search.
int i = 0;
int j = list.size() - 1;
return false;
}
169 | 531
163 of
139 of 246
288
68 Get Target Number Using Number List and Arithmetic Operations
return result;
}
return result;
}
164 of
140 of 246
288
69 Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.
this is a simple problem which can be solved by using two pointers scanning from
beginning and end of the array.
public String reverseVowels(String s) {
ArrayList<Character> vowList = new ArrayList<Character>();
vowList.add(’a’);
vowList.add(’e’);
vowList.add(’i’);
vowList.add(’o’);
vowList.add(’u’);
vowList.add(’A’);
vowList.add(’E’);
vowList.add(’I’);
vowList.add(’O’);
vowList.add(’U’);
int i=0;
int j=s.length()-1;
while(i<j){
if(!vowList.contains(arr[i])){
i++;
continue;
}
if(!vowList.contains(arr[j])){
j--;
continue;
}
char t = arr[i];
arr[i]=arr[j];
arr[j]=t;
i++;
j--;
171 | 531
165 of
141 of 246
288
69 Reverse Vowels of a String
166 of
142 of 246
288
70 Flip Game
You are playing the following Flip Game with your friend: Given a string that con-
tains only these two characters: + and -, you and your friend take turns to flip two
consecutive "++" into "–". The game ends when a person can no longer make a move
and therefore the other person will be the winner.
Write a function to compute all possible states of the string after one valid move.
if(s==null)
return result;
return result;
}
173 | 531
167 of
143 of 246
288
71 Flip Game II
You are playing the following Flip Game with your friend: Given a string that con-
tains only these two characters: + and -, you and your friend take turns to flip two
consecutive "++" into "–". The game ends when a person can no longer make a move
and therefore the other person will be the winner.
Write a function to determine if the starting player can guarantee a win.
For example, given s = "++++", return true. The starting player can guarantee a win
by flipping the middle "++" to become "+–+".
return canWinHelper(s.toCharArray());
}
arr[i]=’+’;
arr[i+1]=’+’;
//if there is a flip which makes the other player lose, the first
play wins
if(!win){
return true;
}
}
}
return false;
}
175 | 531
169 of
144 of 246
288
71 Flip Game II
Roughly, the time is n*n*...n, which is O(nn̂). The reason is each recursion takes O(n)
and there are totally n recursions.
170 of
145 of 246
288
72 Move Zeroes
Given an array nums, write a function to move all 0’s to the end of it while maintaining
the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should
be [1, 3, 12, 0, 0].
177 | 531
171 of
146 of 246
288
73 Valid Anagram
return true;
}
If the inputs contain unicode characters, an array with length of 26 is not enough.
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length())
179 | 531
173 of
147 of 246
288
73 Valid Anagram
return false;
if(map.size()>0)
return false;
return true;
}
174 of
148 of 246
288
74 Group Shifted Strings
Given a string, we can "shift" each of its letter to its successive letter, for example: "abc"
->"bcd". We can keep "shifting" which forms the sequence: "abc" ->"bcd" ->... ->"xyz".
Given a list of strings which contains only lowercase alphabets, group all strings
that belong to the same shifting sequence, return:
[
["abc","bcd","xyz"],
["az","ba"],
["acef"],
["a","z"]
]
for(String s: strings){
char[] arr = s.toCharArray();
if(arr.length>0){
int diff = arr[0]-’a’;
for(int i=0; i<arr.length; i++){
if(arr[i]-diff<’a’){
arr[i] = (char) (arr[i]-diff+26);
}else{
arr[i] = (char) (arr[i]-diff);
}
}
}
181 | 531
175 of
149 of 246
288
74 Group Shifted Strings
}
}
result.addAll(map.values());
return result;
}
176 of
150 of 246
288
75 Top K Frequent Elements
We can solve this problem by using a counter, and then sort the counter by value.
public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> result = new ArrayList<Integer>();
for(int i: nums){
if(counter.containsKey(i)){
counter.put(i, counter.get(i)+1);
}else{
counter.put(i, 1);
}
}
int i=0;
for(Map.Entry<Integer, Integer> entry: sortedMap.entrySet()){
result.add(entry.getKey());
i++;
if(i==k)
break;
}
return result;
}
}
183 | 531
177 of
151 of 246
288
75 Top K Frequent Elements
if(diff==0){
return 1;
}else{
return diff;
}
}
}
178 of
152 of 246
288
76 Find Peak Element
A peak element is an element that is greater than its neighbors. 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 case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞. For example, in array [1, 2, 3, 1], 3 is
a peak element and your function should return the index number 2.
76.1 Thoughts
This is a very simple problem. We can scan the array and find any element that is
greater can its previous and next. The first and last element are handled separately.
if(curr > prev && curr > next && curr > max){
index = i;
max = curr;
}
}
return index;
}
}
185 | 531
179 of
153 of 246
288
77 Word Pattern
Given a pattern and a string str, find if str follows the same pattern. Here follow means
a full match, such that there is a bijection between a letter in pattern and a non-empty
word in str.
if(pattern.length()!=arr.length)
return false;
if(map.containsKey(c)){
if(!map.get(c).equals(s))
return false;
}else{
if(map.containsValue(s))
return false;
map.put(c, s);
}
}
return true;
}
187 | 531
181 of
154 of 246
288
78 Set Matrix Zeroes
78.1 Analysis
This problem should be solved in place, i.e., no other array should be used. We can
use the first column and the first row to track if a row/column should be set to 0.
Since we used the first row and first column to mark the zero row/column, the
original values are changed.
Step 1: First row contains zero = true; First column contains zero = false;
189 | 531
183 of
155 of 246
288
78 Set Matrix Zeroes
184 of
156 of 246
288
78 Set Matrix Zeroes
if(firstRowZero){
for(int i=0; i<matrix[0].length; i++)
matrix[0][i] = 0;
}
}
}
185 of
157 of 246
288
79 Spiral Matrix
If more than one row and column left, it can form a circle and we process the circle.
Otherwise, if only one row or column left, we process that column or row ONLY.
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> result = new ArrayList<Integer>();
int m = matrix.length;
int n = matrix[0].length;
int x=0;
int y=0;
193 | 531
187 of
158 of 246
288
79 Spiral Matrix
break;
}
//left - move up
for(int i=0;i<m-1;i++){
result.add(matrix[x--][y]);
}
x++;
y++;
m=m-2;
n=n-2;
}
return result;
}
}
We can also recursively solve this problem. The solution’s performance is not better
than Solution or as clear as Solution 1. Therefore, Solution 1 should be preferred.
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
if(matrix==null || matrix.length==0)
return new ArrayList<Integer>();
return spiralOrder(matrix,0,0,matrix.length,matrix[0].length);
}
188 of
159 of 246
288
79 Spiral Matrix
if(m<=0||n<=0)
return result;
//left - move up
if(n>1){
for(int i=0;i<m-1;i++){
result.add(matrix[x--][y]);
}
}
if(m==1||n==1)
result.addAll(spiralOrder(matrix, x, y, 1, 1));
else
result.addAll(spiralOrder(matrix, x+1, y+1, m-2, n-2));
return result;
}
}
189 of
160 of 246
288
80 Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral
order. For example, given n = 4,
[
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7]
]
int x=0;
int y=0;
int step = 0;
for(int i=0;i<total;){
while(y+step<n){
i++;
result[x][y]=i;
y++;
}
y--;
x++;
while(x+step<n){
i++;
result[x][y]=i;
x++;
}
x--;
y--;
while(y>=0+step){
i++;
197 | 531
191 of
161 of 246
288
80 Spiral Matrix II
result[x][y]=i;
y--;
}
y++;
x--;
step++;
while(x>=0+step){
i++;
result[x][y]=i;
x--;
}
x++;
y++;
}
return result;
}
192 of
162 of 246
288
81 Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix
has properties:
1) Integers in each row are sorted from left to right. 2) The first integer of each row
is greater than the last integer of the previous row.
For example, consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
int m = matrix.length;
int n = matrix[0].length;
int start = 0;
int end = m*n-1;
while(start<=end){
int mid=(start+end)/2;
int midX=mid/n;
int midY=mid%n;
if(matrix[midX][midY]==target)
return true;
199 | 531
193 of
163 of 246
288
81 Search a 2D Matrix
if(matrix[midX][midY]<target){
start=mid+1;
}else{
end=mid-1;
}
}
return false;
}
}
194 of
164 of 246
288
82 Search a 2D Matrix II
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix
has the following properties:
Integers in each row are sorted in ascending from left to right. Integers in each
column are sorted in ascending from top to bottom.
For example, consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
In a naive approach, we can use the matrix boundary to reduce the search space. Here
is a simple recursive implementation.
public boolean searchMatrix(int[][] matrix, int target) {
int i1=0;
int i2=matrix.length-1;
int j1=0;
int j2=matrix[0].length-1;
public boolean helper(int[][] matrix, int i1, int i2, int j1, int j2, int
target){
if(i1>i2||j1>j2)
return false;
for(int j=j1;j<=j2;j++){
if(target < matrix[i1][j]){
return helper(matrix, i1, i2, j1, j-1, target);
}else if(target == matrix[i1][j]){
return true;
201 | 531
195 of
165 of 246
288
82 Search a 2D Matrix II
}
}
for(int i=i1;i<=i2;i++){
if(target < matrix[i][j1]){
return helper(matrix, i1, i-1, j1, j2, target);
}else if(target == matrix[i][j1]){
return true;
}
}
for(int j=j1;j<=j2;j++){
if(target > matrix[i2][j]){
return helper(matrix, i1, i2, j+1, j2, target);
}else if(target == matrix[i2][j]){
return true;
}
}
for(int i=i1;i<=i2;i++){
if(target > matrix[i][j2]){
return helper(matrix, i1, i+1, j1, j2, target);
}else if(target == matrix[i][j2]){
return true;
}
}
return false;
}
int i=m;
int j=0;
196 of
166 of 246
288
82 Search a 2D Matrix II
}
}
return false;
}
197 of
167 of 246
288
83 Rotate Image
In the following solution, a new 2-dimension array is created to store the rotated
matrix, and the result is assigned to the matrix at the end. This is WRONG! Why?
public class Solution {
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length==0)
return ;
int m = matrix.length;
matrix = result;
}
}
The problem is that Java is pass by value not by refrence! "matrix" is just a reference
to a 2-dimension array. If "matrix" is assigned to a new 2-dimension array in the
method, the original array does not change. Therefore, there should be another loop
to assign each element to the array referenced by "matrix". Check out "Java pass by
value."
public class Solution {
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length==0)
return ;
int m = matrix.length;
205 | 531
199 of
168 of 246
288
83 Rotate Image
By using the relation "matrix[i][j] = matrix[n-1-j][i]", we can loop through the matrix.
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < Math.ceil(((double) n) / 2.); j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n-1-j][i];
matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
matrix[j][n-1-i] = temp;
}
}
}
200 of
169 of 246
288
84 Valid Sudoku
Determine if a Sudoku is valid. The Sudoku board could be partially filled, where
empty cells are filled with the character ’.’.
207 | 531
201 of
170 of 246
288
84 Valid Sudoku
if (board[i][j] != ’.’) {
if (m[(int) (board[i][j] - ’1’)]) {
return false;
}
m[(int) (board[i][j] - ’1’)] = true;
}
}
}
return true;
}
202 of
171 of 246
288
85 Minimum Path Sum
Given a m x n grid filled with non-negative numbers, find a path from top left to
bottom right which minimizes the sum of all numbers along its path.
A native solution would be depth-first search. It’s time is too expensive and fails the
online judgement.
public int minPathSum(int[][] grid) {
return dfs(0,0,grid);
}
if(i<grid.length-1){
return grid[i][j] + dfs(i+1, j, grid);
}
if(j<grid[0].length-1){
return grid[i][j] + dfs(i, j+1, grid);
}
return 0;
}
209 | 531
203 of
172 of 246
288
85 Minimum Path Sum
int m = grid.length;
int n = grid[0].length;
return dp[m-1][n-1];
}
204 of
173 of 246
288
86 Unique Paths
A robot is located at the top-left corner of a m x n grid. It can only move either down
or right at any point in time. The robot is trying to reach the bottom-right corner of
the grid.
How many possible unique paths are there?
if(i<m-1){
return dfs(i+1,j,m,n);
}
if(j<n-1){
return dfs(i,j+1,m,n);
}
return 0;
}
211 | 531
205 of
174 of 246
288
86 Unique Paths
//left column
for(int i=0; i<m; i++){
dp[i][0] = 1;
}
//top row
for(int j=0; j<n; j++){
dp[0][j] = 1;
}
return dp[m-1][n-1];
}
206 of
175 of 246
288
87 Unique Paths II
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
if(obstacleGrid[0][0]==1||obstacleGrid[m-1][n-1]==1)
return 0;
//left column
for(int i=1; i<m; i++){
if(obstacleGrid[i][0]==1){
dp[i][0] = 0;
}else{
dp[i][0] = dp[i-1][0];
}
}
//top row
213 | 531
207 of
176 of 246
288
87 Unique Paths II
}
}
return dp[m-1][n-1];
}
208 of
177 of 246
288
88 Number of Islands
Given a 2-d grid map of ’1’s (land) and ’0’s (water), count the number of islands. An
island is surrounded by water and is formed by connecting adjacent lands horizontally
or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
The basic idea of the following solution is merging adjacent lands, and the merging
should be done recursively.
public int numIslands(char[][] grid) {
if(grid==null||grid.length==0||grid[0].length==0)
return 0;
int m=grid.length;
int n=grid[0].length;
int count=0;
for(int i=0;i<m; i++){
for(int j=0;j<n; j++){
if(grid[i][j]==’1’){
count++;
merge(grid, i, j);
}
}
}
215 | 531
209 of
178 of 246
288
88 Number of Islands
return count;
}
if(grid[i][j]==’1’){
grid[i][j]=’0’;
merge(grid, i-1,j);
merge(grid, i+1,j);
merge(grid, i,j-1);
merge(grid, i,j+1);
}
}
210 of
179 of 246
288
89 Number of Islands II
A 2d grid map of m rows and n columns is initially filled with water. We may perform
an addLand operation which turns the water at position (row, col) into a land. Given a
list of positions to operate, count the number of islands after each addLand operation.
An island is surrounded by water and is formed by connecting adjacent lands hori-
zontally or vertically. You may assume all four edges of the grid are all surrounded by
water.
int[] p = positions[k];
int index = p[0]*n+p[1];
rootArray[index]=index;//set root to be itself for each node
for(int r=0;r<4;r++){
int i=p[0]+directions[r][0];
int j=p[1]+directions[r][1];
if(i>=0&&j>=0&&i<m&&j<n&&rootArray[i*n+j]!=-1){
//get neighbor’s root
int thisRoot = getRoot(rootArray, i*n+j);
if(thisRoot!=index){
rootArray[thisRoot]=index;//set previous root’s root
count--;
}
}
}
217 | 531
211 of
180 of 246
288
89 Number of Islands II
result.add(count);
}
return result;
}
212 of
181 of 246
288
90 Surrounded Regions
Given a 2D board containing ’X’ and ’O’, capture all regions surrounded by ’X’. A
region is captured by flipping all ’O’s into ’X’s in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
90.1 Analysis
This problem is similar to Number of Islands. In this problem, only the cells on the
boarders can not be surrounded. So we can first merge those O’s on the boarders like
in Number of Islands and replace O’s with ’#’, and then scan the board and replace all
O’s left (if any).
int m = board.length;
int n = board[0].length;
if(board[i][n-1] == ’O’){
219 | 531
213 of
182 of 246
288
90 Surrounded Regions
merge(board, i,n-1);
}
}
if(board[m-1][j] == ’O’){
merge(board, m-1,j);
}
}
if(board[i][j] != ’O’)
return;
board[i][j] = ’#’;
214 of
183 of 246
288
90 Surrounded Regions
int m = board.length;
int n = board[0].length;
if (board[i][n - 1] == ’O’) {
bfs(board, i, n - 1);
}
}
215 of
184 of 246
288
90 Surrounded Regions
while (!queue.isEmpty()) {
int cur = queue.poll();
int x = cur / n;
int y = cur % n;
fillCell(board, x - 1, y);
fillCell(board, x + 1, y);
fillCell(board, x, y - 1);
fillCell(board, x, y + 1);
}
}
// add current cell is queue & then process its neighbors in bfs
queue.offer(i * n + j);
board[i][j] = ’#’;
}
}
216 of
185 of 246
288
91 Maximal Rectangle
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing
all ones and return its area.
91.1 Analysis
int maxArea = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == ’0’) {
height[i][j] = 0;
} else {
height[i][j] = i == 0 ? 1 : height[i - 1][j] + 1;
}
}
}
return maxArea;
}
int i = 0;
int max = 0;
223 | 531
217 of
186 of 246
288
91 Maximal Rectangle
return max;
}
218 of
187 of 246
288
92 Maximal Square
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing all
1’s and return its area.
For example, given the following matrix:
1101
1101
1111
Return 4.
92.1 Analysis
This problem can be solved by dynamic programming. The changing condition is:
t[i][j] = min(t[i][j-1], t[i-1][j], t[i-1][j-1]) + 1. It means the square formed before this
point.
int m = matrix.length;
int n = matrix[0].length;
//top row
for (int i = 0; i < m; i++) {
t[i][0] = Character.getNumericValue(matrix[i][0]);
}
//left column
for (int j = 0; j < n; j++) {
t[0][j] = Character.getNumericValue(matrix[0][j]);
}
//cells inside
for (int i = 1; i < m; i++) {
225 | 531
219 of
188 of 246
288
92 Maximal Square
int max = 0;
//get maximal length
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (t[i][j] > max) {
max = t[i][j];
}
}
}
220 of
189 of 246
288
93 Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "ad-
jacent" cells are those horizontally or vertically neighboring. The same letter cell may
not be used more than once.
For example, given board =
[
["ABCE"],
["SFCS"],
["ADEE"]
]
word = "ABCCED", ->returns true, word = "SEE", ->returns true, word = "ABCB",
->returns false.
93.1 Analysis
return result;
}
public boolean dfs(char[][] board, String word, int i, int j, int k){
int m = board.length;
227 | 531
221 of
190 of 246
288
93 Word Search
int n = board[0].length;
if(board[i][j] == word.charAt(k)){
char temp = board[i][j];
board[i][j]=’#’;
if(k==word.length()-1){
return true;
}else if(dfs(board, word, i-1, j, k+1)
||dfs(board, word, i+1, j, k+1)
||dfs(board, word, i, j-1, k+1)
||dfs(board, word, i, j+1, k+1)){
return true;
}
board[i][j]=temp;
}
return false;
}
222 of
191 of 246
288
94 Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where
"adjacent" cells are those horizontally or vertically neighboring. The same letter cell
may not be used more than once in a word.
For example, given words = ["oath","pea","eat","rain"] and board =
[
[’o’,’a’,’a’,’n’],
[’e’,’t’,’a’,’e’],
[’i’,’h’,’k’,’r’],
[’i’,’f’,’l’,’v’]
]
Return ["eat","oath"].
Similar to Word Search, this problem can be solved by DFS. However, this solution
exceeds time limit.
public List<String> findWords(char[][] board, String[] words) {
ArrayList<String> result = new ArrayList<String>();
int m = board.length;
int n = board[0].length;
229 | 531
223 of
192 of 246
288
94 Word Search II
result.add(word);
}
}
return result;
}
if (board[i][j] == word.charAt(k)) {
char temp = board[i][j];
board[i][j] = ’#’;
if (k == word.length() - 1) {
return true;
} else if (dfs(board, word, i - 1, j, k + 1)
|| dfs(board, word, i + 1, j, k + 1)
|| dfs(board, word, i, j - 1, k + 1)
|| dfs(board, word, i, j + 1, k + 1)) {
board[i][j] = temp;
return true;
}
} else {
return false;
}
return false;
}
If the current candidate does not exist in all words’ prefix, we can stop backtracking
immediately. This can be done by using a trie structure.
public class Solution {
Set<String> result = new HashSet<String>();
224 of
193 of 246
288
94 Word Search II
int m=board.length;
int n=board[0].length;
if(i<0 || j<0||i>=m||j>=n){
return;
}
if(visited[i][j])
return;
if(!trie.startsWith(str))
return;
if(trie.search(str)){
result.add(str);
}
visited[i][j]=true;
dfs(board, visited, str, i-1, j, trie);
dfs(board, visited, str, i+1, j, trie);
dfs(board, visited, str, i, j-1, trie);
dfs(board, visited, str, i, j+1, trie);
visited[i][j]=false;
}
}
//Trie Node
225 of
194 of 246
288
94 Word Search II
class TrieNode{
public TrieNode[] children = new TrieNode[26];
public String item = "";
}
//Trie
class Trie{
public TrieNode root = new TrieNode();
226 of
195 of 246
288
95 Integer Break
Given a positive integer n, break it into the sum of at least two positive integers and
maximize the product of those integers. Return the maximum product you can get.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 +
4).
Let dp[i] to be the max production value for breaking the number i. Since dp[i+j] can
be i*j, dp[i+j] = max(max(dp[i], i) * max(dp[j], j)), dp[i+j]).
public int integerBreak(int n) {
int[] dp = new int[n+1];
return dp[n];
}
If we see the breaking result for some numbers, we can see repeated pattern like the
following:
2 -> 1*1
3 -> 1*2
4 -> 2*2
5 -> 3*2
6 -> 3*3
7 -> 3*4
8 -> 3*3*2
9 -> 3*3*3
10 -> 3*3*4
11 -> 3*3*3*2
233 | 531
227 of
196 of 246
288
95 Integer Break
We only need to find how many 3’s we can get when n>4. If n
public int integerBreak(int n) {
if(n==2) return 1;
if(n==3) return 2;
if(n==4) return 4;
int result=1;
if(n%3==0){
int m = n/3;
result = (int) Math.pow(3, m);
}else if(n%3==2){
int m=n/3;
result = (int) Math.pow(3, m) * 2;
}else if(n%3==1){
int m=(n-4)/3;
result = (int) Math.pow(3, m) *4;
}
return result;
}
228 of
197 of 246
288
96 Range Sum Query 2D Immutable
Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined
by its upper left corner (row1, col1) and lower right corner (row2, col2).
96.1 Analysis
Since the assumption is that there are many calls to sumRegion method, we should
use some extra space to store the intermediate results. Here we define an array sum[][]
which stores the sum value from (0,0) to the current cell.
int m = matrix.length;
int n = matrix[0].length;
sum = new int[m][n];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
if(this.sum==null)
235 | 531
229 of
198 of 246
288
96 Range Sum Query 2D Immutable
return 0;
int bottomLeftX=row2;
int bottomLeftY= col1;
int result=0;
}else if(col1==0){
result = sum[row2][col2]
-sum[topRightX-1][topRightY];
}else{
result = sum[row2][col2]
-sum[topRightX-1][topRightY]
-sum[bottomLeftX][bottomLeftY-1]
+sum[row1-1][col1-1];
}
return result;
}
}
230 of
199 of 246
288
97 Longest Increasing Path in a Matrix
Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You
may NOT move diagonally or move outside of the boundary
return longest;
}
237 | 531
231 of
200 of 246
288
97 Longest Increasing Path in a Matrix
}
}
return longest;
}
if(x>=0&&y>=0&&x<matrix.length&&y<matrix[0].length&&matrix[x][y]>matrix[i][j]){
mem[i][j]=Math.max(mem[i][j], dfs(matrix, x, y, mem));
}
}
return ++mem[i][j];
}
}
232 of
201 of 246
288
98 Implement a Stack Using an Array in
Java
@SuppressWarnings("unchecked")
public Stack(int cap) {
this.CAP = cap;
this.arr = (E[]) new Object[cap];
}
public E pop() {
if(this.size == 0){
return null;
}
this.size--;
E result = this.arr[top];
this.arr[top] = null;//prevent memory leaking
this.top--;
return result;
}
239 | 531
233 of
202 of 246
288
98 Implement a Stack Using an Array in Java
this.size++;
this.arr[++top] = e;
return false;
}
sb.setLength(sb.length()-2);
return sb.toString();
}
System.out.println(stack);
stack.pop();
System.out.println(stack);
stack.pop();
System.out.println(stack);
}
}
Output:
hello, world
hello
null
234 of
203 of 246
288
98 Implement a Stack Using an Array in Java
It turns out I don’t need to improve anything. There are some naming differences but
overall my method is ok.
This example occurs twice in "Effective Java". In the first place, the stack example is
used to illustrate memory leak. In the second place, the example is used to illustrate
when we can suppress unchecked warnings.
Do you wonder how to implement a queue by using an array?
235 of
204 of 246
288
99 Add Two Numbers
You are given two linked lists representing two non-negative numbers. The digits are
stored in reverse order and each of their nodes contain a single digit. Add the two
numbers and return it as a linked list.
Input: (2 ->4 ->3) + (5 ->6 ->4) Output: 7 ->0 ->8
if(p2 != null){
carry += p2.val;
p2 = p2.next;
}
if(carry==1)
p3.next=new ListNode(1);
return newHead.next;
}
}
What if the digits are stored in regular order instead of reversed order?
Answer: We can simple reverse the list, calculate the result, and reverse the result.
243 | 531
237 of
205 of 246
288
100 Reorder List
Given a singly linked list L: L0→L1→ ... →Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-
1→L2→Ln-2→...
For example, given 1,2,3,4, reorder it to 1,4,2,3. You must do this in-place without
altering the nodes’ values.
100.1 Analysis
• Break list in the middle to two lists (use fast & slow pointers)
• Reverse the order of the second list
• Merge two list back together
ListNode(int x) {
val = x;
next = null;
}
}
245 | 531
239 of
206 of 246
288
100 Reorder List
n3.next = n4;
printList(n1);
reorderList(n1);
printList(n1);
}
//use a fast and slow pointer to break the link to two parts.
while (fast != null && fast.next != null && fast.next.next!= null) {
//why need third/second condition?
System.out.println("pre "+slow.val + " " + fast.val);
slow = slow.next;
fast = fast.next.next;
System.out.println("after " + slow.val + " " + fast.val);
}
ListNode p1 = head;
ListNode p2 = second;
p1.next = p2;
p2.next = temp1;
p1 = temp1;
p2 = temp2;
}
}
}
240 of
207 of 246
288
100 Reorder List
return pre;
}
The three steps can be used to solve other problems of linked list. A little diagram
may help better understand them.
Reverse List:
241 of
208 of 246
288
100 Reorder List
Merge List:
242 of
209 of 246
288
100 Reorder List
243 of
210 of 246
288
101 Linked List Cycle
101.1 Analysis
If we have 2 pointers - fast and slow. It is guaranteed that the fast one will meet the
slow one if there exists a circle.
if(slow == fast)
return true;
}
return false;
}
}
251 | 531
245 of
211 of 246
288
102 Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which
could point to any node in the list or null.
Return a deep copy of the list.
• copy every node, i.e., duplicate every node, and insert it to the list
• copy random pointers for all newly created nodes
• break the list to two
if (head == null)
return null;
RandomListNode p = head;
253 | 531
247 of
212 of 246
288
102 Copy List with Random Pointer
p.next = temp.next;
if (temp.next != null)
temp.next = temp.next.next;
p = p.next;
}
return newHead;
}
The break list part above move pointer 2 steps each time, you can also move one at
a time which is simpler, like the following:
while(p != null && p.next != null){
RandomListNode temp = p.next;
p.next = temp.next;
p = temp;
}
From Xiaomeng’s comment below, we can use a HashMap which makes it simpler.
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null)
return null;
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode,
RandomListNode>();
RandomListNode newHead = new RandomListNode(head.label);
RandomListNode p = head;
RandomListNode q = newHead;
map.put(head, newHead);
p = p.next;
while (p != null) {
RandomListNode temp = new RandomListNode(p.label);
map.put(p, temp);
q.next = temp;
q = temp;
p = p.next;
}
p = head;
q = newHead;
while (p != null) {
if (p.random != null)
q.random = map.get(p.random);
else
248 of
213 of 246
288
102 Copy List with Random Pointer
q.random = null;
p = p.next;
q = q.next;
}
return newHead;
}
249 of
214 of 246
288
103 Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made
by splicing together the nodes of the first two lists.
103.1 Analysis
The key to solve the problem is defining a fake head. Then compare the first elements
from each list. Add the smaller one to the merged list. Finally, when one of them is
empty, simply append it to the merged list, since it is already sorted.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode p1 = l1;
ListNode p2 = l2;
257 | 531
251 of
215 of 246
288
103 Merge Two Sorted Lists
p = p.next;
}
if(p1 != null)
p.next = p1;
if(p2 != null)
p.next = p2;
return fakeHead.next;
}
}
252 of
216 of 246
288
104 Odd Even Linked List
104.1 Problem
Given a singly linked list, group all odd nodes together followed by the even nodes.
Please note here we are talking about the node number and not the value in the nodes.
The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
104.2 Analysis
This problem can be solved by using two pointers. We iterate over the link and move
the two pointers.
259 | 531
253 of
217 of 246
288
104 Odd Even Linked List
p1.next = p2.next;
p1 = p1.next;
p2.next = p1.next;
p2 = p2.next;
}
p1.next = connectNode;
return result;
}
254 of
218 of 246
288
105 Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only
once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
105.1 Thoughts
The key of this problem is using the right loop condition. And change what is nec-
essary in each loop. You can use different iteration conditions like the following 2
solutions.
105.2 Solution 1
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;
while(p != null){
if(p.val == prev.val){
prev.next = p.next;
p = p.next;
//no change prev
261 | 531
255 of
219 of 246
288
105 Remove Duplicates from Sorted List
}else{
prev = p;
p = p.next;
}
}
return head;
}
}
105.3 Solution 2
ListNode p = head;
return head;
}
}
256 of
220 of 246
288
106 Remove Duplicates from Sorted List
II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only
distinct numbers from the original list.
For example, given 1->1->1->2->3, return 2->3.
ListNode p = t;
while(p.next!=null&&p.next.next!=null){
if(p.next.val == p.next.next.val){
int dup = p.next.val;
while(p.next!=null&&p.next.val==dup){
p.next = p.next.next;
}
}else{
p=p.next;
}
return t.next;
}
263 | 531
257 of
221 of 246
288
107 Partition List
Given a linked list and a value x, partition it such that all nodes less than x come
before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two
partitions.
For example, given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.
ListNode p = head;
ListNode prev = fakeHead1;
ListNode p2 = fakeHead2;
while(p != null){
if(p.val < x){
p = p.next;
prev = prev.next;
}else{
p2.next = p;
prev.next = p.next;
p = prev.next;
p2 = p2.next;
}
}
prev.next = fakeHead2.next;
return fakeHead1.next;
265 | 531
259 of
222 of 246
288
107 Partition List
}
}
260 of
223 of 246
288
108 LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache. It should
support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the
cache, otherwise return -1. set(key, value) - Set or insert the value if the key is not
already present. When the cache reached its capacity, it should invalidate the least
recently used item before inserting a new item.
108.1 Analysis
The key to solve this problem is using a double linked list which enables us to quickly
move nodes.
The LRU cache is a hash table of keys and double linked nodes. The hash table
makes the time of get() to be O(1). The list of double linked nodes make the nodes
adding/removal operations O(1).
267 | 531
261 of
224 of 246
288
108 LRU Cache
return -1;
}
if(n.next!=null){
n.next.pre = n.pre;
}else{
end = n.pre;
}
if(head!=null)
head.pre = n;
262 of
225 of 246
288
108 LRU Cache
head = n;
if(end ==null)
end = head;
}
}else{
setHead(created);
}
map.put(key, created);
}
}
}
263 of
226 of 246
288
109 Intersection of Two Linked Lists
109.1 Problem
Write a program to find the node at which the intersection of two singly linked lists
begins.
For example, the following two linked lists:
A: a1 -> a2
->
c1 -> c2 -> c3
->
B: b1 -> b2 -> b3
First calculate the length of two lists and find the difference. Then start from the longer
list at the diff offset, iterate though 2 lists and find the node.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int len1 = 0;
int len2 = 0;
ListNode p1=headA, p2=headB;
if (p1 == null || p2 == null)
return null;
while(p1 != null){
len1++;
p1 = p1.next;
271 | 531
265 of
227 of 246
288
109 Intersection of Two Linked Lists
}
while(p2 !=null){
len2++;
p2 = p2.next;
}
int diff = 0;
p1=headA;
p2=headB;
}
p1 = p1.next;
p2 = p2.next;
}
return null;
}
}
266 of
228 of 246
288
110 Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
The key to solve this problem is using a helper node to track the head of the list.
public ListNode removeElements(ListNode head, int val) {
ListNode helper = new ListNode(0);
helper.next = head;
ListNode p = helper;
while(p.next != null){
if(p.next.val == val){
ListNode next = p.next;
p.next = next.next;
}else{
p = p.next;
}
}
return helper.next;
}
273 | 531
267 of
229 of 246
288
111 Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example, given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in
the list, only nodes itself can be changed.
Use two template variable to track the previous and next node of each pair.
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)
return head;
return h.next;
}
275 | 531
269 of
230 of 246
288
112 Reverse Linked List
ListNode p1 = head;
ListNode p2 = head.next;
head.next = null;
while(p1!= null && p2!= null){
ListNode t = p2.next;
p2.next = p1;
p1 = p2;
if (t!=null){
p2 = t;
}else{
break;
}
}
return p2;
}
277 | 531
271 of
231 of 246
288
112 Reverse Linked List
second.next = head;
return rest;
}
272 of
232 of 246
288
113 Reverse Linked List II
113.1 Analysis
int i=0;
ListNode p = head;
while(p!=null){
i++;
if(i==m-1){
prev = p;
}
if(i==m){
first.next = p;
}
if(i==n){
second.next = p.next;
p.next = null;
}
p= p.next;
}
if(first.next == null)
return head;
279 | 531
273 of
233 of 246
288
113 Reverse Linked List II
p1.next = second.next;
return head;
}
274 of
234 of 246
288
114 Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
For example, given linked list 1->2->3->4->5 and n = 2, the result is 1->2->3->5.
Calculate the length first, and then remove the nth from the beginning.
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null)
return null;
return head;
}
281 | 531
275 of
235 of 246
288
114 Remove Nth Node From End of List
Use fast and slow pointers. The fast pointer is n steps ahead of the slow pointer. When
the fast reaches the end, the slow pointer points at the previous element of the target
element.
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null)
return null;
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
276 of
236 of 246
288
115 Implement Stack using Queues
Implement the following operations of a stack using queues. push(x) – Push element
x onto stack. pop() – Removes the element on top of the stack. top() – Get the top
element. empty() – Return whether the stack is empty.
Note: only standard queue operations are allowed, i.e., poll(), offer(), peek(), size()
and isEmpty() in Java.
115.1 Analysis
class MyStack {
LinkedList<Integer> queue1 = new LinkedList<Integer>();
LinkedList<Integer> queue2 = new LinkedList<Integer>();
283 | 531
277 of
237 of 246
288
115 Implement Stack using Queues
278 of
238 of 246
288
116 Implement Queue using Stacks
class MyQueue {
value.push(x);
while(!temp.isEmpty()){
value.push(temp.pop());
}
}
}
285 | 531
279 of
239 of 246
288
116 Implement Queue using Stacks
280 of
240 of 246
288
117 Palindrome Linked List
We can create a new list in reversed order and then compare each node. The time and
space are O(n).
public boolean isPalindrome(ListNode head) {
if(head == null)
return true;
ListNode p = head;
ListNode prev = new ListNode(head.val);
while(p.next != null){
ListNode temp = new ListNode(p.next.val);
temp.next = prev;
prev = temp;
p = p.next;
}
ListNode p1 = head;
ListNode p2 = prev;
while(p1!=null){
if(p1.val != p2.val)
return false;
p1 = p1.next;
p2 = p2.next;
}
return true;
}
We can use a fast and slow pointer to get the center of the list, then reverse the second
list and compare two sublists. The time is O(n) and space is O(1).
287 | 531
281 of
241 of 246
288
117 Palindrome Linked List
secondHead.next = null;
p = p.next;
q = q.next;
return true;
}
282 of
242 of 246
288
118 Implement a Queue using an Array
in Java
There following Java code shows how to implement a queue without using any extra
data structures in Java. We can implement a queue by using an array.
import java.lang.reflect.Array;
import java.util.Arrays;
E[] arr;
int head = -1;
int tail = -1;
int size;
boolean push(E e) {
if (size == arr.length)
return false;
if(tail == -1){
tail = head;
}
289 | 531
283 of
243 of 246
288
118 Implement a Queue using an Array in Java
return true;
}
boolean pop() {
if (size == 0) {
return false;
}
E result = arr[tail];
arr[tail] = null;
size--;
tail = (tail+1)%arr.length;
if (size == 0) {
head = -1;
tail = -1;
}
return true;
}
E peek(){
if(size==0)
return null;
return arr[tail];
}
284 of
244 of 246
288
119 Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only
access to that node.
Supposed the linked list is 1 ->2 ->3 ->4 and you are given the third node with value
3, the linked list should become 1 ->2 ->4 after calling your function.
291 | 531
285 of
245 of 246
288
120 Moving Average from Data Stream
Given a stream of integers and a window size, calculate the moving average of all
integers in the sliding window.
LinkedList<Integer> queue;
int size;
return (double)sum/queue.size();
}
}
293 | 531
287 of
246 of 246
288
Test Lead Basics Manual Testing Sample Interview
Question and Answers prepared by Haradhan Pal
1 What is SDLC?
SDLC or the Software Development Life Cycle is a process that produces software with the
highest quality and lowest cost in the shortest time possible. SDLC provides a well-structured
flow of phases that help an organization to quickly produce high-quality software which is well-
tested and ready for production use.
2 Why SDLC?
Here, are prime reasons why SDLC is important for developing a software system.
• It offers a basis for project planning, scheduling, and estimating
• Provides a framework for a standard set of activities and deliverables
• It is a mechanism for project tracking and control
• Increases visibility of project planning to all involved stakeholders of the development
• process
• Increased and enhance development speed
• Improved client relations
• Helps you to decrease project risk and project management plan overhead
3 SDLC Phases?
The entire SDLC process divided into the following stages:
• Phase 1: Requirement collection and analysis
• Phase 2: Feasibility study:
• Phase 3: Design:
• Phase 4: Coding:
• Phase 5: Testing:
• Phase 6: Installation/Deployment:
• Phase 7: Maintenance:
3.1 Requirements Gathering/Analysis.
This is a process with much communication taking place between stakeholders, end
users and the project team. Meetings with managers, stake holders and users are held
in order to determine the requirements like; who is going to use the system? How will
they use the system? What data should be input into the system? What data should be
output by the system? These are general questions that get answered during a
requirement gathering phase. The QA engineer playing the role to configure the
requirements using requirements traceability matrix (RTM).
3.2 Design:
In this phase the software design is prepared from the requirement
specifications which were studied in the first phase. System Design helps in specifying
hardware and system requirements and also help in defining overall system
architecture. In this phase the QA Engineers comes up with the Test strategy, where they
mention what to test, how to test.
3.3 Implementation / Coding:
Upon receiving system design documents, the work is divided in modules/units and
actual coding is started. Since, in this phase the code is produced so it is the main focus
for the developer. This is the longest phase of SDLC. In this phase the QA Engineers
comes up with the Test Environment setup and test Case Documentation.
3.4 Testing:
After the code is developed it is tested against the requirements to make sure that the
product is actually solving the needs addressed and gathered during the requirements
phase. During this phase all types of like unit testing, integration testing, Smoke Testing,
functional testing, Sanity Testing, system testing, acceptance testing is done as well
as non-functional testing is also done.
3.5 Deployment: After successful testing the product is delivered / deployed to the customer
for their use. As soon as the product is given to the customers, they will first do the beta
testing/User
Spiral Model: The spiral model is a risk-driven process model. This SDLC model helps the team
to adopt elements of one or more process models like a waterfall, incremental, waterfall, etc.
This model adopts the best features of the prototyping model and the waterfall model. The
spiral methodology is a combination of rapid prototyping and concurrency in design and
development activities.
Prototyping Model: Prototyping model is a software development model in which prototype is
built, tested, and reworked until an acceptable prototype is achieved. It also creates base to
produce the final system or software. It works best in scenarios where the project's
requirements are not known in detail. It is an iterative, trial and error method which takes place
between developer and client.
7 What is STLC?
It is the testing process which is executed in systematic and planned manner. In STLC
process, different activities are carried out to improve the quality of the product.
Following steps are involved in Software Testing Life Cycle (STLC).
1. Requirement Analysis (RTM)
2. Test Planning (Test Strategy, Test Plan, Test Bed Creation)
3. Test Case Development (Test Procedures, Test Scenarios, Test Cases)
4. Environment Setup
5. Test Execution
6. Defect Reporting
8 What are Quality Assurance and Quality Control?
Quality Assurance:
Quality Assurance involves in process-oriented activities. It ensures the prevention of
defects in the process used to make Software Application. So the defects don’t arise when
the Software Application is being developed. The process is:
• Plan - Organization should plan and establish the process related objectives and
determine the processes that are required to deliver a high-Quality end product.
• Do - Development and testing of Processes and also "do" changes in the processes
• Check - Monitoring of processes, modify the processes, and check whether it meets the
predetermined objectives
• Act - A Quality Assurance tester should implement actions that are necessary to achieve
improvements in the processes.
Quality Control:
Quality Control involves in product-oriented activities. It executes the program or code to
identify the defects in the Software Application.
In other words, validation is concerned with checking that the system will meet the
customer’s actual needs. validation is an extremely subjective process. Validation
includes activities such as requirements modelling, prototyping and user evaluation.
While verification is concerned with whether the system is well-engineered, error-free,
and so on. Verification will help to determine whether the software is of high quality, but
it will not ensure that the system is useful. Verification includes all the activities associated
with the producing high-quality software: testing, inspection, design analysis,
specification analysis, and so on. It is a relatively objective process.
24 What is RTM?
Requirements Traceability Matrix (RTM) is used to trace the requirements to the tests
that are needed to verify whether the requirements are fulfilled. Requirement
Traceability Matrix AKA Traceability Matrix or Cross Reference Matrix.
Which Parameters to include in Requirement Traceability Matrix?
• Requirement ID
• Requirement Type and Description
• Test Cases with Status
55 What is a Defect?
The variation between the actual results and expected results is known as a defect. If a
developer finds an issue and corrects it by himself in the development phase, then it’s
called a defect.
56 What is an Error?
We can’t compile or run a program due to a coding mistake in a program. If a developer
unable to successfully compile or run a program, then they call it as an error.
57 What is a Failure?
Once the product is deployed and customers find any issues then they call the product
as a failure product. After release, if an end user finds an issue, then that particular issue
is called as a failure.
Describes what the product does Describes how the product works
1 What is SDLC?
SDLC or the Software Development Life Cycle is a process that produces software with the
highest quality and lowest cost in the shortest time possible. SDLC provides a well-structured
flow of phases that help an organization to quickly produce high-quality software which is well-
tested and ready for production use.
2 Why SDLC?
Here, are prime reasons why SDLC is important for developing a software system.
• It offers a basis for project planning, scheduling, and estimating
• Provides a framework for a standard set of activities and deliverables
• It is a mechanism for project tracking and control
• Increases visibility of project planning to all involved stakeholders of the development
• process
• Increased and enhance development speed
• Improved client relations
• Helps you to decrease project risk and project management plan overhead
3 SDLC Phases?
The entire SDLC process divided into the following stages:
• Phase 1: Requirement collection and analysis
• Phase 2: Feasibility study:
• Phase 3: Design:
• Phase 4: Coding:
• Phase 5: Testing:
• Phase 6: Installation/Deployment:
• Phase 7: Maintenance:
3.1 Requirements Gathering/Analysis.
This is a process with much communication taking place between stakeholders, end
users and the project team. Meetings with managers, stake holders and users are held
in order to determine the requirements like; who is going to use the system? How will
they use the system? What data should be input into the system? What data should be
output by the system? These are general questions that get answered during a
requirement gathering phase. The QA engineer playing the role to configure the
requirements using requirements traceability matrix (RTM).
3.2 Design:
In this phase the software design is prepared from the requirement
specifications which were studied in the first phase. System Design helps in specifying
hardware and system requirements and also help in defining overall system
architecture. In this phase the QA Engineers comes up with the Test strategy, where they
mention what to test, how to test.
3.3 Implementation / Coding:
Upon receiving system design documents, the work is divided in modules/units and
actual coding is started. Since, in this phase the code is produced so it is the main focus
for the developer. This is the longest phase of SDLC. In this phase the QA Engineers
comes up with the Test Environment setup and test Case Documentation.
3.4 Testing:
After the code is developed it is tested against the requirements to make sure that the
product is actually solving the needs addressed and gathered during the requirements
phase. During this phase all types of like unit testing, integration testing, Smoke Testing,
functional testing, Sanity Testing, system testing, acceptance testing is done as well
as non-functional testing is also done.
3.5 Deployment: After successful testing the product is delivered / deployed to the customer
for their use. As soon as the product is given to the customers, they will first do the beta
testing/User
Spiral Model: The spiral model is a risk-driven process model. This SDLC model helps the team
to adopt elements of one or more process models like a waterfall, incremental, waterfall, etc.
This model adopts the best features of the prototyping model and the waterfall model. The
spiral methodology is a combination of rapid prototyping and concurrency in design and
development activities.
Prototyping Model: Prototyping model is a software development model in which prototype is
built, tested, and reworked until an acceptable prototype is achieved. It also creates base to
produce the final system or software. It works best in scenarios where the project's
requirements are not known in detail. It is an iterative, trial and error method which takes place
between developer and client.
7 What is STLC?
It is the testing process which is executed in systematic and planned manner. In STLC
process, different activities are carried out to improve the quality of the product.
Following steps are involved in Software Testing Life Cycle (STLC).
1. Requirement Analysis (RTM)
2. Test Planning (Test Strategy, Test Plan, Test Bed Creation)
3. Test Case Development (Test Procedures, Test Scenarios, Test Cases)
4. Environment Setup
5. Test Execution
6. Defect Reporting
8 What are Quality Assurance and Quality Control?
Quality Assurance:
Quality Assurance involves in process-oriented activities. It ensures the prevention of
defects in the process used to make Software Application. So the defects don’t arise when
the Software Application is being developed. The process is:
• Plan - Organization should plan and establish the process related objectives and
determine the processes that are required to deliver a high-Quality end product.
• Do - Development and testing of Processes and also "do" changes in the processes
• Check - Monitoring of processes, modify the processes, and check whether it meets the
predetermined objectives
• Act - A Quality Assurance tester should implement actions that are necessary to achieve
improvements in the processes.
Quality Control:
Quality Control involves in product-oriented activities. It executes the program or code to
identify the defects in the Software Application.
In other words, validation is concerned with checking that the system will meet the
customer’s actual needs. validation is an extremely subjective process. Validation
includes activities such as requirements modelling, prototyping and user evaluation.
While verification is concerned with whether the system is well-engineered, error-free,
and so on. Verification will help to determine whether the software is of high quality, but
it will not ensure that the system is useful. Verification includes all the activities associated
with the producing high-quality software: testing, inspection, design analysis,
specification analysis, and so on. It is a relatively objective process.
24 What is RTM?
Requirements Traceability Matrix (RTM) is used to trace the requirements to the tests
that are needed to verify whether the requirements are fulfilled. Requirement
Traceability Matrix AKA Traceability Matrix or Cross Reference Matrix.
Which Parameters to include in Requirement Traceability Matrix?
• Requirement ID
• Requirement Type and Description
• Test Cases with Status
55 What is a Defect?
The variation between the actual results and expected results is known as a defect. If a
developer finds an issue and corrects it by himself in the development phase, then it’s
called a defect.
56 What is an Error?
We can’t compile or run a program due to a coding mistake in a program. If a developer
unable to successfully compile or run a program, then they call it as an error.
57 What is a Failure?
Once the product is deployed and customers find any issues then they call the product
as a failure product. After release, if an end user finds an issue, then that particular issue
is called as a failure.
Describes what the product does Describes how the product works
ALTER DELETE
DDL : Data Definition Language DML: Data Manipulation Language
TRUNCATE DCL : Data Control Language TCL : Transaction Control Language
DQL : Data Query Language
1
By Fang Ying, Sham
2
By Fang Ying, Sham
7. Save table to another table --into file_name: save result in another table (BASE TABLE)
select distinct customerlastname into temp
from customer
order by customerlastname
select * from temp --see the table (data type will remain)
8. Like (search something) -- (underscore sign) _ is only specific for one character only
-- (percent sign) % represents zero, one, or multiple characters
select * from customer
where customerlastname like '_r%'
3
By Fang Ying, Sham
--
SELECT FirstName, LastName, JobTitle, Salary,
CASE
WHEN JobTitle = 'Salesman' THEN Salary + (Salary *.10)
WHEN JobTitle = 'Accountant' THEN Salary + (Salary *.05)
WHEN JobTitle = 'HR' THEN Salary + (Salary *.000001)
ELSE Salary + (Salary *.03)
END AS SalaryAfterRaise
FROM EmployeeDemographics ED
JOIN EmployeeSalary ES
ON ED.EmployeeID = ES.EmployeeID
4
By Fang Ying, Sham
-- Replace
Select LastName, REPLACE(LastName, '- Fired', '') as
LastNameFixed
FROM EmployeeErrors
-- Substring
Select Substring(err.FirstName,1,3),
Substring(dem.FirstName,1,3), Substring(err.LastName,1,3),
Substring(dem.LastName,1,3)
FROM EmployeeErrors err
JOIN EmployeeDemographics dem
on Substring(err.FirstName,1,3) =
Substring(dem.FirstName,1,3)
and Substring(err.LastName,1,3) =
Substring(dem.LastName,1,3)
Select *
From #temp_employee
GO;
5
By Fang Ying, Sham
-- with Partition By
SELECT EmployeeID, Salary, AVG(Salary) OVER () AS
AllAvgSalary
FROM EmployeeSalary
-- Subquery in From
SELECT a.EmployeeID, AllAvgSalary
FROM (SELECT EmployeeID, Salary, AVG(Salary) OVER () AS
AllAvgSalary
FROM EmployeeSalary) a
ORDER BY a.EmployeeID
-- Subquery in Where
SELECT EmployeeID, JobTitle, Salary
FROM EmployeeSalary
WHERE EmployeeID in (SELECT EmployeeID FROM
EmployeeDemographics
WHERE Age > 30)
6
By Fang Ying, Sham
SQL JOINS
select
inventoryname,saledate,saleunitprice,salequantity,saleunitprice*salequantity
as [Total Amount]
from inventory inner join sale
on sale.inventoryid=inventory.inventoryid
order by inventoryname
inventory sales
inventory sales
7
By Fang Ying, Sham
--left join (might have NULL value, since some inventory might not have sales)
select inventory.inventoryid,inventoryname
from inventory left join sale on
sale.inventoryid=inventory.inventoryid
inventory sales
--left join
select inventory.inventoryid,inventoryname
from inventory left join sale on
sale.inventoryid=inventory.inventoryid
where sale.inventoryid is NULL
inventory sales
--right join
select sale.inventoryid,inventoryname
from inventory right join sale on
sale.inventoryid=inventory.inventoryid
inventory sales
8
By Fang Ying, Sham
Output:
employeeID Full Name managerID managerName
1002 Kelvin Koh 1001 Tan Mei Ling
1003 Amin Wong 1002 Kelvin Koh
Output:
employeeID Full Name managerID managerName
1001 Tan Mei Ling
1002 Kelvin Koh 1001 Tan Mei Ling
1003 Amin Wong 1002 Kelvin Koh
9
By Fang Ying, Sham
SQL UNIONS
1. Union
--allow you to combine two tables select cust_lname,cust_fname from customer
together (but the no. of columns & union
each column’s data types for 2 tables select cust_lname,cust_fname from customer_2
must be match)
--don't need common key, only need
common attributes
--merge, not showing duplicate record
customer customer_2
customer customer_2
customer customer_2
--use subquery
select cust_lname,cust_fname from customer
where(cust_lname) not in
(select cust_lname from customer_2) and
(cust_fname) not in
(select cust_fname from customer_2)
10
By Fang Ying, Sham
customer
inventory sales
11
By Fang Ying, Sham
SQL RANKS
1. ROW_NUMBER() --get a unique sequential number for each row
--get different ranks for the row having similar values
SELECT *,
ROW_NUMBER() OVER(ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary
USING PARTITION BY
SELECT *,
RANK() OVER(PARTITION BY JobTitle ORDER BY Salary DESC)
SalaryRank
FROM EmployeeSalary
ORDER BY JobTitle, SalaryRank
12
By Fang Ying, Sham
3. DENSE_RANK()
-- if have duplicate values, SQL assigns different ranks to those rows.
-- will get the same rank for duplicate or similar values
SELECT *,
DENSE_RANK() OVER(ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary
ORDER BY SalaryRank
RANK() DENSE_RANK()
SELECT *, SELECT *,
RANK() OVER(PARTITION BY JobTitle ORDER DENSE_RANK() OVER(PARTITION BY JobTitle
BY Salary DESC) SalaryRank ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary FROM EmployeeSalary
ORDER BY JobTitle, SalaryRank ORDER BY JobTitle, SalaryRank
-- skip a rank if have similar values -- maintains the rank and does not give any gap
for the values
13
By Fang Ying, Sham
4. NTILE() -- can specify required how many group of result, and it will rank accordingly
SELECT *,
NTILE(3) OVER(ORDER BY Salary DESC) SalaryRank
FROM EmployeeSalary
ORDER BY SalaryRank;
Group 1
Group 2
Group 3
USING PARTITION BY
SELECT *,
NTILE(3) OVER(PARTITION BY JobTitle ORDER BY Salary DESC)
SalaryRank
FROM EmployeeSalary
ORDER BY JobTitle, SalaryRank;
Group 1
Group 2
Group 3
14
By Fang Ying, Sham
2. ISNULL(expression, value) --ParcelID is same, but UniqueID is different; can assume that if the ParcelID is
--expression: to test whether is same, the Property Address will be same
NULL, value: to return if Select a.ParcelID, a.PropertyAddress, b.ParcelID,
expression is NULL b.PropertyAddress,
ISNULL(a.PropertyAddress,b.PropertyAddress)
From NashvilleHousing a
JOIN NashvilleHousing b
on a.ParcelID = b.ParcelID
AND a.[UniqueID] <> b.[UniqueID]
Where a.PropertyAddress is null
-- Update record
Update a
SET PropertyAddress =
ISNULL(a.PropertyAddress,b.PropertyAddress)
From NashvilleHousing a
JOIN NashvilleHousing b
on a.ParcelID = b.ParcelID
AND a.[UniqueID] <> b.[UniqueID]
Where a.PropertyAddress is null
❖ LEN(string)
15
By Fang Ying, Sham
Update NashvilleHousing
SET PropertySplitAddress = SUBSTRING(PropertyAddress, 1,
CHARINDEX(',', PropertyAddress) -1 )
Update NashvilleHousing
SET PropertySplitCity = SUBSTRING(PropertyAddress,
CHARINDEX(',', PropertyAddress) + 1 , LEN(PropertyAddress))
Select OwnerAddress,
PARSENAME(REPLACE(OwnerAddress, ',', '.') , 3)
❖ PARSENAME('object_name' ,PARSENAME(REPLACE(OwnerAddress, ',', '.') , 2)
, object_piece) ,PARSENAME(REPLACE(OwnerAddress, ',', '.') , 1)
From NashvilleHousing
--numbering works from
right to left
❖ REPLACE(string, old_string,
new_string)
Update NashvilleHousing
SET OwnerSplitAddress = PARSENAME(REPLACE(OwnerAddress,
',', '.') , 3)
Update NashvilleHousing
SET OwnerSplitCity = PARSENAME(REPLACE(OwnerAddress, ',',
'.') , 2)
Update NashvilleHousing
SET OwnerSplitState = PARSENAME(REPLACE(OwnerAddress, ',',
'.') , 1)
16
Low
-
Level
= Design
- Kapil Yadav
- OOPs concepts
- Design Principles
- Design Patterns
Kapil Yadav
-
INDEX
1 .
Classes and
objects .
→
public
→
Private (friend class and
friend fume] .
→ Protected
3 . Constructor
→
•
Default
→
Parameterized
→
copy
4. static
keyword
5 .
This keyword
6 .
New keyword
7. Const
keyword
8- Final
keyword
9.
Explicit keyword
10 .
Inheritance
Inheritance
single
→
Multiple
→
Inheritance
→ Inheritance
Multilevel
→
Hierarchical Inheritance
→
Hybrid Inheritance .
11 "
Polymorphism
→
Compile Time
Polymorphism
Function
overloading
•
•
operator overloading
Kapil Yadav
polymorphism
→ Run time
•
virtual Functions
12 .
Encapsulation
13 .
Data Abstraction
Builder
3.
Design Pattern
Design Pattern
4. Observer
5 Abstract
.
Factory Design
linkedin.com/in/kapilyadav22
Kapil Yadav
-
class : -
Blueprint
↓
→ state /Property /field/data member
design / type
*m⑦ behaviour / function / data function .
Humans hand
→§ }→
Ex - 2
state /properties
Leg
2
↓ 2
eyes
behaviour → walk eat
, speak , .
Architect class ,
gives Blueprint
→ is the
using
Blueprint ,
we make the house is object .
memory / space
takes class does 't
Object
→
.
,
→ class is a
logical component .
→
Object takes
memory from heap .
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
Data
Hiding
: -
Data
hiding refers to
restricting access
functions ,
and which are not .
→ There are 3
types of access modifiers available in
C++ .
I. Public
2 .
Private
3. Protected
→
By default ,
The access modifier of the members will be Private .
1. Public :
keyword used create
The
public is to
public
-
accessible
The
public members from part of the
•
are
any
program .
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
The
private keyword is used to create
private members
•
(data and
functions ] .
•
The private members can
only be accessed from
within the class .
•
However , friend classes and friend functions can access
private members .
class .
linkedin.com/in/kapilyadav22
Kapil Yadav
Friend class ? -
A friend class can access private and
class it
protected members of other in which is
defined as friend .
It is sometimes used to allow
a
particular class to access
private members of
other class .
linkedin.com/in/kapilyadav22
Kapil Yadav
Friend Function : -
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav
initialize data
objects
→
It is used to the members new
of .
return
Constructors don't have
type
→
any
.
→
don't
If we
specify a constructor, C++
compiler generates
a default constructor for object .
→
It should be placed in public section
of
class .
→ It can be overloaded .
Constructors in C++
→
we can do constructor private .
But what will
happen ?
linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav
☆
→ Do constructor returns
any
value ?
No constructor does not return value
,
any
.
Kapil Yadav
STATIC KEYWORD : -
variables in a class
objects
in a class .
not
object .
class Human {
Human C)
{ count tt ;
y
3; 11 initialize static member of class Human
int main C)
E coat <<
Human : : count -
Lendl ;
ng
object ?
Anis .
Yes .
linkedin.com/in/kapilyadav22
Kapil Yadav
NOTE : -
A non
-
static member function can
modify
a static data member as
long as the data member 's
visibility allows it .
keyword method
→
we cannot use this in static .
linkedin.com/in/kapilyadav22
Kapil Yadav
THIS
keyword :
-
→
Object Pointer A pointer contains address
of
-
called Pointer
an
object is
object .
local
this
object pointer in every
→ is a
instance member
function containing address
of the caller
object .
→ this
pointer cannot be
modify .
caller
→ 9T is used to refer object in member
function .
because
friends are not members of a class .
Only member
functions have a this
pointer .
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
NEW KEYWORD : -
→ The new is a
memory
allocation operator ,
→ The
memory initialized by
the new operator is
allocated in a
heap .
returns
It the
starting address of the
→
memory,
variable
which
get assigned to the .
variable
Type datatype of
• -
a .
•
variable -
name of the variable .
parameter - list -
initialized to a variable .
int *
pts =
new int ;
WHAT IS MALLOC ?
→ Malbec ) is function that allocates at
a
memory
the runtime .
→
Syntax
-
Ctypetamalloclsizeofctype));
variable
type it és the
datatype of
•
: the .
•
variable -
name : it defines the name of the variable
get the
pointer of specified type
a that
to the
points memory
.
linkedin.com/in/kapilyadav22
Kapil Yadav
NOTE :
-
The mallocc ) function returns the void pointer ,
$0
typecasting is
required to
assign a different
type to the
pointer The sizeof
.
operator is
much
memory
is
required for the allocation .
Allocation New
→ Memory using
delete p ;
linkedin.com/in/kapilyadav22
Kapil Yadav
Allocation mallee
Memory using
: -
→
If the sufficient memory is not available ,
mallee function returns the NULL
pointer .
→
de allocate
using free
Allocated can be
memory
function .
linkedin.com/in/kapilyadav22
Kapil Yadav
1. New
operator construct 1 . Mallee is a
function ,
it does
constructor to
initialize
an
object .
2. delete operator to
destroy
2.
free function to deallocate
the
the
object .
memory .
3. new is an
operator 3 . It is predefined function
a
5-
If sufficient memory is not 5 . Malloch ) will seteem a NULL
an
exception
6. we need to
specify 6
. We need to
specify number
allocated
number of objects .
of bytes
to be .
7. allocated be reallocated
memory by new 7 . It can
using
cannot be resized .
ocallocc)
function .
linkedin.com/in/kapilyadav22
Kapil Yadav
FINAL
keyword : _
overriding final
'
error -
functions
'
'
derive
error : -
cannot
from
'
final
' '
base '
Base in
' '
derived Derived
type
linkedin.com/in/kapilyadav22
Kapil Yadav
CONST KEYWORD ! -
→ Const
keywords used to define the constant
value that cannot
change during program
execution .
Use of const
keyword with different parameters : -
•
Use const variable
const with
Use
pointers
•
•
Use const with function arguments
•
Use const with class member functions
Use class
objects
•
const with .
1. Consent variable
const int a- 20 ;
a -_ at 105
OUTPUT : -
error .
2. Const pointer
cannot address of const
we
change the the
→
pointer will
alwaysis point to the same address
pointer .
linkedin.com/in/kapilyadav22
Kapil Yadav
Const into a;
]→ both pointer
are
to
linkedin.com/in/kapilyadav22
Kapil Yadav
5. Const
pointer pointing to a const variable : _
const
Syntax const datatypes varname ;
-
Kapil Yadav
6. Pass const
argument value to a non const
parameter of
- -
'
→ •
into ?
from
'
error : -
invalid conversion const intro to
const value to
integer us .
we
pass const or non
-
const
variable to the
function because
the value will be oeteerned
by the
function will be
constant
automatically .
As the
the
argument of
function is non
-
const .
linkedin.com/in/kapilyadav22
Kapil Yadav
8. For return
const
type and const
parameter : -
→ Here ,
both const and non -
const values can be
Otherwise
,
we will face the error .
"
linkedin.com/in/kapilyadav22
Kapil Yadav
Inheritance ? -
1.
Single
2. Multilevel
3. Hierarchical
4.
Multiple 3- Not in Java
5-
Hybrid
17 Base class
Single : -
→
↓
☒ → derived class
output : 35 60
linkedin.com/in/kapilyadav22
Kapil Yadav
2) Multilevel 1-
Car
t
Toyota
↓
Innova
linkedin.com/in/kapilyadav22
Kapil Yadav
37 Hierarchical ?
Employee
< ]
Intern FTE
linkedin.com/in/kapilyadav22
Kapil Yadav
MOM DAD
cH%D
classes
There Be
ambiguity the Base
→
can ,
when
use
scope resolution operator .
scope
g→ oesolution
operator
Kapil Yadav
Hybrid ?
-
Vehicle
Car
Racing
Ferrari derived from Cart
*
Racing
Ferrari
linkedin.com/in/kapilyadav22
Kapil Yadav
ADVANTAGES : -
Reusability
→
code .
→ don't
Improves code
readability as we need to
Inheritance classes
supports extensibility
→ as new can
classes
be
easily added to
existing
.
linkedin.com/in/kapilyadav22
Kapil Yadav
POLYMORPHISM : _
POLY MORPH
↓ ↓
Forms
Many .
→ In Ctt
, polymorphism is
mainly divided into two
types : -
→
Compile-time polymorphism .
→
Runtime Polymorphism .
Polymorphism
N
L
✓ ☒ ✓
Virtual
Function Operator
Functions
Overloading Overloading
1. Compile-time polymorphism : -
This
type of polymorphism
is achieved
by function overloading or
operator
overloading .
Function
Overloading
• : -
overloaded .
Functions be overloaded
by
→ •
can .
OR / AND
Kapil Yadav
changing the
type of arguments
•
.
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
Operator Overloading : -
with
C++ has
ability
the to
provide the operators a
as operator overloading
.
→
To overload an
operator a operator function
,
is defined
inside a class .
class class
{
-
name
return
type operator Cargs)
:
3;
Kapil Yadav
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav
R-ntmeymrp.cm?-
→
It is achieved
by function overriding .
Function
Overriding :
•
-
derived class
Function
overriding has
→
occurs when a a
Rules →
Must do inheritance .
→ same
function name / same
parameter .
Function ?
Virtual A virtual function is member
-
function ,
which is declare within a base class and
Run-time
They mainly use to achieve
→ are
Points to remember ? -
3 .
They are
always defined in the base class and
class (
may / maynot
overridden in a derived . we
linkedin.com/in/kapilyadav22
Kapil Yadav
OUTPUT -
This is call to
parent class area
linkedin.com/in/kapilyadav22
Kapil Yadav
OUTPUT : 25
Square area :
-
.
linkedin.com/in/kapilyadav22
Kapil Yadav
Use of Virtual Function ?
→
It allows us to create a list
of base class pointers
and call methods derived class without
of any
even
→
working of virtual functions (concepts of VTABZE and
VPTR) .
object of a
pointer is inherited
by derived
classes . .
Irrespective of not ,
2 .
object is created or
Virtual Table -
A table created at compile time for
derived
every single class
containing the most versions
each virtual
function that can be
class
called
by objects of the .
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
Virtual Destructor :-
object using a
pointer of base class
type
that
has a non -
virtual destructor oesults in undefined
behaviour .
OUTPUT
constructing
: -
base
constructing derived
Destructing base
linkedin.com/in/kapilyadav22
Kapil Yadav
OUTPUT ? -
constructing base
derived
constructing
derived
Destructing
Destructing base
Kapil Yadav
in the
memory , means no virtual pointer defined
yet .
,
so constructor should
always be non -
virtual .
Because not
the
object created virtual
→
is
,
construction is impossible .
→
The compiler must know the type of object
before creating it .
Constructors
'
Error -
Encapsulation : -
Encapsulation is defined as
wrapping up
of data and information under single
a unit .
Role of access
specifiers in encapsulation : -
The
process of implementing encapsulation can be scut divided
-
into two
steps : -
should be labeled as
public using the public access specifier .
linkedin.com/in/kapilyadav22
Kapil Yadav
details
and
hiding the internal
C++
provides great level of abstraction for
•
a . ex -
••
Abstraction classes
using .
•
Abstraction in header files .
linkedin.com/in/kapilyadav22
Kapil Yadav
not allowed
directly
→ to
we are access
my,z
however them member
function
using
, we can access
of the class .
→ Increases Zeus
ability .
→
Implementation details class
of the are
protected from
the inadvertent user level errors .
linkedin.com/in/kapilyadav22
Kapil Yadav ①
Clean code ? →
easily readable
by other
developers .
Why ?
How ?
→
meaningful variable name
, function ,
class etc .
→ comments .
→ Modular
→
functions
→
short,
DESIGN PRINCIPLES : _
DRY Don't
repeat yourself
→ :
.
→ Kiss
keep it simple stupid
:
.
→
Abstraction :
Features of ?
Good
Design
-
l . Code Reuse : -
'
is
2.
Extensibility
:
change the
only constant
thing
_
in
programmer
's life ?
linkedin.com/in/kapilyadav22
Kapil Yadav
Naming Intension
revealing
→ -
names .
→
descriptive names .
-
int ✗
int getsumc ) ; a
~ ✗
b
int
getanswe.ro ; int
② lines]
Verb
Function Name dedicate
single
→ -
short to task
, ,
.
•
should have fewer arg cements ( Use Helper function ) .
• sort , several
, swap, pow .
→
Ward 's principle
-
Class Name
-
Noun
→
descriptive
meaningful
→
→
intent
revealing
-
linkedin.com/in/kapilyadav22 RCnMartin_
Kapil Yadav
one
thing only .
② KISS ( Keep it
simple stupid)
if (a)
{ if (b)
{ ifcc)
{ if (d)
{ 3
else {3
3
}
3
→
if (a && 6 && c && d) is
simple .
Benefits ? -
easy
to read
/ understand .
•
less time to code .
are .
linkedin.com/in/kapilyadav22
Kapil Yadav
③ YAGNI : -
You ain't
gonna
need it .
"
→
Don't
engineering
Do over .
Benefits : -
•
Slave time .
•
concise code .
Boy -
Scout Law ? -
The code
quality tends to
degrade
with each
change .
-
(tech debt .
'
→
leave behind better state
Always the code in a
found
"
than it
you .
linkedin.com/in/kapilyadav22
Kapil Yadav
→ Maximum cohesion .
Coupling
: -
It is the degree to which each module depend
on other modules .
HUMAN → CAR
→
Required low
coupling .
Command -
linkedin.com/in/kapilyadav22
Kapil Yadav
Is there
exception of CQS ?
any
SOLID -
a set of principles .
S
single responsibility principle
-
.
0
Open closed
principle
-
-
.
L -
Liskov Substitution Principle
I Interface Segregation Principle
-
D-
Dependency Inversion Principle .
code ) should
package ,
source have a reason to
change by
only one actor .
function calculate
salary ,
calculate hours , savec-mpdate.CI .
Calculates
alary C) CFO
-
calculatehours C) -
Technical
savec-mpdato.CI HR
-
linkedin.com/in/kapilyadav22
Kapil Yadav
used and it
If calculates
alanya by
→ is CFO
acquired
a method
getRegularHours O and make a
change in
Hours C) ,
which is
managed by someone else .
linkedin.com/in/kapilyadav22
Kapil Yadav
here class
→ what
happened was ,
one
exposed two or three
different methods ,
which were
corresponding to different
stakeholders of the software .
It is
voélating Single
Responsibility Principle .
stakeholder ,
which
fulfill one business
Requirement ,
till then it is
fine .
class have
That means ou r can more than one
public
method as
long as the
change in those
public method
is
requested by one stakeholder / group of stakeholders .
→ Create 3
different class ,
the calculation
of salary
doesn't
depend
need to know about / doesn't need on method
,
any
which is used in calculate hours .
→
By decomposing one class into multiple classes, we
can
actually adhere
single
sits in
oesponsiblity ,
where
the business
requirement one
particular
class , and request to
change those
logics comes from
one actor
only .
OPEN -
CLOSED PRINCIPLE
"
→
software entities such as classes, modules , functions etc ,
.
should be
open for extension
,
but closed for modification .
functionality should be
by
→
Meyer originated
→
Bertrand the term OCP .
Implementation Guidelines : -
→ The
simplest way to apply OCP is to
implement the
new
functionality on new derived classes .
abstract interface .
WHY OCP ?
Not
If followed
→
End
testing the entire
functionality
→
up
QA need test flow
→
Team to the entire .
linkedin.com/in/kapilyadav22
→
Costly Process for the
Organization
Breaks well
single roesponsibility
→
the as .
1-
doesn't
It 's
design allow behaviour
→
to extend the unless
we
change the code .
for ex -
sensormodel , we have to
change distance sensor class to
by defining
→
we start what we want a distancesensor to
do below
in
general .
In code ,
Distance sensor is
generic, it
to concrete instance it
of
a .
class or in
javea we can
say interface .
→ when we create
specializations of
the interface for
,
each
child class ,
that implements the distance sensors interface
without
changing any existing code .
linkedin.com/in/kapilyadav22
LISKOV SUBSTITUTION PRINCIPLE ( LSP)
for
"
must substitutable their base
subtypes be
→
types ?
"
"
may
be
replaced with objects of type
S
Derived substitutable
types be
completely
→
must
→ LSP is a
particular definition of a
subtyping
relation , called C. ) behavioral
strong subtyping .
Introduced
by Barbara Leskov
→
.
→ Extension
of the
Open close principle .
Implementation Guidelines
No
exceptions be
by the
subtype
→ new can thrown .
derived
New classes
just extend without
replacing
→
the
functionality of old classes .
linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav
"
fat interface
→
one need to be
split to
many
smaller and relevant interfaces so that clients can
to them .
→
The ISP was first used and
formulated by
Robert for
c. Martin while
consulting Xerox
Case
Study
Problem ? -
had created
printer system that
→ Xerox a new
could perform a
variety of tasks such as
stapling and
faxing along with the
regular
printing task .
→ The
software for this
system was created
→
Modifications and
Deployment to the
system
became more
complex .
SOLUTION
→ One
large Job class is
segregated to multiple
interfaces depending on the
requirement .
linkedin.com/in/kapilyadav22
public Animal
Dog
:
Animal
{ feed C);
{ feed :
Pete] ;
pet ; 3
3;
Lion :
public Animal
{ feed C) ;
pete
;✗
3
linkedin.com/in/kapilyadav22
Kapil Yadav
D-
Dependency inversion Principle .
"
(Interfaces)
"
→
Abstractions should not depend on details . Details
should depend on
abstracl.im#- interfaces
should be abstract
modules
thought of as an
linkedin.com/in/kapilyadav22
Kapil Yadav
, ,
structural
Bridge Adaptive, Composite
-
,
> Behavioural
Interpreter
_
, strategy ,
observer .
7)
Factory Method
Design Pattern : -
→ ( subclasses are
responsible to create the instances
of
the class ?
→ This pattern is also known as Virtual constructor .
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
→ Now ,
we are
going to create a
factory it will
,
creation
take care
of
entire
logic without
,
bother .
Kapil Yadav
will
logic factory if
→ Now , write and
we our in ,
client
any change required ,
will not bothered , we
only need to do
change in
factory .
Library to decide
→ be
should which
responsible obj type
create based
to on
input .
→ client should
just call
library's factory and
pass type
without
worrying
about actual
implementation of creation
of object .
Pattern :
Advantages of Factory Design -
the
type of objects to create .
loose
promotes the
couplingclasses
by eliminating the
•
It -
need to bind
application specific
-
into code the .
•
when a class doesn't know what sub-classes will
be required to create .
classes
when class wants that its sub
specify
•
a -
created
the
objects to be .
Kapil Yadav
Ex-2_: -
Plan
Generate bill
rate
getRate()
calculateBill()
mainC)
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
of instances are 1
this
message
is
from user 1 .
→
New csnstance created .
No .
of instances are 2
this
message is from user 2 .
→
I want to restrict them to able to access
logger constructor .
class
1. Restrict users
from creating object of .
→
By making the constructor private , we are
oestoicting users
from creating object or
Kapil Yadav
→ code fails In
Multithreading Case .
same
,
so total 2 instances will be created .
linkedin.com/in/kapilyadav22
Use -
Mute , Kapil Yadav
Kapil Yadav
first time ,
when
logger instance = NOLL
,
and multiple
lock
threads
trying to access
loggesinstanee , we need ,
but
don't lock,
once
loggerinstance is created, we need
double
so
put check
ifcloggerinstance __=nullptD
then lock,
only
•
use
Kapil Yadav
Double checked
locking
-
: -
, if we
only
lock null,
need when
loggesirstance check
-_ =
a ,
so
this condition ,
because locks are
expensive .
linkedin.com/in/kapilyadav22
Kapil Yadav
[ ]
linkedin.com/in/kapilyadav22
Kapil Yadav
17 constructor
Make
copy as
private .
27 operator private
Make
equal to ,
overloading as .
astrict to operations
uses
copy .
linkedin.com/in/kapilyadav22
Kapil Yadav
[ T-sxstn.cl
users
linkedin.com/in/kapilyadav22
Kapil Yadav
structure
→ whenever we are
building very complex
which has a lot
of configurations in it .
Advantages of Builder
Design Pattern : _
clear
It provides separation between the construction
•
and
srepzesentation of an
object
.
process .
supports to
change the internal representation of
•
It
objects .
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
"
Pattern
just define
→ observer
An that one-to-one
says
states , all its
dependency so that when one
object changes
dependents are notified and updated automatically .
Ex -
group notifications .
linkedin.com/in/kapilyadav22
Kapil Yadav
Kapil Yadav
5. Abstract
Factory Design :
→
Factory design pattern was
creating concrete classes
or
object .
create
→ Abstract
factory design pattern is
going to
factories that is
going
to coeale
object .
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
linkedin.com/in/kapilyadav22
Kapil Yadav
Performance
Performance
Testing and its
Testing and its
value for startups
value for startups
For any new business coming in the market, it becomes
crucial for the technology to be,
- Resilient,
- Reliable,
- Stable and above all, something which gives
- Confidence to the customers.
Performance
Testing
This is the reason Performance Testing is a key factor for
us to evaluate the application and technology a startup
is basing its existence.
Stress
- Stress on Data
- Stress on Boundaries
- Requests and Responses
- User Load
- Transaction Load
- Internal Functions and APIs
Reliability
and Stability
- Data Updates and Handling
- Network handling
- Communication
- Speed of response
- Relevance of information
- Completeness of information
Failure and
Recovery
- Error handling
- Crashes and Shutdowns
- Help Tips and User Guidance during recovery.
- Backend Preventions and Support
User
Experience
- User understands the load and peak time constraints.
- Feedback loops
- System Navigation
- Third Party Experience and Reconnect
INTERNAL
1. Name the four main processes for creating and uploading a Power BI
report onto the Power BI Server.
• Get and Transform Data, also known as Power Query, which involves
importing data and manipulating it.
• Data Modelling the data. This allows for adding calculated columns,
measures, and relationships between data sources.
• Adding data visualizations.
• Publishing onto the Power BI Service.
2. What are the main programs, apps, or options for buying or using
Microsoft Power BI?
Power BI visualizations
3. What are the differences and similarities between a table and a matrix
visualization?
Both tables and matrixes show data in a text format, similar to a spreadsheet.
Note that the plural of “matrix” in Power BI is “matrixes” rather than “matrices.”
Tables can show one row for each source table row. Both tables and matrixes can
show aggregated values (such as SUM, COUNT, MIN, or MAX).
A table shows one column for each field used. So if you have six fields included in a
table, there would be six columns.
When you use Drill Down, you go to a different level of detail. For example, you may
be looking at a matrix that currently shows years. You can drill down so that the
matrix shows quarters or months. Or you could show the combination of years and
quarters and months.
INTERNAL
When you use Drill Through, you go from one report to another that concentrates on
some aspect of the first report. For example, you might click on a country in one
report, and drill through to a second report that concentrates on that country.
5. How can you add Drill Through to a report and how can you use it?
You can add drill through by going to page B and dragging the relevant field to the
Add Drill Through Fields Here section.
2. Going to Data/Drill —> Drill Through or right-clicking on the field and going to Drill
Through in the Context menu
2. Select a visualization
3. Select which interaction (filter, highlight, or none) you want to happen on the
second visualization
You can use a slicer, which allows you to filter on one page or multiple pages.
Configure which pages a slicer filters by going to View —> Sync Slicers.
INTERNAL
Go to View —> Selection, which lists all the visualizations on the page, visible and
invisible. Toggle visibility for any visualization in this pane.
10. You set up a bar chart with the year in the X-axis and sales in the Y-
axis. How can you sort it so that the years are shown in sales order,
instead of year order?
By default, fields such as years are shown in a continuous sequence. For example,
2025 follows 2024 and is before 2026.
To show it in a different order, go to Visualizations —> Format —> X-axis, and change
Type from Continuous to Categorical. You can then sort the visualization by clicking
on More Options (the three dots in the top right corner of the visualization) and click
on Sort By —> Sales.
11. You have set up your page as you want to show it later. How can you
save this setup for future use? Name two ways you can retrieve it.
You can save your set up by using a Bookmark. Go to View —> Bookmarks and click
on Add.
You can also modify the bookmark so you can choose whether it remembers: the
Data, the Display, and/or the Current Page, and which visuals it remembers.
To retrieve your Bookmarks, you can go to View —> Bookmarks again and click on
the relevant bookmark. Or insert a shape, button, or another control with an Action,
and change the Action so that it goes to the relevant bookmark. This is a more user-
friendly way for the end-user to choose different bookmarks.
3. Switch this to On
You can then control the formatting by going to Advanced Controls within
Conditional Formatting.
13. I’ve imported the data, but the wrong row is being used as the headers
— the row below should be used instead. What do I do?
The Applied Steps pane in Power Query shows the process that Get and Transform
Data uses. When you load data initially, then the computer adds a few steps
automatically. They typically include:
However, if the first row was not meant to be used as the header (for example, there
is a title in the data set, and the headers are in the second row), then this can be
premature.
1. Remove the Change Type step (as Applied Steps should be removed in reverse
order)
3. You can remove any Applied Steps by clicking on the x next to these steps
4. To remove any rows which should not be included in the data, go to Home —>
Remove Rows, and enter the number of rows to be removed
6. It’s a good idea to change the data types of your columns, most simply by
selecting all of the columns and going to Transform —> Detect Data Type (and
correcting any errors)
14. What is the name of the formula language used in Get and Transform
(or Power Query)?
There are several ways to remove columns from your imported data. They include:
Right-click on a column or columns that you want to remove and select Remove.
• Go to Home —> Choose Columns. You can then uncheck columns you do not
wish to keep.
• Select the columns you want to remove and go to Home —> Remove Columns
—> Remove Columns.
• Select the columns you want to keep and go to Home —> Remove Columns —
> Remove Other Columns.
• Use the Table.RemoveColumns formula.
16. What is the difference between merge queries, append queries, and
combine files?
INTERNAL
• Merge queries allows you to introduce columns from one query into another
(or a new) query.
• Append queries allows you to introduce rows from one query into another (or
a new) query.
• Combine files allows you to load files on your computer and combine them
into a new query. The advantages of this include that these individual files
don’t have to become individual queries first and that you can simply point to
an entire folder as the source.
18. Name two different ways to convert a text column to date format.
• Clicking on the ABC or ABC123 icon next to the field name and selecting Date
or Date/Time.
• Selecting the column and going to Home —> Data Type —> Date/Time.
• Selecting the column and going to Transform —> Date —> Parse.
The advantage of the last method is that it uses the DateTimeZone.From(_) formula,
which you can modify to change the locale. This is useful if, for example, your
computer is set up in American date format, but the dates are shown in British
format. In this case, you can modify the DateTimeZone.From formula to include the
fact that the dates are in the British format.
19. How do you use hard code the date 2 March 2024 in a formula?
You would use #date(2024,3,2). Make sure that “date” is all in lower case letters.
20. What is the quickest way to create a list of dates from 1 January 2022
to 31 December 2022 with every date included?
When loading data from SQL Server or similar databases, it is possible that Power BI
will interpret some of the Applied Steps that you enter by changing the initial SQL
Server SELECT statement. The advantages of this are:
22. When using DAX formulas, what is BLANK()? Give an example of when
you should use it.
BLANK() is the equivalent of NULL in other languages. It means that the answer is
nothing.
You should use it when using zero or an empty string would lead to the wrong result
in a later formula. For example, there is a difference between 0+1 and BLANK()+1, as
the latter results in BLANK() instead of 1.
23. Can you write a formula that returns the number 1 only if all of the
following are true: [Price] > 2, [Price] < 10, and [Price]<>5 ?
You can use the following formula: =IF(OR(OR([Price] > 2, [Price] < 10),
[Price]<>5),1,0)
Unlike OR in Excel, the OR function in DAX can only have two arguments. You have to
nest ORs if you want to have more than two arguments.
INTERNAL
This formula is meant to retrieve the tenth character in the field [Description].
However, unlike Excel, if you use this when [Description] is less than 10 characters
long, it will result in an error. This error will then cascade throughout the column,
meaning that the entire column will result in errors.
You should couple this formula with IFERROR, or IF and LEN, to trap this error.
A calculated column results in an answer for each and every row in a query. A
measure results in one answer for each context in which it is calculated.
Because the calculated column needs to calculate an answer for each row, this
results in an increase in the processing power needed.
Some functions that you can use validly in calculated columns cannot be used in
measures, and vice versa.
Let’s assume that there are two tables, A and B, which may be data from different
sources, but are connected using a one-to-many relationship. For example, table A
could be a list of employees, and table B a list of their expenses, and a single
employee could have multiple expenses.
RELATED allows you to get a single value where the relationship goes from “many”
to “one” based on the current filter context. For example, you could add a calculated
column using the RELATED formula in table B to import an employee’s name from
table A.
INTERNAL
RELATEDTABLE allows you to get multiple rows where the relationship goes in the
opposite direction, from “one” to “many.” For example, you could add a calculated
column in table A using the RELATEDTABLE formula to get all the expenses.
RELATEDTABLE typically requires another function, such as SUM, to deal with the
multiple rows.
SUM totals (for example) a column in a table, based on context. So if the context is a
particular employee, then SUM could total all of the expenses for that employee.
SUMX allows you to do a calculation before totaling the column. For example, you
could multiply two fields together, such as the number of items by the unit price for
each item, before totaling the column.
The CALCULATE function allows you to perform an expression based on a filter. For
example, you could calculate all of the expenses for a particular employee, but only
for a particular month.
30. If DueDate for a particular context is July 17, 2025, what period does
the formula DATESINPERIOD([DueDate],FIRSTDATE([DueDate]),-7,DAY)
retrieve?
As the number of days is negative, the period goes before the July 17, 2025 date.
However, it goes back for seven days inclusive, so the first date is July 11, not July
10. So the total period is July 11-17, 2025.
While a report may be loosely referred to as a dashboard, the term “dashboard” has a
specific meaning in the Power BI Service.
A Power BI app is a packaged series of dashboards and reports that can be shared.
1. Create roles while you are editing in Power BI Desktop using DAX expressions.
2. After uploading it into the Power BI service, add Row Level Security to the Dataset.
35. How can you refresh data stored on Power BI when the data is stored
on your machine or network?
You should use a data management gateway. There are two different types:
• The on-premises data gateway should be used if you have multiple users
connecting to the data sources.
• The on-premises data gateway (personal mode) should be used if you have
one user connecting to sources.
Project Quality Plan
T14-2305 – Darwin – New Henbury School –
Design Development and Construction Project
Table of Contents
1.2 Amendments
All amendments are to be acted upon by the holders of this document upon receipt of the amendment. The
plan will be finalised during the project launch and will be progressively reviewed and updated if required.
Revision
Distribution
Date
Copy Holder Details
Issued
Chris Giannikouris Halikos Design Manager Halikos Pty Ltd April 2015
Connor Newble Senior Project Manager Halikos Pty Ltd April 2015
Brian Hogbin SEQ Compliance Manager Halikos Pty Ltd April 2015
Johnny McLaughlin Construction Site Manager Halikos Pty Ltd April 2015
Sharon Sutton SEQ Compliance Advisor Halikos Pty Ltd April 2015
Authorisation
The construction and commissioning of a new school oval for the use of Dripstone Middle School in
accordance with the 'for construction' documents included with the Request For Tender (RFT);
• Decommissioning of the existing playing oval is to commence only on completion of with the
permission of the Superintendent. and
The design development, 'for construction' documentation and construction of the new Henbury
School in accordance with the Principal’s design and contractual documents. The works also
include all necessary statutory approvals, certifications, production of operational management
documentation, work as executed documentation and graphic representations as required to
convey the project intent to stakeholders.
The Superintendent shall consider and approve each stage and early works packaging before the Halikos
commences each stage. Such approval may be given after Halikos demonstrates to the Superintendent that
the Contractor’s design and construction methodology meets the requirements and quality required of the
RFT and associated documents.
The intention of such consideration by the Superintendent is further to ensure the existing Dripstone school,
its services, and the local community are not unduly disrupted or inconvenienced.
2.0 INTRODUCTION
This Project Quality Plan prepared by Halikos sets out in detail all procedures the Project team shall
implement to manage its activities on and near the site. This Plan will be implemented and maintained
throughout the duration of the Project.
Halikos have proposed a Project Management team led by the Construction Manager and an experienced
Project Manager who has managed projects of similar size and complexity to this Project.
The Halikos Project Management Team selected for this project will consist of experienced personnel with a
demonstrated ability to manage the construction workforce and who have undertaken many design and
construction projects.
Bringing together a proven team who have previously worked together, and who are local Darwin residents,
eliminates many of the problems associated with project start-up and reduces the risk of mid-project staff
changes.
All of the personnel nominated are proven performers with regards to delivering construction projects to the
highest quality, on budget and on time.
Our project team have been working full time on this project during the tender period and have
comprehensive knowledge of this project’s objectives and challenges. The project team is currently available
and ready to immediately mobilise on to this project.
AS/NZS ISO 9004:2009 - Managing for the sustained success of an organization -- A quality
management approach
Halikos Pty Ltd PMP-3-01 Project Health and Safety Management Plan
Copies of all Legislation and relevant standards shall be held at the Project site.
Urban Road Design – Guide to the Geometric Design of Major Urban Roads
Managing Urban Stormwater, Soils and Construction – Vol 1, 4th Edition, Landcom
Subcontractor records including quotes & transmittals, subcontract agreements, purchase orders,
instructions, payments, variations and correspondence
Register of Subcontractors
Noncompliance reports
Audit records
Site Diaries
Construction programs
Minutes of meetings
Record of Defects
Relevant procedures and records (including site safety and environmental management)
This plan describes the unique requirements of this project and its application throughout the project
lifecycle. This plan will also be the prescribed mechanism for the quality compliance benchmark throughout
the project.
4.2 Procedures
Project procedures provide specific details for the management of the identified quality issues at the project
level, including any relevant forms or checklists. Project procedures will always be subject to evolutionary
change throughout the project lifecycle as the expected standard of service provision may change.
Project procedures are also used as the provision of compliance confidence within the Project itself. This
compliance confidence enables both the customer and Halikos to ensure all system targets are maintained
as enablers to the identified output of the Project.
Date;
Product concerned;
When sub-contractors' ITP’s are required, verification of their compliance with the specified
requirements;
Characteristics to be tested;
Halikos maintain project records to provide evidence of compliance to requirements in accordance with
written procedures. Electronic records are protected by a backup system. The computer system is run from
an Uninterrupted Power Supply.
Documents required by the quality management system shall be controlled. Records are a special type of
document and shall be controlled according to the requirements stated in this sub-section.
A documented procedure has been established to define the controls needed to:
Ensure that changes and the current revision status of documents are identified;
Ensure that relevant versions of applicable documents are available at points of use;
Ensure that documents of external origin are identified and their distribution controlled; and
Prevent the unintended use of obsolete documents, and to apply suitable identification to them if
they are retained for any purpose.
Purchase orders;
Registers of sub-contractors;
Delivery Dockets;
Invoices;
Completed ITP’s;
Test Results;
Calibration schedules;
Noncompliance reports;
Training records.
During the Project, Halikos shall make all quality records available to the Superintendent at all times during
normal working hours when requested to do so. To that end, Halikos shall (within one calendar month of date
of practical completion) provide a register of all quality records held.
Halikos shall retain all quality records for at least five years from the date of Project completion.
The Halikos Quality Policy is included in appendix 1 of this plan. The Policy has been formulated with regard
to Halikos organisational aims and the needs and expectations of its clients.
Copies of the Quality Policy will be displayed at all Halikos offices. All workers are instructed in the Quality
Policy and their roles and responsibilities in the Quality System at initial induction and through regular
communication.
At Operational level, the Project Manager (or delegated staff member) is the Quality Manager
Representative (QMR) and has overall responsibility for Quality; Safety and Environmental functions
of the Halikos Group, these functions are managed at the Halikos Company Headquarters.
At Project level, the Construction Site Manager (or delegated staff member) is The Project Quality
Manager Representative (PQMR) and has overall responsibility for Quality, Safety and
Environmental functions of Halikos Pty Ltd on the Project. The PQMR reports directly to the QMR.
Fundamental checking by site supervisory staff and site based subcontractors will also be a feature
of the PQP. Placing responsibility for the achievement of quality objectives at the workface will lead
to greater accountability at this level.
The duties and responsibilities of Halikos staff are defined in position descriptions maintained by the Human
Resource Manager at the Halikos Company Headquarters.
Project Director/Manager:
The Project Manager has overall authority in the determination of all matters affecting the
implementation and operation of the project. The Project Manager reports directly to the
Construction Manager.
Reviewing and authorising the Project Quality Plan (PQP), and other project plans;
Ensuring all project personnel are suitably trained, and possess the necessary skills to undertake
their designated quality responsibilities;
Providing sufficient funds, materials and equipment to ensure the PQP objectives are achievable;
Participating in the review of the quality system and other relevant quality meetings and programs;
The PQMR is responsible for the implementation of the Project Quality Plan (PQP). The PQMR
reports directly to the Project Manager and has a reporting function to the Quality Manager
Representative.
The PQMR has the authority to resolve all quality assurance matters in conjunction with the Project
Manager. The PQMR has the authority to reject non-conforming products/processes and the responsibility
to ensure that remedial measures are implemented to curtail further non-conformance.
Ensuring the Project Quality Plan is correctly implemented to meet the requirements of the project;
Reviewing inspection reports are ensuring any actions required are initiated;
Verification Personnel are responsible for inspecting and testing works in accordance with the Inspection and
Test Plans. Such work shall include off-site manufacture and fabrication and onsite works.
Halikos has a qualitative measure for Verification and Validation and they are defined as:
Customer Validation - The assurance that a product, service, or system meets the needs of the
customer and other identified stakeholders. It often involves acceptance and suitability with external
customers.
Internal Verification - The evaluation of whether or not a product, service, or system complies with a
regulation, requirement, specification, or imposed condition. It is often an internal process.
Verification Personnel have the authority to reject any nonconforming product/process and are answerable to
the PQMR in this regard. Various project personnel with relevant experience/qualifications will be used to
perform the necessary inspections to ensure the quality of product is being upheld.
Performing the inspection and testing, or witnessing the inspection and testing by others, as laid
down in the Inspection and Test Plans including release of Halikos nominated Hold Point;
Verifying that the procedures being used are adequate for effective control of quality;
Ensuring and verifying corrective action is taken when nonconforming work is identified.
o The “Halikos, Construction Office” shall maintain customer focus by satisfying current and
future customer needs. Customers can be both internal and external to the organisation.
o The “Halikos Construction Office” shall measure customer need satisfaction by means of a
validation process.
o The “Halikos Construction Office” shall strive to meet customer expectations with due regard
to cost, schedule, technical, programmatic and supportability facets of risk mitigation.
o The “Halikos Construction Office” staff shall adopt a process approach to achieve a
consistent methodology of operation.
o Continual improvement of all quality policy principles shall be pursued through the review
and audit of the “Halikos Construction Office” and ‘Halikos Operational Projects’ processes.
management system to the Managing Director and the Halikos’ senior management group. This position will
be held by the Safety Environment and Quality Manager.
5.7 Frequency
The Management System Review meetings should be conduct as per the FRM-6-55 Integrated Management
Systems Planner, or as required. The system will be reviewed on a six monthly basis, at a minimum annually
to ensure information is communicated effectively throughout the company and any changes to legislation,
codes of practices or industry best practice are adopted and implemented. The Managing Directors
directives can be documented and implemented across the group to ensure they reflect those legislative
requirements. The SEQ Manager will meet with the Managing Director once a month to discuss and action
company SEQ matters.
The continuing suitability of the Safety Management System in relation to changing conditions and
information;
All observations, conclusions and recommendations will be documented for necessary action.
The review will take into consideration, but not be limited to:
Incident reports;
Hazard identification;
The Halikos Project Manager will be responsible for the development of a project deliverables register which
outlines all project deliverables required under the contract. The project deliverables register will be
implemented to manage procurement, registration, review and final submission of project deliverables prior
to uploading the web based computer application.
Pending the issue of a full set of contract documents for signature/sealing, the “Contract Issue Documents”
issued by the Client to enable the project to commence shall be reviewed by the Project Manager against the
“Tender” Documents as specified in Procedure PRO-4-52 ‘Project Launch’.
As part of the ‘Project Launch Procedure’ a Contractual Rights and Obligations summary will be undertaken
which is a summary of Client and Contractor obligations and protocols under the contract. Applicable
Contractual time bars are documented to ensure that contractual obligations are understood and executed in
a timely manner.
To ensure all subcontractors engaged by Halikos are not exposed to identified hazards and are free from
risk, requires continual communication and consultation. Halikos is responsible for ensuring all workers
comply with current Legislation, Australian Standards, Codes of Practice and all Halikos Project
Management Strategies for the works performed. Halikos shall achieve this through a close working
relationship and ensuring there is a safe system of work for the task to be undertaken.
All Subcontractors are under the direction of Halikos, and shall participate in full with the Project Quality Plan.
Subcontractor workers are required to adopt the same responsibilities for Halikos workers. All
subcontractors will, in addition, report to the SEQ Compliance Officer, Project Manager, Site Manager,
Foreman and Supervisors for all matters relevant to Quality Assurance and Control on the project. Where the
subcontractor’s supervisor or manager is not physically undertaking work on the project they shall nominate
a Project Quality Management Representative (PQMR) who will be responsible for attending to their workers
issues raised at meetings and the day to day practices of their workers.
All subcontractors shall be required to attend a Project Induction with the Halikos SEQ Compliance Officer to
discuss the specific elements of the Project Plan, hazards and risks, and the rules of the project.
Subcontractors shall also be required to submit (when required) Inspection and Test Plans and be involved
with specific activities that may be planned for the project. The task specific activities shall be determined in
consultation with Project Management. Whilst subcontractors will be required to submit Project Procedures
for particular work they propose to undertake on the project, they should be informed of the following:
Project Management acceptance and/or approval of a subcontractor procedure shall not in any way
remove or limit the subcontractor’s responsibility to provide and maintain as far as is practicable a
working environment that is safe and without risk to the health of workers, products and services
and the project program.
At the start of any project the following process steps will be used to manage subcontractors and ensure
their compliance to work practices.
Compliance will be managed through a review of work performed and scheduled audits to ensure
compliance is maintained with the work scope to be carried out on the project. Subcontractor supervision will
ensure that all workers and sole traders/subcontractors are, or have:
Vehicles & mobile plant that meet Halikos’ and national standard requirements;
All performance will be monitored and managed through project documentation, such as checklists.
Equipment and trained personnel are provided at all organisational levels to carry out the project processes,
verification as well as internal audits to ensure conformance to the project specification.
ACTIVITY ORGANISATION
Architectural Design, review & analysis MKEA
Architectural Documentation MKEA
Building Supervision Halikos Pty Ltd
Progress Payment Certification Halikos Pty Ltd
Project Administration Halikos Pty Ltd
Structural Engineering W&G
Civil Engineering Byrne Design
Electrical Engineering NTBS
Mechanical Engineering Building Services Group
Hydraulic Engineering Building Services Group
Surveying Fyfe
Quantity Surveying N/A
To ensure that staff are competent to perform their assigned tasks, the following systems have been put in
place:
The Halikos “Training” procedure provides guidelines and information to effectively manage identification and
implementation of Quality programs.
Halikos shall ensure that all workers hold a valid General Construction Industry Induction (White Card) and
appropriate licences for the task being conducted prior to commencing works on the Project.
Prior to undertaking work on the project all workers will be required to undertake the Project specific Safety
Induction. The induction will include elements of the PSP, workplace specific hazards, and company policies,
procedures, and rules.
Visitors and workers temporarily on the project to deliver plant, supplies, materials or services must report to
the project office and must receive instructions by the Site Manager or Project Manager. Depending on the
activities of the project at the time of the visit, and the nature of the visit the visitor may be requested to
undertake the project specific induction training detailed above. As a minimum all visitors to the project shall
be shown the emergency instruction sheet.
Any variation to the contract shall be reviewed by the Project Manager in conjunction with other project staff
with appropriate technical knowledge as required. The review is to ensure that technical and quality
requirements are clearly defined and that the project has the necessary resources, organisation and facilities
to perform its obligations under the terms of the variation.
Upon completion of the review, the Project Manager shall sign and date the variation, and ensure distribution
of the amendment to all concerned parties.
Methods of communication include RFI (Request for Information) to Design Consultants and Site
Instructions to subcontractors. Client complaints shall be handled in accordance with the Halikos
“Noncompliance” procedure.
Serial number;
Date;
Code;
Batch number; or
Lot number.
Once a product has been identified (using the above method), the product is then to be placed where the
install of that item will eventually be, provided it does not obstruct any other works.
The responsibility for achieving a safe project design, are with those workers working on a project design and
development. This is achieved through consultation with workers who are directly involved in the design
activity such as architects, engineers, and those who make decisions that influence the design outcome. It is
started by establishing the design scope of the project. The risk management is defined by identifying the
scope of workplace hazards that need to be considered. Establish collaborative relationships with the client
and others who can influence the design outcome. Categorise the risks to be evaluated in areas such as
operational, technical, financial, legal, social, and environmental elements. Develop a safe design framework
for the project, by identifying the steps in the process that need to be taken to ensure that risks are
addressed throughout the course of the project.
Managers involved in design activities should facilitate a design risk assessment with the design consultant
team. All consultants should identify design related hazards associated with the specifications that they
design with relationship to the completed project. The design and consultant team should assess the risks
arising from design-related hazards. All identified issues need to eliminate the hazards and control risks.
During the design concept phase, through the life of the design process, monitoring and review of the design
risk assessment and the risk control measures will continue. Halikos will maintain all records of design risk
workshops, risk assessments, and design meetings. Halikos will consult with all workers and consultants on
the project, and will provide significant updated information on the high risk design changes. The design risk
assessment must comply with the hazard and risk management process of this Plan and be referred to for
the standard as part of the process as it is undertaken.
The project designers need to consider risks relating to the construction and through to decommissioning of
a building which can be controlled by assessing them prior to designs and drawings being finalised. Key
design options need to be considered such as planning the disconnection and re-routing services and power
cables before the construction begins which will avoid contact by workers. Investigating and choosing
construction materials that are safe to handle and do not require special tools or resources. Allow for the
designing scope, the construction of temporary and permanent work platforms and stairways to help prevent
falls and other hazards from occurring during the phases of the design. Designing components which
facilitate the pre-fabrication off-site or on the ground to avoid the hazards associated with assembling or
erecting at height. Designers need to provide adequate clearance in the design between the building
footprint and power sources such as overhead power lines, and other electrical components. There must be
allowance for the erecting of construction equipment to be located on site such as cranes and other tall
equipment. It is critical that the design of parapets is to a height that complies with guardrail requirements,
eliminating the need to construct temporary guardrails during the construction. Work at height is considered
a high risk not just during construction, but must be considered for things such as roof maintenance.
Consideration needs to be made, if possible to reducing the space between roof trusses and battens to
reduce the risk of internal falls during roof construction.
The Halikos designer team and consultants will keep a record of the risks identified during the design
process and the steps taken to eliminate or minimise the risks. Records should be kept of new information
relating to all design modifications. The construction phase involves ensuring those records of risks are
available and reviewed by the project team. The design plans are a crucial document for Project Managers to
rely on for accuracy and ensuring that key project staff is following correct design plans. Monitoring and
evaluating the design risk controls is to be a regular activity of the project management team which done as
part of design meetings. Communication between the project management team and designers should
confirm the effectiveness of risk controls in the design. Hazard identification during the construction phase,
especially the identification of new hazards and risks encountered that were not previously known to the
designers should be communicated back for the improvement of the process. This process can be picked up
during toolbox meetings, safety compliance checks, and reported hazards from workers.
All key Halikos and project stakeholders must assess all design change for potential risk. If there are no new
risks, that can be the end of the risk assessment process. If there are new risks identified, then Halikos’ risk
management process and procedure will be implemented.
Whenever a key Halikos or project stakeholder determines that some safety aspect of the project should be
changed, then that stakeholder is to submit a change proposal to the project design team. The change
proposal should identify the work process in question, describe the aspect of the work process that the
stakeholder wishes to change, and include a description of the Workplace Health and Safety impact of the
proposed change.
The design change proposal should be circulated to all key Halikos and project stakeholders who the
applicant has identified as being affected by the proposed design change. The design team will consider
circulating proposed changes with any other stakeholders for consultation. There will be involvement with the
project Workplace Health and Safety team on the possible Workplace Health and Safety effects of
implementing the proposed changes.
Once the impact of the proposed change or changes has been assessed by all of relevant project
stakeholders, the project design management team should decide whether to recommend the acceptance or
rejection of the proposed change. The project design team may reject a proposed change if it is determined
that there are significant Workplace Health and Safety risks to project workers, construction workers,
maintenance workers or the end facility users and occupiers. The approval or rejection of a design change
will be done through the project design team meeting.
The completion phase of a project will involve conducting a risk assessment for the safe receipt of the
completed project ready for handover to the client. The safe transfer of the completed project to the client will
be part of the completion and handover process. The communication of the residual risks and all risk control
measures that are implemented for the safety of users to the client.
Design will be performed by external Consultants as per the Halikos “Design Management” procedure.
Project Plans and procedures are updated as necessary as the design proceeds.
Additionally Halikos will endeavour to use local subcontractors and suppliers wherever possible, refer to the
project “Industry Participation Plan (IPP)”.
All purchased products (including subcontracted works) shall be subject to verification to ensure
conformance to contractual requirements.
The Project Manager shall review all purchase documents prior to approval and release. Halikos Position
Descriptions detail purchasing authority levels and responsibilities.
Halikos may arrange for offsite Inspectors to conduct inspection and verification activities at subcontractor’s
premises as required. The verification arrangements and the method of release shall be specified in the
purchasing documents.
Qualification of personnel, equipment and procedures for these processes shall be in accordance with the
applicable Standards, Specification and Codes. Records of qualified processes, procedures, personnel and
equipment will be maintained in accordance with Halikos documented procedures.
Product conformance will be determined by acceptance criteria laid down in the specifications and Inspection
and Test Plans.
During inspection and testing, any nonconforming product/process detected shall be identified, document
and segregated (where possible) in accordance with the Halikos “Compliance Control” procedure.
All manufactured/constructed items shall undergo final inspection and testing in accordance with specified
contractual requirements prior to release to the client. No manufactured/constructed items shall be offered to
the client until all the activities specified in the Project Quality Plan or documentation procedures and
instructions have been satisfactorily completed.
All Laboratory testing is to be conducted by National Association of Testing Authorities (NATA) certified
organisations as defined in T14-2305 Tender Documentation.
For this project the following inspection, measuring and test equipment shall be subject to calibration:
The PQMR shall verify all test results and maintain calibration records on the project file.
Any equipment identified as having doubtful accuracy or precision shall be removed from use and calibrated.
Where any inspection, measuring and test equipment is found to be out of calibration, the validity of the
previous inspection results will be assessed and documented.
A documented Halikos procedure (PRO-4-02 Document and Data Control Procedure) has been established
to define the controls needed to:
With the above in mind, the Halikos “Internal Audit Procedure” provides guidelines to effectively assess
project compliance against internal and external legislative requirements and identify causes of
project/system failures to promote proactive management of quality that result in continuous improvement
opportunities.
The nominated PQMR will implement the audit programme, schedule audit dates, and confirm names of the
audit team participants.
Project Quality Audits will be carried out at intervals defined in the Halikos audit schedule and will review
specific sections of the PQP to provide verification of the implementation, effectiveness and possible
recommendations for further improvement. The Audit Schedule is defined at Appendix 6 to this document.
The results of all audits shall be documented and Noncompliance Reports will be raised for deficiencies
identified and brought to the attention of the Project Manager for follow up action.
Following satisfactory rectification of the noncompliance and the identification and implementation of
corrective actions to prevent reoccurrence, the responsible person shall provide a completed copy of the
report to the auditor.
Where contractually required, concessions or waivers shall be sought from the client for the proposed use of
the product, which does not conform to specified requirements. All nonconformity shall be documented and
a register is maintained by the PQMR to monitor the status of the non-conformances.
All products identified to be ‘Nonconforming’ shall be recorded on FRM-6-20 and isolated to ensure the
product is not used or installed inadvertently. Once FRM-6-20 is populated, the details of the noncompliance
are recorded on REG-7-24 within 24 hours (one working day). All products deemed to be Nonconforming
shall be identified to the Project Manager who has the overall authority and responsibility for remedial action
to be undertaken.
If amendment, variation or extension of time will result from the proposed remedial action, the Project
Manager will submit the Noncompliance report with the proposed remedial action to the Superintendent for
approval. Such a noncompliance constitutes a Hold Point and is to be noted on the ITP accordingly.
In the event of the Superintendent observing defective work or a defect in the quality system, Halikos will be
advised in writing. Within one ordinary working day of receipt of the advice, the Contractor shall raise a
noncompliance report and action it in accordance with Clause 7.4.13 of the Tender Documentation
Defects identified during the defects liability period will be documented and resolved in accordance with
Halikos procedures.
Statistical information will be analysed and reported to all Halikos workers, project subcontractors and other
interested parties. The Project Manager will review project statistics regularly.
Corrective and/or preventative actions taken to eliminate the causes of actual or potential nonconformity
shall be in accordance with the documented procedure. The action taken shall be to a degree appropriate to
the magnitude of problems and the risks encountered.
16.0 DEFINITIONS
Client - Department of Infrastructure, Construction Division.
Subcontractor - Any company or person who is contracted to Halikos Pty Ltd for the purpose of supplying
goods or services.
Consultant - The architectural and engineering consultants who have been engaged by Halikos Pty Ltd to
perform the design, preparation of detailed ‘For Construction’ documentation and necessary certification to
meet contractual requirements.
Project Quality Plan (PQP) - A document that describes how the work under the contract will be performed
and controlled, i.e. this document.
Procedure - A document which describes the method for undertaking a certain activity.
Inspection and Test Plan (ITP) - A document which describes what checks for compliance for a particular
process or activity are to be made.
Hold Point - A point in the construction or verification process beyond which work must not proceed without
the written approval of a designated person or authority.
Witness Point - A point in the construction or verification process at which an activity is to be observed.
1
Company Policies
Number Issue Name Reviewed Number Issue Name Reviewed
POL-1- Occupational Health & POL-1-
1 Apr-14 Free
01 Safety Policy 12
POL-1- POL-1-
1 Environmental Policy Apr-14 Free
02 13
POL-1- POL-1-
1 Quality Policy Apr-14 1 Personal Leave Policy Jun-11
03 14
POL-1- Workplace Violence POL-1-
1 Nov-12 Free
04 Policy 15
POL-1- Drugs & Alcohol POL-1-
1 Nov-12 1 Motor Vehicle Policy Jan-12
05 Policy 16
POL-1- POL-1-
1 Rehabilitation Policy Nov-12 1 Personal Leave Policy Aug-10
06 17
POL-1- Equal Employment POL-1-
1 Nov-12 Free
07 Opportunity Policy 18
POL-1- POL-1-
1 Sustainability Policy Mar-12 Free
08 19
POL-1- POL-1-
Free 1 Cash Holding Tills Jul-11
09 20
POL-1- POL-1- Contracts Agreements
Free 1 Jul-11
10 21 Leases Policy
POL-1- POL-1-
Free Free
11 22
2
Company Manuals
Number Issue Name Reviewed Number Issue Name Reviewed
Free Free
Free Free
3
Project Plans
Number Issue Name Reviewed Number Issue Name Reviewed
PMP-3- Project Health and PMP-3-
1 Dec-14 Free
01 Safety Plan 22
PMP-3- PMP-3- Industry Participation
Free 1 Dec-14
02 23 Plan
PMP-3- Project Environmental PMP-3- Project Training and
1 Dec-14 1 Dec-14
03 Management Plan 24 Education Plan
PMP-3- PMP-3-
1 Project Quality Plan Dec-14 Free
04 25
PMP-3- Project Emergency PMP-3-
1 Dec-14 Free
05 Response Plan 26
PMP-3- Cyclone Management PMP-3-
1 Dec-14 Free
06 Plan 27
PMP-3- PMP-3-
Free Free
07 28
PMP-3- Project Risk PMP-3-
1 Dec-14 Free
08 Management Plan 29
PMP-3- PMP-3-
Free Free
09 30
PMP-3- PMP-3-
Free Free
10 31
PMP-3- PMP-3- Indigenous
Free 1 Mar -15
11 32 Development Plan
PMP-3- PMP-3-
Free Free
12 33
PMP-3- PMP-3-
Free Free
13 34
PMP-3- PMP-3-
Free Free
14 35
PMP-3- PMP-3-
Free Free
15 36
PMP-3- PMP-3-
Free Free
16 37
PMP-3- PMP-3-
Free Free
17 38
PMP-3- PMP-3-
Free Free
18 39
PMP-3- PMP-3-
Free Free
19 40
PMP-3- PMP-3-
Free Free
20 41
PMP-3- PMP-3-
Free Free
21 42
4Procedures
4Procedures
REG-7- CL-7-
Emergency Response
Objectives and Dec-14 and First Aid Dec-14
12 12
3 Targets Matrix 1 Assessment Checklist
REG-7- CL-7-
1 Equipment Register Dec-14
13 13
REG-7- CL-7-
1 Scaffold Register Dec-14
14 14
REG-7- CL-7-
1 Calibration Regitister Dec-14
15 15
REG-7-16 1 PPE Register Dec-14
REG-7-17 1 Noise Register Dec-14
REG-7-18 1 Rain Gauge Register Dec-14
Internal Audit
Dec-14
REG-7-19 1 Schedule
REG-7-20 1 Training Matrix Dec-14
Training Participation Dec-14
REG-7-21 1 Register
REG-7-22 1 Mobile Plant Register Dec-14
WorkSafe Visit
Dec-14
REG-7-23 1 Register
REG-7-24 1 Action Register Dec-14
REG-7-25 1 LOTO Register Dec-14
REG-7-26 6 Project Risk Register Dec-14
Key 2: S/C – Subcontractor HA – Halikos Site QA Rep C – Client Site QA Rep BC – Building Certifier
ALL ITP’s ARE TO BE SIGNED AND DATED ON THE ATTACHED ITP SIGN-OFF SCHEDULE
1)What is Jira?
● Jira is a tool to help your team manage work.
3)What is a Project?
● A project is a collection of issues
4)What is a Board?
● A board is a visual display of work progress, often with 3-4 columns.
5)What is a workflow?
● A workflow is the path of statuses an issue will go through from start to finish.
An example of a simple workflow is an issue moving from To Do to In Progress to
Done.
2
6)What is a epic?
● An epic is a large initiative. Known as "parent" issues, epics contain smaller
issues within them. They often represent large bodies of work that can break
down into smaller tasks. It will be up to you and your team to decide what's a
large initiative and what's not.
7)What is a task?
● A task is the most common issue type. They contain a more detailed
description of a work item. Tasks can exist within a larger epic or exist all on their
own.
8)What is a story?
9)What is a subtask?
A subtask is a further defined issue, used to break down tasks, stories, or bugs into
smaller work items. Subtasks must have a parent issue type. They cannot exist on their
own.
STAR POINT - Boards sit within projects. A single Jira project can have several boards. A
board is often named after a larger deliverable or team of people.
3
Kanban boards
● Kanban boards are used by all types of teams. They illustrate a continuous flow
of work. Issues continuously move in and out of the board from the start of the
project until the end of the project.
Scrum boards
● Scrum boards are mostly used by agile software development teams. Scrum
boards bring in groups of issues that the team will attempt to complete during a
fixed period of time, often a two-week "sprint."
References
1) https://university.atlassian.com/student/collection/850385/path/1083901/activi
ty/1080730
2) KDTells ~ Confluence Certification Path – IT Quality Den (wordpress.com)
21 + Yrs of Exp: Senior IT Consultant |CTL Prime QA & Testing and App Support Management, Delivery Management International Exposure
(On-Site): Cyprus (TSYS – 07-08), Jamaica (NCBJ 17-18, 21-22), and UAE (UNB- 18), India (ICICI- 22-23), Philippines (Aug 23- Till Date)
NOTEWORTHY HIGHLIGHTS
Industrial Credit and Investment Corporation of India (ICICI) Bank (May’ 22 – Jul’ 23)
✓ Ownership TS-Prime App-Support (Consultant)
✓ Ownership of working closely with ICICI Internal stakeholders and Vendor (TSYS)
✓ Ownership of Prime 4 tickets and co-ordination with vendor (TSYS) and internal teams
✓ Ownership to validate fix(s) provided by vendor (TSYS) in UAT and ensuring timely deployments on Production
✓ Ownership to offer support for critical incidents to internal (ICICI) teams and Vendor (TSYS) teams
National Commercial Bank of Jamaica (May’ 17-Mar’ 18, Mar’ 21-Mar’ 22)
✓ Amex and Discovery Payment Gateways
✓ Payment Facilitator
✓ Auto Settlement
✓ M-PoS Contactless
✓ Minimum Payment Alerts
✓ Chargeback Automation & Transactions Alerts
Synopsis: The BFSI project aimed at developing & testing Payment Systems like AMEX, MasterCard, and VISA issues mandates,
TSYS updates its products and provides updated versions to Client. TSYS applied these updates for its clients.
✓ TS – PRIME
ONSITE EXPEREINCE
➢ ICICI Bank, Hyderabad India – May’22 till Date
➢ National Commercial Bank, Kingston Jamaica as Consultant - Software Testing and Quality Analyst, Jul' 17-Feb' 18 & May' 21-Till Date
➢ Union National Bank, Abu Dhabi as Technical Advisor, Mar' 18-Oct' 18
➢ TSYS International, Jul' 08-Sep' 08 – Cyprus Nicosia
ORGANIZATIONAL EXPERIENCE
➢ SR intelligent Technologies May’22 – Till Date
➢ TSYS International as Sr. Test Lead - BFSI, May' 08-Mar' 12
➢ Steria (Formally XANSA India) as Test Analyst, May' 06-May' 08
➢ A1 Technology Pvt. Ltd., Delhi as Senior Test Engineer, Sep' 03-May' 06
➢ Treasury and Accounts Department Government of Haryana, Sep' 01-May' 03
Table of Contents
1. Introduction 3
2. Scope 3
3. Test Objective 4
4. Reference Document 4
Test Strategy
Test Schdeule
Test Resources
Pass/Fail Criteria:
Environment
Exit Criteria
1. Introduction
The Test Plan outlines the scope, approach, resources, and schedule of all testing
activities. It identifes the items and features to be tested; types of testing. It contains a
detailed and executable strategy for conducting. It defnes the detailed testing objective
specifc to a particular system, the testing approach, test environment, test conditions, and
the test plan.
2. Scope
The scope of this test plan is to ensure websiteX meets all of its technical, functional and
business requirements. The purpose of this document is to describe the overall test plan
and strategy for testing the website. The approach described in this document provides the
framework for all the testing related to website. This document will also be updated as
required with the requirement updates. We also need to make sure that all the expected
results are achieved.
3. Test Objectives
The general test objectives are to test the correctness of the generation of the
interface data fle, the content of the interface data fle, and any error conditions. The
quality objectives of testing the website are to ensure complete validation of the
business and software requirements:
Reference Documents
—--------
Requirement Analysis
Design Testing
Functionality Testing
Verify each functionlaity of the system is working as per requirement
Testing the links
Testing the forms
Cookies Testing
Validation (HTML/CSS/PHP)
Database Testing
Integration Test Specifcation
API Testing
Usability Testing
Compatibility Testing
Browser Compatibility
OS compatibility
Mobile browsing
Performance Testing
Load Testing
Stress Testing
Security Testing
Automation Testing
Smoke Testing
Beta Testing
Make sure the major scenarios and requirements are mentioned in the document. If there
is something missing, highlight the missing requiremnts and also suggest improvements if
there is any.
—-----------
And also make sure the designs for all the specifed languages and dark themes.
search engines.
Comp
5.4. API Testing
Set of procedures to verify the expected functionality, reliability, and security and ensure
the correct interaction between backend and frontend. To validate the logic of the build
architecture within a short amount of time. Each api test consists of some test actions
mentioned below. Further details of API Testing will be covered in API Test Plan
To determine design inconsistencies and usability problem areas within the user
interface and content areas.
Potential sources of error may include:
Navigation errors – failure to locate functions, excessive keystrokes to
complete a function, failure to follow recommended screen fow.
Presentation errors – failure to locate and properly act upon desired
information in screens, selection errors due to labeling ambiguities.
Control usage problems – improper toolbar or entry feld usage.
Exercise the application or web site under controlled test conditions with representative
users. Data will be used to access whether usability goals regarding an effective,
effcient, and well-received user interface have been achieved.
Establish baseline user performance and user-satisfaction levels of the use interface for
future usability evaluations.
Basic Usability:
The site should have a clear hierarchy.
Headings clearly indicate the structure of the document
Navigation should be easy to understand
Navigation is consistent throughout the site
The site uses underlined links
The site uses consistent and appropriate language
The site has easy to fnd sitemap and contact page
The site has a search tool
The site has a link to home page on every page
The site has clearly defned visited links
5.7.2 OS compatibility:
Some functionality in the web application may not be compatible with all operating
systems. All new technologies used in web development like graphics designs, interface
calls like different API’s may not be available in all Operating Systems. Testing the web
application on different operating systems like Windows, Unix, MAC, Linux, Solaris with
different OS favors.
Accept-Language
SESSION_ID/Device ID
Signature
User-Agent
Furthermore we will use Zap for security testing. It is an end-to-end web application
security scanner. This will give us a 360-degree view of the security of our website. It
is important to have an understanding of how the client (browser) and the server
communicate using HTTP. the tester should at least know the basics of SQL injection
and XSS.
Automation Testing:
Smoke testing will be performed at two stages. Once new features are added, the other is
before fnalizing the build for Production/live.
Beta testing is the fnal round of testing before releasing a product to a wide audience. The
objective is to uncover as many bugs or usability issues as possible in this controlled
setting. QA will also a perfrom the beta Testing.
6. Test Strategy
The overall strategy of this testing initiative is manual, black box testing. We are
testing the data, interface part and mplemented system in detail. The testing at the
SAP end of the interface will be covered by the SAP functional testing. Follow the
testing phases and techniques mentioned inside “Detailed Test Approach”. All type
of testing are covered in this document.
Some of the test specifcations use test data which needs to be set-up in the test
environment prior to executing the test cases.
For each level of testing, a separate test plan is prepared with the following set of
deliverables:
Test Schdeule
The test schedule is the timeline of acceptance testing activities and deliverable dates.
Requirement Analysis.
Design Testing
Develop test scenarios
Develop test cases
Review scenarios/test cases for accuracy, completeness and sequence (confrm
test data is correct)
Integration testing
API Testing
Regression Testing
Functionality Testing
Database Testing
Integration Test Specifcation
Usability Testing
Compatibility Testing
Performance Testing
Security Testing
UAT Testing
Automation Testing
Smoke Testing
Beta Testing
Severity 1 - Crash or High impact problems that often prevent a user/host from correctly
completing an experience/booking.
Severity 3 - Either moderate problems with low frequency or low problems with moderate
frequency; these are minor annoyance problems faced by a number of participants.
Severity 4 - Low impact problems faced by few participants; there is low risk of not
resolving these problems. Reward for resolution is typically exhibited in increased user
satisfaction.
9. Test Resources
Here is the list of resources with the roles those will work on website
1.
2.
11. Environment
Start testing on a staging server once a certain level is achieved, then move to Production
and give the fnal approval at Production. All the experiments should be performed at
staging. Testing data must be private at Production.
12. Test Cases and Test Scenarios
Write down the detailed test cases on the basis of requirement, technical doecument and test
plan. For testcases use the Google sheet and use the Jira for bug, suggestion reporting.
Jira wil be used for defect reporting and issue bugs/defects management and
traceability.
completed.
I started my career as a Testing Executive 4.5 years back with Infosys currently I am working as Test
Engineer.
My responsibility is to understand Business Requirement Specification and High-Level scenarios and to
convert them into test cases & Automation scripts if required.
Execution of test cases and reporting of defect to the developer if there any and get them fixed.
I have experience on Functional, Automation, Regression, Smoke, Sanity, Web accessibility, Web
Analytics, Mobile Testing.
In my previous project I have worked on Automation testing where we have used Selenium with java and
TestNG Cucumber framework for BDD approach. We have used Page object model where we have
separated our test cases with page objects, and we performed testing on the same. For build
management tool we are using Maven for version controlling we are using Git and for automating our
jobs for nightly run or any schedule we are using Jenkins,.
For defect management & test case management we have used JIRA, TEST RAIL & HP ALM.
I have worked on tools like BrowseStack, DeviceAnywhere, Toadsql,
I am working on Agile environment we have daily standup call and we have 2-week sprint cycle. I am part
of 8-member team out of which we are 3-Tester, 2- dev, 1- manager, 1-scrum master.
First thing I do after login in my system. I check the active sprint in Jira for our project code. There I can
see my assigned open tasks. After that I will check my mail if there is any important mail I need to take
action on. Then we have our daily scrum meeting where we used to tell our previous day actions what we
did, what we are planning for today and if we have any blocker to discuss. Product owner and scrum
master help us to resolve that blocker. After that I need to take the pending task and do needed action
whether creating test case, Execution, Defect retesting if any.
• Do you have created framework from scratch, or you have maintained that?
I have not created Framework from scratch by myself but yes, I was part of framework creation and
created some part of it.
• Can you tell me Oops concepts and relate it with your Framework?
We have Polymorphism, Inheritance, Encapsulation and Abstraction in Oops. So, we will start with
1) DATA ABSTRACTION
Data Abstraction means to handle complexity by hiding unnecessary details from the user. In java,
abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using
interfaces.
In Selenium, WebDriver itself acts as an interface. Consider the below statement:
WebDriver driver = new ChromeDriver();
We initialize the Chrome Browser using Selenium Webdriver. It means we are creating a reference
variable (driver) of the interface (WebDriver) and creating an Object. Here WebDriver is an Interface and
ChromeDriver is a class.
We can apply Data Abstraction in a Selenium framework by using the Page Object Model design pattern.
We define all our locators and their methods in the page class. We can use these locators in our tests but
we cannot see the implementation of their underlying methods. So we only show the locators in the tests
but hide the implementation. This is a simple example of how we can use Data Abstraction in our
Automation Framework.
2) ENCAPSULATION
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together code and the data it manipulates. Encapsulation can be achieved by: Declaring all the variables in
the class as private and writing public methods in the class to set and get the values of variables.
All the classes in an Automation Framework are an example of Encapsulation. In Page Object Model
classes, we declare the data members using @FindBy and initialization of data members will be done
using Constructor to utilize those in methods.
3) INHERITANCE
Inheritance is the mechanism in java by which one class is allowed to inherit the features (fields and
methods) of another class.
We can apply Inheritance in our Automation Framework by creating a Base Class to initialize the
WebDriver interface, browsers, waits, reports, logging, etc. and then we can extend this Base Class and its
methods in other classes like Tests or Utilities. This is a simple example of how we can apply Inheritance in
our framework.
4) POLYMORPHISM
Polymorphism allows us to perform a single action in different ways. In Java polymorphism can be
achieved by two ways:
– Method Overloading: When there are multiple methods with same name but different parameters then
these methods are said to be overloaded. Methods can be overloaded by change in number of
arguments or/and change in type of arguments.
In Selenium Automation, Implicit wait is an example of Method Overloading. In Implicit wait we use
different time stamps such as SECONDS, MINUTES, HOURS etc.
– Method Overriding: It occurs when a derived class has a definition for one of the member functions of
the base class. That base function is said to be overridden.
In Selenium Automation, Method Overriding can be achieved by overriding any WebDriver method. For
example, we can override the findElement method
In assertion we have used overload because in assertion we used to like asset.true(actual, expected) and
second time we can use same assert.true(actual, expected, message).
• How can you use interface and how it is different from Abstract class?
Abstract class may have Abstract and concrete methods, and there is not any compulsion in adding
abstract method in abstract class. But in Interface, we do have only abstract methods and we don’t need
to write abstract keyword in Interface this is by default public and abstract.
• What do you mean by Static keyword in Java?
Static means it is at class level not at instance level, we have static method, static variable & static inner
class. When we have any variable as static so it will remain same for all the instance of our classes, and
static/Private/Final methods can’t be over-ridden like if we have initialized any method as Static so we
cannot override it in any child class.
• What do you mean by wrapper class and how will you do data conversion?
Wrapper class in java are used for data conversion. In data conversion if user wants to convert Int to
string, String to int, Boolean, double then we use Wrapper class.
integer.parseInt(); - To convert string to Integer
Double.parseDouble(); - To convert string to Double
Boolean.parse Boolean(); - To convert string to Boolean
String.valueof(); - To convert Integer to String.
• Can you tell me about difference between Throw and Throws keyword?
Throw is a keyword used inside a body of function. And Throws used while initializing any method. By
using Throw we can throw only one exception while for Throws we can declare multiple exceptions which
might occur in that particular function. Throws keyword followed by instance name and Throw keyword is
followed by class name of that exception.
• How much you rate yourself in selenium out of 5?
Out of 5 I will rate myself 3.5 in selenium.
• Can you tell me how you will handle multiple window in selenium.
We have windowhandle & windowhandles function for handling Multiple windows. Windowhandle will
give the string value of only the active window that is open whereas windowhandles will give set of all the
windows that are open in browser.
• Do you work in cucumber, can you tell me what all files required in cucumber?
In cucumber we have Feature file, Step Definition file and Test Runner file.
In feature file we used to write scenario in gherkin language which is most like in plain English language.
Here we use some of the keywords like feature, scenario, scenario outline, given, when, then, and,
example, background keywords for writing our test scenarios steps.
In Step Definition file we write mapping code for all the scenario of feature file.
In test Runner file we provide the address of the feature file, step definition file, and all-important Tags,
Plugin, Listeners in that.
• Can you tell me how you will re-run failed scenario in cucumber?
For that we can use re-run attribute in our test runner file. After that we can write one file location.
Where all the test cases which failed while execution get stored. So next time while running execution we
can give this file location and run the failed TC.
• You have worked in Cucumber & TestNG according to you which one is best?
I will consider Cucumber as it is most likely understood by Laymen people which is English plain language.
Because in order to understand the functionality flow no need to go look and script/code. Via Scenario
steps lines only we can get clear understanding about the functionality.
It helps to come all the QA members Dev, Client, Product Owner on same page.
• Have you used GIT in your project can you explain about it?
Yes I have used GIT, It is a version control tool. Where we can maintain our central repo. we used to
manage our code via GIT only. We use Git to maintain our project in our local system. So, if someone like
to work on that project I need to send complete update copy to him and after that he can work on that.
There are chances that single project is handled by multiple teams across the globe. So, it will be difficult
if we won’t use GIT.
• Can you give me some GIT commands which you used on daily basis?
Git status- which shows status of all the files,if we have some files which is not yet added to our repo so it
will give us untracked file.
After that we can use GIT add command after adding it will added to particular index and we can commit
this file using Git Commit-(Message) we can commit this untracked file. Also we have Git Merge, Git Post,
Git Pull, Git It in etc.
• You have worked in Jenkins can you tell me how you have created jobs in Jenkins?
We have separate Dev-Ops Team to create Jenkins jobs at broad level but we also have access to jenkins,
so we have created jobs for our internal purpose.
For creating any job we have click on create new job->inside that give name of your job->select freestyle
project->then add. Beside that we can provide description of our project and in source code management
we can choose Git-> provide repo url ->after that provide some schedule if you want to run the job on any
specific schedule time.-> select window batch command-file location-save-click on build now for running.
After triggering we can check log in console.
Java main() method is always static, so that compiler can call it without the creation of an object or before
the creation of an object of the class. ... Static method of a class can be called by using the class name only
without creating an object of a class.
Run-Time Polymorphism: Whenever an object is bound with the functionality at run time, this is known
as runtime polymorphism. The runtime polymorphism can be achieved by method overriding. Java
virtual machine determines the proper method to call at the runtime, not at the compile time.
The main difference between List and Set is that Set is unordered and contains different elements,
whereas the list is ordered and can contain the same elements in it.
Method overriding is used to provide the specific implementation of the method that is already
provided by its super class. Method overloading is performed within class. Method overriding occurs in
two classes that have IS-A (inheritance) relationship. In case of method overloading, parameter must be
different.
• Use of constructor.
The purpose of constructor is to initialize the object of a class while the purpose of a method is to
perform a task by executing java code. Constructors cannot be abstract, final, static and synchronised
while methods can be. Constructors do not have return types while methods do.
• Difference between static and non-static methods
Static method uses complie time binding or early binding. Non-static method uses run time binding or
dynamic binding. A static method cannot be overridden being compile time binding. A non-static
method can be overridden being dynamic binding.
Step 2 − In the next screen, enter the Item name, in this case we have named it Helloworld. Choose the ‘Freestyle project option’
Step 3 − The following screen will come up in which you can specify the details of the job.
Step 4 − We need to specify the location of files which need to be built. In this example, we will assume that a local git
repository(E:\Program) has been setup which contains a ‘HelloWorld.java’ file. Hence scroll down and click on the Git option and enter the
URL of the local git repository.
Note − If you repository if hosted on Github, you can also enter the url of that repository here. In addition to this, you would need to click
on the Add button for the credentials to add a user name and password to the github repository so that the code can be picked up from
the remote repository.
Step 5 − Now go to the Build section and click on Add build step → Execute Windows batch command
Step 6 − In the command window, enter the following commands and then click on the Save button.
Javac HelloWorld.java
Java HelloWorld
Step 7 − Once saved, you can click on the Build Now option to see if you have successfully defined the job.
Step 8 − Once the build is scheduled, it will run. The following Build history section shows that a build is in progress.
Step 9 − Once the build is completed, a status of the build will show if the build was successful or not. In our case, the following build has
been executed successfully. Click on the #1 in the Build history to bring up the details of the build.
Step 10 − Click on the Console Output link to see the details of the build
• Can we declare many interfaces object class inside the interface class.
Yes, you can define a class inside an interface. In general, if the methods of the interface use
this class and if we are not using it anywhere else we will declare a class within an interface.
Selenium Assertions can be of three types: “assert”, “verify”, and ” waitFor”. When an “assert” fails, the
test is aborted. When a “verify” fails, the test will continue execution, logging the failure. A “waitFor”
command waits for some condition to become true.
The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to
access the superclass constructor. The most common use of the super keyword is to eliminate the
confusion between superclasses and subclasses that have methods with the same name.
Break statement resumes the control of the program to the end of loop and made executional flow
outside that loop. Continue statement resumes the control of the program to the next iteration of that
loop enclosing 'continue' and made executional flow inside the loop again
Abstract class can inherit another class using extends keyword and implement
an interface. Interface can inherit only an inteface. Abstract class can be inherited using extends
keyword. Interface can only be implemented using implements keyword.
In the Java programming language, the keyword static indicates that the particular member belongs to a
type itself, rather than to an instance of that type. This means that only one instance of
that static member is created which is shared across all instances of the class.
Using the Actions class in Selenium, we can implement the sendKeys() method to type specific values in
the application. That is how you use the actions class in Selenium with sendKeys() method. ... The
perform() method is used to perform the series of actions that are defined.
unchecked exceptions –
NullPointerException,ArrayIndexOutOfBoundsException,ArithmeticException,IllegalArgumentException
NumberFormatException
• Apart from sendkeys, are there any different ways, to type content onto the editable field?
In non-static method, the method can access static data members and static methods as well as non-
static members and method of another class or same class. Binding process. Static method uses compile
time or early binding. Non-static method uses runtime or dynamic binding. Overriding.
this keyword mainly represents the current instance of a class. On other hand super keyword represents
the current instance of a parent class. this keyword used to call default constructor of the same class.
The length is an instance variable of an array in Java whereas length() is a method of String class
Abstract Classes and Methods Abstract class: is a restricted class that cannot be used to create objects
(to access it, it must be inherited from another class). Abstract method: can only be used in an abstract
class, and it does not have a body. The body is provided by the subclass (inherited from).
Actions is a class that is based on a builder design pattern. This is a user-facing API for emulating complex
user gestures. Whereas Action is an Interface which represents a single user-interaction action.
Using Actions Class: Actions action = new Actions(driver); action. keyDown(Keys. ...
Using SendKeys Chord: driver. findElement(By. ...
Using Robot Class: // Create Robot class Robot rb = new Robot(); // Press control keyboard key rb.
• What is dry run in Cucumber?
Dry-run is used to compile feature files and step definitions in cucumber. It is specially used in the stage
when you will have to see if there are any compilation errors, to check that you can use dry-run. Dry-
run options can either set as true or false.
• Annotations in Cucumber
Total 11 Annotations -Feature, Scenario, Background, given, when , then, and, but, example, scenario
outline, scenario template.
HashMap and HashSet both are one of the most important classes of Java Collection framework.
... HashMap Stores elements in form of key-value pair i.e each element has its corresponding key which is
required for its retrieval during iteration. HashSet stores only objects no such key value pairs maintained.
Maps are used for when you want to associate a key with a value and Lists are an ordered collection. Map is an
interface in the Java Collection Framework and a HashMap is one implementation of the Map
interface. HashMap are efficient for locating a value based on a key and inserting and deleting values based on a
key. HashMap<String, Integer> map = new HashMap<>();
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);
+ map.size());
System.out.println(map);
if (map.containsKey("vishal")) {
Integer a = map.get("vishal");
Option 1: Look for any other attribute which Is not changing every time In that div node like name, class
etc. So If this div node has class attribute then we can write xpath as bellow.
//div[@class='post-body entry-content']/div[1]/form[1]/input[1]
Option 2: We can use absolute xpath (full xpath) where you do not need to give any attribute names In
xpath.
/html/body/div[3]/div[2]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[4]/div[1]/div/div/div/div[1]/div/div/di
v/div[1]/div[2]/div[1]/form[1]/input[1]
Option 3: We can use starts-with function. In this xpath's ID attribute, "post-body-" part remains same
every time. //div[starts-with(@id,'post-body-')]/div[1]/form[1]/input[1]
Option 4: We can use contains function. Same way you can use contains function as
bellow.div[contains(@id,'post-body-')]/div[1]/form[1]/input[1]
The Singleton's purpose is to control object creation, limiting the number of objects to only one. Since
there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just
like static fields. Singletons often control access to resources, such as database connections or sockets.
For example, if you have a license for only one connection for your database or your JDBC driver has trouble
with multithreading, the Singleton makes sure that only one connection is made or that only one thread
can access the connection at a time.
The finally block always executes when the try block exits. This ensures that the finally
block is executed even if an unexpected exception occurs.
maximum one catch block will be executed. No, we can write multiple catch block but only one is
executed at a time.
• java file mai ek hi public class hoti hai, uske alava aur classes v ho sakti hai par public ek hi.
• If we need to create one variable for multiple values, we need to use Array concept.
• Int marks[] = new int[5]
• Array can store only homogenous data, int for int array, string for string,
• If we need to add heterogeneous data in array, we need to create object array.
• Object a[] = new Object[5]; now we can add different data type objects.
• Array is fixed in size, which we define while creating.
• If we try to access index value >= given index value, we got arrayOutOfBundException.
• Arrays are not defined by any data layer structure so we can’t run readymade methods on
it.
• To overcome this, we have collection framework under which there are ArrayList, List,
HashMap, HashTable, Tree, Stack.
• We can add new elements in run time under collections while in array we cannot.
• Collection is a group of objects. To represent this we need certain interfaces and classes.
• Common operations we generally do on collections are adding objects, removing objects &
finding object.
• Collection (I) is called collection interface having methods which are common throughout all
collections.
• Collections is basically a class from java.util package which contains some methods which
we can use for collection objects.
• Collection – 1. List, 2. Set, 3. Queue
• List (I) is child of collection(I). In list Insertion order is preserved and duplicates are allowed.
• ArrayList, LinkedList, Vector these are different classes which implements List Interface.
• Set(I) is child of collection(I). Insertion order is not preserved & duplicates not allowed.
• HashSet, Linked Hashset these are different classes which implements Set Interface.
• Queue(I) is child of collection(I). We used it when we need prior to processing means first in
first out concept.
• priorityQueue is class which implements Set Interface.
• There is one independent interface known as Map(I). In Map(I) objects are created with key
and value pair. Key cannot be duplicate, but Value can be.
• Hashmap, Linked Hashmap, Hash Table these are different classes which implements Map
Interface.
• Whatever methods present in Collection(I) are also present in their child interface i.e List,
Set, Queue.
• add(object o), addAll(Collection c), remove(Object o), removeAll(Collection c),
retainAll(Collection c) these are some methods of Collection Interface.
• clear(), isEmpty(), size(), contains(), conatinsAll(), toArray() are also some methods.
• In List index play an important role because with the help of index only we can find
duplicates elements.
• add(index , object), get(index), set(index, object) are methods of List Interface.
• ArrayList al= new ArrayList(), it allows heterogenous objects also.
• ArrayList<Str> al= new <str>(), now it can store objects of string only.
• Collections.Sort(al) , Collections.Shuffle(al) This will sort & shuffle the objects of arraylist.
• We can read the data with for loop, for each loop, iterator () method.
• JVM have 2 types of memories Static pool -static data, heaps-Non static data,
•
==================================================================================
• Object. with . we can access behavior and properties of that class or any other public class.
• In Polymorphism, we can create many methods with same name, differentiating with input
parameter. Void Walk(){}, void walk(int steps){} . We cannot create duplicate methods or one
method into another.
• Compile time polymorphism, tell which method is called before running it.
• By applying static it means now it became class property not object one and it applicable to all
objects throughout the class.
• Static methods are accessed by class, Non Static methods are accessed by objects.
• Constructor in java is to make objects, we can create constructor but there is one default
constructor in java, like students a = new students(); highlighted is the default constructor.
• Constructor are non static methods. Constructor can be parameterized
• We can create our own constructor like students b= new students(int rollNo ,String name){}
• this() keyword is used to call one constructor by another.
• this() keyword also used in agar 2 alag alag methods mai same parameter name hai , to conflict
na ho isliye this.name, this.rollNo use krte h. this is known as method overloading bcs you are
using one method parameter in second one.
• Inheritance ka matlab hai ki Parent class ki property ko hum child class mai bhi use kar sake.
• e.g class Sci extends students{}, extends keyword ki help se hum students class ki property
ko Sci class mai inherit kr rahe h.
• super() keyword parent class ke constructor ko child mai le ata hai , means ab agar hum Sci
class ka object baneyenge to students class ka v ek object banega.
• this() keyword call current class property, super() keyword call parent class property.
• Java ke andar jitne v by default objects hote hai unke ek parents class hoti hai object.
• Run time polymorphism tell which method is called while running it.
• Public method ka matlab hai hum us method ko ab jis class mai vo bna hai uske bhar bhi access
kr sakte hai uski class ka object bna ke.
• Aur isi point par Encapsulation ka concept v ata hai , hum kisi v method ko kisi v class mai
use kr sakte hai agar vo public hua , par agar hamne usko public na kar to ab vo method apni
class mai Encapsulate ho gya ab usko koi aur use nahi kar skta, ise hi Encapsulation bolte
hai.
• Public, private, protected inko access modifier bolte hai.
• Agar hamne kisi method ko Private bnaya hai to vo bas usi class mai hi use ho skta hai aur
kahi nahi.
• Agar hum chate hai ki parent class ki property bas uske child class ko mile to un
properties/methods ko hum Protected kar dete hai.
• Encapsulation isliye v karte hai bcs hame same kind of variables and method jo kisi ek kam
ke liye specially bne ho unko ek sath le aye. Is se data hiding mai help milti hai and security v
increase hoti hai.
• Aur yahi par getter and setter ka funda ata hai.
• Abstraction iska matlba hai ki hum unnecessary info ko user se hide kre taki usko main
functionality par focus rahe na k internal logic pr.
• e.g ATM withdraw, user ko bas apna pin no cahiye aur kitna paise nikalana hai , uske piche
kya kya process hota hai uska use koi lene dene nahi hai. To jis process ka user ko kuch lena
dena nahi use background mai rakhna ise Abstraction kehte h.
• abstract keyword agar kisi class ke sath lagaya hai to hum uska objects nahi bna sakte.
• Ha bas abstract class ko extend kake hum uske children class mai objects bna skate hai
only override karke.
• Aur agar hum kisi class ko abstract banate hai to hame usme kuch logic dene ki jaroort nahi
hai. Aur ye ek imp property hai abstract method ki.
• Abstract method bannna hai to uski class ko bhi abstract bannna padega.
• Interface methods are by default public and abstract.
• Abstract method ke andar hum concrete functions bna sakte hai , par interface ke andar
kuch nahi bna sakte.
• Interface hame complete Abstraction provide karata hai.
• Interface ko use karne ke liye hum implements keyword use karte h.
• Class-extends-class, class-implements-interface, interface-extends-interface
• Java mai ek class ke multiple parent nahi ho sakte bcs java multiple inheritance support ni
krta. Iske liye hum interface ka use karte hai.
• Tokens in java, Token is known as the smallest unit of your program, the whole java code
you have written is a token.
• Literals means are the string values, integer values, comments, keyword.
COLLECTION FRAMEWORK
•
• Thread Safety-When multiple threads are working on same data, and the value of our data is
changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is
already working on an object and prevent another thread on working on the same object is
known as thread safety. We can achieve Thread safety via Synchronization, Volatile Keyword,
Atomic variable, Final Keyword.
Array List:
• ArrayList<Object Type> ar = new ArrayList<Object Type>();
• ArrayList is Dynamic in nature.
• Virtual Capacity of ArrayList by default is 10 but Physical capacity if we did not add any object is
0. Once we start adding Physical objects Virtual Capacity got decreased by same.
Hashmap:
==================================================================================
• compareTo - The Java String compareTo() method is used for comparing two strings
lexicographically.
• boolean equals() - The java string equals() method compares the two given strings
based on the content of the string (case sensitive)
• String concat() – concat two strings
• boolean equalsIgnoreCase() - The java string equals() method compares the two given
strings based on the content of the string (not casesensitive)
• char charAt() – index position - The java string charAt() method returns a char value at
the given index number.
• boolean contains()
• toUpperCase() – convert to upper case
• toLowerCase() – convert to lower case
• trim() – remove spaces from both sides of string
• substring() -- returns part of string
• boolean endsWith()
• boolean startWith() – ends with specified suffix or not
• int length()
• replace()
• int num = Integer.parseInt(str);- Convert String to int using Integer.parseInt(String)
• int num = Integer.valueOf(str);- Convert String to int using Integer.valueOf(String)
• Convert int to String using String.valueOf()
String int ivar = 123;
String str = String.valueOf(ivar);
System.out.println("String is: "+str);
System.out.println(555+str);
• Convert int to String using Integer.toString()
int ivar = 123;
String str = Integer.toString(ivar);
System.out.println("String is: "+str);
System.out.println(555+str);
• In java, string objects are immutable. Immutable simply means unmodified or
unchangeable.Once string object is created its data or state can't be changed but a new
string object is created.
==================================================================================
Array one line que.
• How will you print length of string without using length method.
String str = “Pankaj”
Sysout(str.toCharArray().length);
Sysout(str.lastIndexOf(“”));
2.
Create a string-> create new stringBuffer and here you can apply reverse fuction.
String str = “Pankaj”;
StringBuffer sf = new StringBuffer(s);
Sysout(sf.reverse());
• isEnabled() to Check Whether the Element is Enabled Or Disabled in the Selenium WebDriver.
•
• findElement(By, by) with sendKeys() to type in the form fields.
•
• findElement(By, by) with getText() to store value of targeted web element.
•
• Submit() to submit a web form.
•
• findElements(By, by) to get the list of web elements.
• List<WebElement> allChoices = dropDown.findElements(By.xpath(".//fruitoption"));
• findElements(By, by) with size() to verify if an element is present.
• Boolean checkIfElementPresent=
driver.findElements(By.xpath("//input[@id='checkbox2']")).size()!= 0;
• pageLoadTimeout(time,unit) to set the time for a page to load
• driver.manage().timeouts().pageLoadTimeout(500, SECONDS);
• implicitlyWait() to set a wait time before searching and locating a web element.
• driver.manage().timeouts().implicitlyWait(1000, TimeUnit.SECONDS);
• untill() from WebdriverWait and visibilityOfElementLocated() from ExpectedConditions to
wait explicitly till an element is visible in the webpage.
• WebDriverWait wait = new WebDriverWait(driver, 10);
• WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated
(By.xpath("//input[@id=’name’]")));
• untill() from WebdriverWait and alertIsPresent() from ExpectedConditions to wait explicitly
till an alert appears.
•
• WebDriverWait wait = new WebDriverWait(driver, 10);
• WebElement element = wait.until(ExpectedConditions.alertIsPresent()
• );
• Select class for selecting and deselecting values from the drop-down in Selenium
WebDriver.
• WebElement mySelectedElement = driver.findElement(By.id("select"));
• Select dropdown= new Select(mySelectedElement);dropdown.selectByVisibleText("Apple");
• navigate() to navigate between the URLs.
• driver.navigate().to("https://www.softwaretestinghelp.com");
• driver.navigate().back();
• driver.navigate().forward();
• getScreenshotAs() to Capture the entire page screenshot in Selenium WebDriver.
• File shot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
• FileUtils.copyFile(shot, new File("D:\\ shot1.jpg"));
• moveToElement() from the Actions class to simulate mouse hover effect.
• Actions actions = new Actions(driver);
• WebElement mouseHover = driver.findElement(By.xpath("//div[@id='mainmenu1']/div"));
• actions.moveToElement(mouseHover);
• actions.perform();
• dragAndDrop() from Actions class to drag an element and drop it on another element.
•
• WebElement sourceLocator = driver.findElement(By.xpath("//*[@id='image1']/a"));
• WebElement destinationLocator = driver.findElement(By.xpath("//*[@id='stage']/li"));
• Actions actions=new Actions(driver);
• actions.dragAndDrop(sourceLocator, destinationLocator).build().perform();
• switchTo() and accept(), dismiss() and sendKeys() methods from Alert class to switch to
popup alerts and handle them.
•
• Alert alert = driver.switchTo().alert();
• alert.sendKeys("This Is Softwaretestinghelp");
• alert.accept()
• getWindowHandle() and getWindowHandles() to handle Multiple Windows in Selenium
WebDriver.
•
• String handle= driver.getWindowHandle();
• Set<String> handle= driver.getWindowHandles();
• for (String handle : driver.getWindowHandles()){
• driver.switchTo().window(handle);
• }
• getConnection() from DriverManager to start Database Connection.
• DriverManager.getConnection(URL, "username", "password" )
• POI to read from the excel files.
• Workbook workbook = WorkbookFactory.create(new FileInputStream(file));
• Sheet sheet = workbook.getSheetAt(0);
• Asserts using assertEquals(),assertNotEquals(), assertTrue() and assertFalse() to compare
the results.
• Assert.assertEquals(message, “This text”);
• Assert.assertNotEquals(message, “This text”);
• Assert.assertTrue(result<0);
• Assert.assertFalse(result<0);
Selenium Notes
1. What is Selenium ?
Limitation of Selenium :
● It doesn’t support windows based applica on directly. However, third party tool (eg: AutoIt) can be
integrated with selenium to automate windows based applica ons.
Note :
1. Selenium community developed specific tool called WINIUM to automate windows based applica ons.
2. Selenium community also developed tools to test mobile applica ons,
● Selendroid - it supports only Android pla orm
● Appium - it supports Android pla orm, MAC, Windows etc.
Note :
All the selenium related resources and documents can be found on the below website.
h p://www.seleniumhq.org
-------------------------------------------------------------------------------------------------------
hence, cross browser tes ng/compa bility tes ng can be performed using selenium.
7. It supports almost all the Opera ng System (MAC, Windows, LINUX etc) and hence,
--------------------------------------------------------------------------------------------------------
● Selenium Core (Developed by a company called Thought Works way back in 2004)
● Selenium IDE (supports only Mozilla Firefox - supports record and playback feature)
● Selenium RC (Remote Control - Version is 1.x) (Used for parallel execu on of automa on scripts on
mul ple remote systems)
● Selenium WebDriver (Version is 2.x and 3.x)
Note :
Selenium WebDriver version 3.x is no longer capable of running Selenium RC directly, rather it does through
emula on and via an interface called WebDriverBackedSelenium.
Selenium Grid :
1. It is one of the component of selenium that is used to run automa on scripts on mul ple system
simultaneously.
2. It is used to carry out compa bility tes ng on mul ple browsers and pla orms.
--------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------
4. Driver Executables
5. Browsers:
Note : To stop auto update of firefox browser version, Make sure to disconnect the internet connec on
and then install 54.0 version, now go to Se ng/Op on in firefox browser and check the below checkbox -
Never check for updates.
https://www.actitime.com/download.php
--------------------------------------------------------------------------------------------------------
OR
1. Since selenium supports multiple languages such as Java, Python, C# etc, we can develop automation
scripts in all the supported languages. This is know as language binding or Client binding.
2. When we execute the selenium code, request goes to the Selenium Standalone Server (also known as
Selenium WebDriver Server), which further process the request based on the input received from the
client binding and perform specific actions on the respective browsers using the browser specific driver
executables,
3. Driver executables uses a protocol called JSON Wire protocol to communicate with related
--------------------------------------------------------------------------------------------------------
NOTE :
All the above men oned interfaces and classes are present in a package called “org.openqa.selenium”.
To view any information about Selenium interfaces, classes and methods, navigate to the below page.
https://github.com/SeleniumHQ/selenium/tree/master/java/client/src/org/openqa/selenium
8. List down all the methods present in below interfaces of Selenium WebDriver.
1. findElement()
2. findElements()
1. close()
2. get()
3. getTitle()
4. getPageSource()
5. getCurrentUrl()
6. getWindowHandle()
7. getWindowHandles()
8. manage()
9. navigate()
10. quit()
11. switchTo()
1. executeScript()
2. executeAsyncScript() - we don’t use this for automation
1. clear()
2. click()
3. getAttribute()
4. getCssValue()
5. getLocation()
6. getRect()
7. getSize()
8. getTagName()
9. getText()
10. isDisplayed()
11. isEnabled()
12. isSelected()
13. sendKeys()
14. submit()
9. Why we upcast the browser related child class to WebDriver, and not RemoteWebDriver class
(RemoteWebDriver being the super most class in selenium) ?
Upcasting Example :
Url - h p://www.seleniumhq.org/projects/webdriver/
-------------------------------------------------------------------------------------------
1. WebDriver is an interface in Selenium that extends the supermost interface called SearchContext.
2. driver is the upcasted object or WebDriver interface reference variable.
3. “ = ” is an assignment operator.
4. new is a keyword using which object of the FirefoxDriver class is created.
5. FirefoxDriver() is the constructor of FirefoxDriver class which ini alises the object and it will also launch
the firefox browser.
-------------------------------------------------------------------------------------------
1. Launch eclipse and go to package explorer [naviga on path :- Window menu → Show View → Package
Explorer]
2. Create a java project [File → New→ Java Project]
3. Right click on Java Project and add a new folder with name “driver” [File → New→ Folder]
4. copy geckodriver.exe file from your system and paste it into this driver folder
5. Similarly, create another folder with name “jar”and copy Selenium Standalone Server.jar file into this jar
folder.
6. Expand the jar folder and right click on Selenium Standalone Server.jar file → select Build Path → select
Add to Build Path
7. As soon as you add any .jar files to build path, a new folder will be available called “Reference Libraries”
under the package explorer sec on and you can see the .jar file is added to this “Reference Libraries”
8. To remove the .jar file from the java build path, go to the Reference Libraries → select the .jar file → right
click → select build path → Remove from build path.
9. Other way of adding .jar file to java build path is : right click on the project → build path → configure build
path → Libraries tab → Add External jars → select the .jar file → Apply → ok
12. This program demonstrates Upcasting concept (FirefoxDriver class object to WebDriver interface) and
accessing various methods of WebDriver interface
package qspiders;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
System.setProperty("webdriver.gecko.driver", ".\\driver\\geckodriver.exe");
driver.get("http://www.google.com");
//Get the title of the google page and print it on the console
//Get the URL of the google page and print it on the console
//Get the source code of the google page and print it on the console
Thread.sleep(2000);
driver.close();
}
Test Lead Basics Manual Testing Sample Interview
Question and Answers prepared by Haradhan Pal
1 What is SDLC?
SDLC or the Software Development Life Cycle is a process that produces software with the
highest quality and lowest cost in the shortest time possible. SDLC provides a well-structured
flow of phases that help an organization to quickly produce high-quality software which is well-
tested and ready for production use.
2 Why SDLC?
Here, are prime reasons why SDLC is important for developing a software system.
• It offers a basis for project planning, scheduling, and estimating
• Provides a framework for a standard set of activities and deliverables
• It is a mechanism for project tracking and control
• Increases visibility of project planning to all involved stakeholders of the development
• process
• Increased and enhance development speed
• Improved client relations
• Helps you to decrease project risk and project management plan overhead
3 SDLC Phases?
The entire SDLC process divided into the following stages:
• Phase 1: Requirement collection and analysis
• Phase 2: Feasibility study:
• Phase 3: Design:
• Phase 4: Coding:
• Phase 5: Testing:
• Phase 6: Installation/Deployment:
• Phase 7: Maintenance:
3.1 Requirements Gathering/Analysis.
This is a process with much communication taking place between stakeholders, end
users and the project team. Meetings with managers, stake holders and users are held
in order to determine the requirements like; who is going to use the system? How will
they use the system? What data should be input into the system? What data should be
output by the system? These are general questions that get answered during a
requirement gathering phase. The QA engineer playing the role to configure the
requirements using requirements traceability matrix (RTM).
3.2 Design:
In this phase the software design is prepared from the requirement
specifications which were studied in the first phase. System Design helps in specifying
hardware and system requirements and also help in defining overall system
architecture. In this phase the QA Engineers comes up with the Test strategy, where they
mention what to test, how to test.
3.3 Implementation / Coding:
Upon receiving system design documents, the work is divided in modules/units and
actual coding is started. Since, in this phase the code is produced so it is the main focus
for the developer. This is the longest phase of SDLC. In this phase the QA Engineers
comes up with the Test Environment setup and test Case Documentation.
3.4 Testing:
After the code is developed it is tested against the requirements to make sure that the
product is actually solving the needs addressed and gathered during the requirements
phase. During this phase all types of like unit testing, integration testing, Smoke Testing,
functional testing, Sanity Testing, system testing, acceptance testing is done as well
as non-functional testing is also done.
3.5 Deployment: After successful testing the product is delivered / deployed to the customer
for their use. As soon as the product is given to the customers, they will first do the beta
testing/User
Spiral Model: The spiral model is a risk-driven process model. This SDLC model helps the team
to adopt elements of one or more process models like a waterfall, incremental, waterfall, etc.
This model adopts the best features of the prototyping model and the waterfall model. The
spiral methodology is a combination of rapid prototyping and concurrency in design and
development activities.
Prototyping Model: Prototyping model is a software development model in which prototype is
built, tested, and reworked until an acceptable prototype is achieved. It also creates base to
produce the final system or software. It works best in scenarios where the project's
requirements are not known in detail. It is an iterative, trial and error method which takes place
between developer and client.
7 What is STLC?
It is the testing process which is executed in systematic and planned manner. In STLC
process, different activities are carried out to improve the quality of the product.
Following steps are involved in Software Testing Life Cycle (STLC).
1. Requirement Analysis (RTM)
2. Test Planning (Test Strategy, Test Plan, Test Bed Creation)
3. Test Case Development (Test Procedures, Test Scenarios, Test Cases)
4. Environment Setup
5. Test Execution
6. Defect Reporting
8 What are Quality Assurance and Quality Control?
Quality Assurance:
Quality Assurance involves in process-oriented activities. It ensures the prevention of
defects in the process used to make Software Application. So the defects don’t arise when
the Software Application is being developed. The process is:
• Plan - Organization should plan and establish the process related objectives and
determine the processes that are required to deliver a high-Quality end product.
• Do - Development and testing of Processes and also "do" changes in the processes
• Check - Monitoring of processes, modify the processes, and check whether it meets the
predetermined objectives
• Act - A Quality Assurance tester should implement actions that are necessary to achieve
improvements in the processes.
Quality Control:
Quality Control involves in product-oriented activities. It executes the program or code to
identify the defects in the Software Application.
In other words, validation is concerned with checking that the system will meet the
customer’s actual needs. validation is an extremely subjective process. Validation
includes activities such as requirements modelling, prototyping and user evaluation.
While verification is concerned with whether the system is well-engineered, error-free,
and so on. Verification will help to determine whether the software is of high quality, but
it will not ensure that the system is useful. Verification includes all the activities associated
with the producing high-quality software: testing, inspection, design analysis,
specification analysis, and so on. It is a relatively objective process.
24 What is RTM?
Requirements Traceability Matrix (RTM) is used to trace the requirements to the tests
that are needed to verify whether the requirements are fulfilled. Requirement
Traceability Matrix AKA Traceability Matrix or Cross Reference Matrix.
Which Parameters to include in Requirement Traceability Matrix?
• Requirement ID
• Requirement Type and Description
• Test Cases with Status
55 What is a Defect?
The variation between the actual results and expected results is known as a defect. If a
developer finds an issue and corrects it by himself in the development phase, then it’s
called a defect.
56 What is an Error?
We can’t compile or run a program due to a coding mistake in a program. If a developer
unable to successfully compile or run a program, then they call it as an error.
57 What is a Failure?
Once the product is deployed and customers find any issues then they call the product
as a failure product. After release, if an end user finds an issue, then that particular issue
is called as a failure.
Describes what the product does Describes how the product works
Affinity Diagram: A group process that takes large amounts of language data, such as a list developed by
brainstorming, and divides it into categories.
Application: A single software product that may or may not fully support a business function.
Audit: This is an inspection/assessment activity that verifies compliance with plans, policies, and procedures,
and ensures that resources are conserved. Audit is a staff function; it serves as the "eyes and ears" of
management.
Backlog: Work waiting to be done; for IT this includes new systems to be developed and enhancements to
existing systems. To be included in the development backlog, the work must have been cost-justified and
approved for development.
Benchmarking: Comparing your company’s products, services, or processes against best practices, or
competitive practices, to help define superior performance of a product, service, or support process.
Black-box Testing: A test technique that focuses on testing the functionality of the program, component, or
application against its specifications without knowledge of how the system is constructed; usually data or
business process driven.
Boundary Value Analysis: A data selection technique in which test data is chosen from the “boundaries” of the
input or output domain classes, data structures, and procedure parameters. Choices often include the actual
minimum and maximum boundary values, the maximum value plus or minus one, and the minimum value plus
or minus one.
Branch Testing: A test method that requires that each possible branch on each decision point be executed at
least once.
Candidate: An individual who has met eligibility requirements for a credential awarded through a certification
program, but who has not yet earned that certification through participation in the required skill and
knowledge assessment instruments.
Cause-Effect Graphing: A tool used to derive test cases from specifications. A graph that relates causes (or
input conditions) to effects is generated. The information in the graph is converted into a decision table where
the columns are the cause-effect combinations. Unique rows represent test cases.
Certification: A voluntary process instituted by a nongovernmental agency by which individual applicants are
recognized for having achieved a measurable level of skill or knowledge. Measurement of the skill or
knowledge makes certification more restrictive than simple registration, but much less restrictive than formal
licensure.
Checklists: A series of probing questions about the completeness and attributes of an application system.
Well-constructed checklists cause evaluation of areas, which are prone to problems. It both limits the scope of
the test and directs the tester to the areas in which there is a high probability of a problem.
https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Checkpoint Review: Held at predefined points in the development process to evaluate whether certain quality
factors (critical success factors) are being adequately addressed in the system being built. Independent experts
for the purpose of identifying problems conduct the reviews as early as possible.
Client: The customer that pays for the product received and receives the benefit from the use of the product.
Coaching: Providing advice and encouragement to an individual or individuals to promote a desired behaviour.
Code Comparison: One version of source or object code is compared to a second version. The objective is to
identify those portions of computer programs that have been changed. The technique is used to identify those
segments of an application program that have been altered as a result of a program change.
Compiler-Based Analysis: Most compilers for programming languages include diagnostics that identify
potential program structure flaws. Many of these diagnostics are warning messages requiring the programmer
to conduct additional investigation to determine whether or not the problem is real. Problems may include
syntax problems, command violations, or variable/data reference problems. These diagnostic messages are a
useful means of detecting program problems, and should be used by the programmer.
Complete Test Set: A test set containing data that causes each element of pre-specified set of Boolean
conditions to be true. In addition, each element of the test set causes at least one condition to be true.
Completeness: The property that all necessary parts of an entity are included. Often, a product is said to be
complete if it has met all requirements.
Complexity-Based Analysis: Based upon applying mathematical graph theory to programs and preliminary
design language specification (PDLs) to determine a unit's complexity. This analysis can be used to measure
and control complexity when maintainability is a desired attribute. It can also be used to estimate test effort
required and identify paths that must be tested.
Compliance Checkers: A parse program looking for violations of company standards. Statements that contain
violations are flagged. Company standards are rules that can be added, changed, and deleted as needed.
Condition Coverage: A white-box testing technique that measures the number of, or percentage of, decision
outcomes covered by the test cases designed. 100% condition coverage would indicate that every possible
outcome of each decision had been executed at least once during testing.
Configuration Management Tools: Tools that are used to keep track of changes made to systems and all
related artifacts. These are also known as version control tools.
Configuration Testing: Testing of an application on all supported hardware and software platforms. This may
include various combinations of hardware types, configuration settings, and software versions.
Consistency: The property of logical coherence among constituent parts. Consistency can also be expressed as
adherence to a given set of rules.
Consistent Condition Set: A set of Boolean conditions such that complete test sets for the conditions uncover
the same errors.
Control Flow Analysis: Based upon graphical representation of the program process. In control flow analysis,
the program graph has nodes, which represent a statement or segment possibly ending in an unresolved
branch. The graph illustrates the flow of program control from one segment to another as illustrated through
branches. The objective of control flow analysis is to determine potential problems in logic branches that
might result in a loop condition or improper processing.
Conversion Testing: Validates the effectiveness of data conversion processes, including field-to field mapping,
and data translation.
https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Correctness: The extent to which software is free from design and coding defects (i.e., faultfree). It is also the
extent to which software meets its specified requirements and user objectives.
Cost of Quality (COQ): Money spent beyond expected production costs (labor, materials, equipment) to
ensure that the product the customer receives is a quality (defect free) product. The Cost of Quality includes
prevention, appraisal, and correction or repair costs.
Coverage-Based Analysis: A metric used to show the logic covered during a test session, providing insight to
the extent of testing. The simplest metric for coverage would be the number of computer statements
executed during the test compared to the total number of statements in the program. To completely test the
program structure, the test data chosen should cause the execution of all paths. Since this is not generally
possible outside of unit test, general metrics have been developed which give a measure of the quality of test
data based on the proximity to this ideal coverage. The metrics should take into consideration the existence of
infeasible paths, which are those paths in the program that have been designed so that no data will cause the
execution of those paths.
Customer: The individual or organization, internal or external to the producing organization that receives the
product.
Data Dictionary: Provides the capability to create test data to test validation for the defined data elements.
The test data generated is based upon the attributes defined for each data element. The test data will check
both the normal variables for each data element as well as abnormal or error conditions for each data
element.
DD (decision-to-decision) path: A path of logical code sequence that begins at a decision statement or an
entry and ends at a decision statement or an exit.
Debugging: The process of analysing and correcting syntactic, logic, and other errors identified during testing.
Decision Coverage: A white-box testing technique that measures the number of, or percentage of, decision
directions executed by the test case designed. 100% decision coverage would indicate that all decision
directions had been executed at least once during testing. Alternatively, each logical path through the program
can be tested. Often, paths through the program are grouped into a finite set of classes, and one path from
each class is tested.
Decision Table: A tool for documenting the unique combinations of conditions and associated results in order
to derive unique test cases for validation testing.
Defect: Operationally, it is useful to work with two definitions of a defect: 1. From the producer's viewpoint a
defect is a product requirement that has not been met or a product attribute possessed by a product or a
function performed by a product that is not in the statement of requirements that define the product; 2. From
the customer's viewpoint a defect is anything that causes customer dissatisfaction, whether in the statement
of requirements or not.
Defect Tracking Tools: Tools for documenting defects as they are found during testing and for tracking their
status through to resolution.
Design Level: The design decomposition of the software item (e.g., system, subsystem, program, or module).
Desk Checking: The most traditional means for analysing a system or a program. Desk checking is conducted
by the developer of a system or program. The process involves reviewing the complete product to ensure that
it is structurally sound and that the standards and requirements have been met. This tool can also be used on
artifacts created during analysis and design.
Driver: Code that sets up an environment and calls a module for test.
https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Dynamic Analysis: Analysis performed by executing the program code. Dynamic analysis executes or simulates
a development phase product, and it detects errors by analysing the response of a product to sets of input
data.
Dynamic Assertion: A dynamic analysis technique that inserts into the program code assertions about the
relationship between program variables. The truth of the assertions is determined as the program executes.
Empowerment: Giving people the knowledge, skills, and authority to act within their area of expertise to do
the work and improve the process.
Entrance Criteria: Required conditions and standards for work product quality that must be present or met for
entry into the next stage of the software development process.
Equivalence Partitioning: The input domain of a system is partitioned into classes of representative values so
that the number of test cases can be limited to one-per-class, which represents the minimum number of test
cases that must be executed.
Error or Defect: 1. A discrepancy between a computed, observed, or measured value or condition and the
true, specified, or theoretically correct value or condition. Human action that results in software containing a
fault (e.g., omission or misinterpretation of user requirements in a software specification, incorrect translation,
or omission of a requirement in the design specification).
Error Guessing: Test data selection technique for picking values that seem likely to cause defects. This
technique is based upon the theory that test cases and test data can be developed based on the intuition and
experience of the tester.
Exhaustive Testing: Executing the program through all possible combinations of values for program variables.
Exit Criteria: Standards for work product quality, which block the promotion of incomplete or defective work
products to subsequent stages of the software development process.
File Comparison: Useful in identifying regression errors. A snapshot of the correct expected results must be
saved so it can be used for later comparison.
Flowchart Pictorial: representations of data flow and computer logic. It is frequently easier to understand and
assess the structure and logic of an application system by developing a flow chart than to attempt to
understand narrative descriptions or verbal explanations. The flowcharts for systems are normally developed
manually, while flowcharts of programs can be produced.
Force Field Analysis: A group technique used to identify both driving and restraining forces that influence a
current situation.
Formal Analysis: Technique that uses rigorous mathematical techniques to analyse the algorithms of a solution
for numerical properties, efficiency, and correctness.
Functional Testing: Application of test data derived from the specified functional requirements without regard
to the final program structure.
Histogram: A graphical description of individually measured values in a data set that is organized according to
the frequency or relative frequency of occurrence. A histogram illustrates the shape of the distribution of
individual values in a data set along with information regarding the average and variation.
Infeasible Path: A sequence of program statements that can never be executed. Inputs Materials, services, or
information needed from suppliers to make a process work, or build a product.
Inspection: A formal assessment of a work product conducted by one or more qualified independent
reviewers to detect defects, violations of development standards, and other problems. Inspections involve
authors only when specific questions concerning deliverables exist. An inspection identifies defects, but does
not attempt to correct them. Authors take corrective actions and arrange follow-up reviews as needed.
https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Instrumentation: The insertion of additional code into a program to collect information about program
behaviour during program execution.
Integration Testing: This test begins after two or more programs or application components have been
successfully unit tested. It is conducted by the development team to validate the technical quality or design of
the application. It is the first level of testing which formally integrates a set of programs that communicate
among themselves via messages or files (a client and its server(s), a string of batch programs, or a set of online
modules within a dialog or conversation.)
Invalid Input: Test data that lays outside the domain of the function the program represents.
Leadership: The ability to lead, including inspiring others in a shared vision of what can be, taking risks, serving
as a role model, reinforcing and rewarding the accomplishments of others, and helping others to act.
Life Cycle Testing: The process of verifying the consistency, completeness, and correctness of software at each
stage of the development life cycle.
Management: A team or individuals who manage(s) resources at any level of the organization.
Mapping: Provides a picture of the use of instructions during the execution of a program. Specifically, it
provides a frequency listing of source code statements showing both the number of times an instruction was
executed and which instructions were not executed. Mapping can be used to optimize source code by
identifying the frequently used instructions. It can also be used to determine unused code, which can
demonstrate code, which has not been tested, code that is infrequently used, or code that is non-entrant.
Mean: A value derived by adding several quantities and dividing the sum by the number of these quantities.
Metric-Based Test Data Generation: The process of generating test sets for structural testing based on use of
complexity or coverage metrics.
Model Animation: It verifies that early models can handle the various types of events found in production
data. This is verified by “running” actual production transactions through the models as if they were
operational systems.
Model Balancing: Model balancing relies on the complementary relationships between the various models
used in structured analysis (event, process, data) to ensure that modelling rules/standards have been
followed; this ensures that these complementary views are consistent and complete.
Mutation Analysis: A method to determine test set thoroughness by measuring the extent to which a test set
can discriminate the program from slight variants (i.e., mutants) of it.
Network Analysers: A tool used to assist in detecting and diagnosing network problems. Outputs Products,
services, or information supplied to meet customer needs. Pass/Fail Criteria Decision rules used to determine
whether a software item or feature passes or fails a test.
Path Expressions: A sequence of edges from the program graph that represents a path through the program.
Path Testing: A test method satisfying the coverage criteria that each logical path through the program be
tested. Often, paths through the program are grouped into a finite set of classes and one path from each class
is tested.
Performance Test: Validates that both the online response time and batch run times meet the defined
performance requirements.
Performance/Timing Analyzer: A tool to measure system performance. Phase (or Stage) Containment A
method of control put in place within each stage of the development process to promote error identification
and resolution so that defects are not propagated downstream to subsequent stages of the development
process. The verification, validation, and testing of work within the stage that it is created. Policy Managerial
desires and intents concerning either process (intended objectives) or products (desired attributes).
https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Population Analysis: Analyses production data to identify, independent from the specifications, the types and
frequency of data that the system will have to process/produce. This verifies that the specs can handle types
and frequency of actual data and can be used to create validation tests.
Procedure: The step-by-step method followed to ensure that standards are met. The work effort that
produces a product. This includes efforts of people and equipment guided by policies, standards, and
procedures. 2. The process or set of processes used by an organization or project to plan, manage, execute,
monitor, control, and improve its software related activities. A set of activities and tasks. A statement of
purpose and an essential set of practices (activities) that address that purpose.
Process Improvement: To change a process to make the process produce a given product faster, more
economically, or of higher quality. Such changes may require the product to be changed. The defect rate must
be maintained or reduced.
Product: The output of a process: the work product. There are three useful classes of products: Manufactured
Products (standard and custom), Administrative/Information Products (invoices, letters, etc.), and Service
Products (physical, intellectual, physiological, and psychological). A statement of requirements defines
products; one or more people working in a process produce them.
Product Improvement: To change the statement of requirements that defines a product to make the product
more satisfying and attractive to the customer (more competitive). Such changes may add to or delete from
the list of attributes and/or the list of functions defining a product. Such changes frequently require the
process to be changed. Note: This process could result in a very new product.
Production Costs: The cost of producing a product. Production costs, as currently reported, consist of (at least)
two parts; actual production or right-the-first time costs (RFT) plus the Cost of Quality (COQ). RFT costs include
labor, materials, and equipment needed to provide the product correctly the first time.
Productivity: The ratio of the output of a process to the input, usually measured in the same units. It is
frequently useful to compare the value added to a product by a process, to the value of the input resources
required (using fair market values for both input and output).
Proof of Correctness: The use of mathematical logic techniques to show that a relationship between program
variables assumed true at program entry implies that another relationship between program variables holds at
program exit.
Quality: A product is a quality product if it is defect free. To the producer, a product is a quality product if it
meets or conforms to the statement of requirements that defines the product. This statement is usually
shortened to: quality means meets requirements. From a customer’s perspective, quality means “fit for use.”
Quality Assurance (QA): The set of support activities (including facilitation, training, measurement, and
analysis) needed to provide adequate confidence that processes are established and continuously improved to
produce products that meet specifications and are fit for use.
Quality Control (QC): The process by which product quality is compared with applicable standards, and the
action taken when nonconformance is detected. Its focus is defect detection and removal. This is a line
function; that is, the performance of these tasks is the responsibility of the people working within the process.
Quality Function Deployment (QFD): A systematic matrix method used to translate customer wants or needs
into product or service characteristics that will have a significant positive impact on meeting customer
demands.
Quality Improvement: To change a production process so that the rate at which defective products (defects)
are produced is reduced. Some process changes may require the product to be changed.
Recovery Test: Evaluates the contingency features built into the application for handling interruptions and for
returning to specific points in the application processing cycle, including checkpoints, backups, restores, and
restarts. This test also assures that disaster recovery is possible.
https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Regression Testing: Testing of a previously verified program or application following program modification for
extension or correction to ensure no new defects have been introduced.
Risk Matrix: Shows the controls within application systems used to reduce the identified risk, and in what
segment of the application those risks exist. One dimension of the matrix is the risk, the second dimension is
the segment of the application system, and within the matrix at the intersections are the controls. For
example, if a risk is “incorrect input” and the systems segment is “data entry,” then the intersection within the
matrix would show the controls designed to reduce the risk of incorrect input during the data entry segment of
the application system.
Run Chart: A graph of data points in chronological order used to illustrate trends or cycles of the characteristic
being measured to suggest an assignable cause rather than random variation.
Self-validating Code: Code that makes an explicit attempt to determine its own correctness and to proceed
accordingly. Simulation Use of an executable model to represent the behaviour of an object. During testing,
the computational hardware, the external environment, and even code segments may be simulated.
Special Test Data: Test data based on input values that are likely to require special handling by the program.
Standardize Procedures that are implemented to ensure that the output of a process is maintained at a desired
level.
Standards: The measure used to evaluate products and identify nonconformance. The basis upon which
adherence to policies is measured.
Statement of Requirements: The exhaustive list of requirements that define a product. Note that the
statement of requirements should document requirements proposed and rejected (including the reason for
the rejection) during the requirement determination process.
Statement Testing: A test method that executes each statement in a program at least once during program
testing. Static
Analysis: Analysis of a program that is performed without executing the program. It may be applied to the
requirements, design, or code. Statistical Process Control The use of statistical techniques and tools to
measure an ongoing process for change or stability.
Stress Testing: This test subjects a system, or components of a system, to varying environmental conditions
that defy normal expectations. For example, high transaction volume, large database size or restart/recovery
circumstances. The intention of stress testing is to identify constraints and to ensure that there are no
performance problems.
Structural Testing: A testing method in which the test data is derived solely from the program structure. Stub
Special code segments that when invoked by a code segment under testing, simulate the behaviour of
designed and specified modules not yet constructed.
Supplier: An individual or organization that supplies inputs needed to generate a product, service, or
information to a customer.
Symbolic Execution: A method of symbolically defining data that forces program paths to be executed. Instead
of executing the program with actual data values, the variable names that hold the input values are used.
Thus, all variable manipulations and decisions are made symbolically. This process is used to verify the
completeness of the structure, as opposed to assessing the functional requirements of the program.
https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
System: One or more software applications that together support a business function.
System Test: During this event, the entire system is tested to verify that all functional, information, structural
and quality requirements have been met. A predetermined combination of tests is designed that, when
executed successfully, satisfy management that the system meets specifications. System testing verifies the
functional quality of the system in addition to all external interfaces, manual procedures, restart and recovery,
and human-computer interfaces. It also verifies that interfaces between the application and the open
environment work correctly, that JCL functions correctly, and that the application functions appropriately with
the Database Management System, Operations environment, and any communications systems.
Test: 1. A set of one or more test cases. 2. A set of one or more test cases and procedures.
Test Case Generator: A software tool that creates test cases from requirements specifications. Cases
generated this way ensure that 100% of the functionality specified is tested.
Test Case Specification: An individual test condition, executed as part of a larger test that contributes to the
test’s objectives. Test cases document the input, expected results, and execution conditions of a given test
item. Test cases are broken down into one or more detailed test scripts and test data conditions for execution.
Test Cycle: Test cases are grouped into manageable (and schedulable) units called test cycles. Grouping is
according to the relation of objectives to one another, timing requirements, and on the best way to expedite
defect detection during the testing event. Often test cycles are linked with execution of a batch process.
Test Data Generator: A software package that creates test transactions for testing application systems and
programs. The type of transactions that can be generated is dependent upon the options available in the test
data generator. With many current generators, the prime advantage is the ability to create a large number of
transactions to volume test application systems.
Test Data Set: Set of input elements used in the testing process.
Test Design Specification: A document that specifies the details of the test approach for a software feature or
a combination of features and identifies the associated tests.
Test Driver: A program that directs the execution of another program against a collection of test data sets.
Usually, the test driver also records and organizes the output generated as the tests are run. Test Harness A
collection of test drivers and test stubs.
Test Incident Report: A document describing any event during the testing process that requires investigation.
Test Item: A software item that is an object of testing. Test Item Transmittal Report A document that identifies
test items and includes status and location information.
Test Log: A chronological record of relevant details about the execution of tests.
Test Plan: A document describing the intended scope, approach, resources, and schedule of testing activities.
It identifies test items, the features to be tested, the testing tasks, the personnel performing each task, and
any risks requiring contingency planning.
Test Procedure: Specification A document specifying a sequence of actions for the execution of a test.
Test Scripts: A tool that specifies an order of actions that should be performed during a test session. The script
also contains expected results. Test scripts may be manually prepared using paper forms, or may be
automated using capture/playback tools or other kinds of automated scripting tools.
Test Stubs: Simulates a called routine so that the calling routine’s functions can be tested. A test harness (or
driver) simulates a calling component or external environment, providing input to the called routine, initiating
the routine, and evaluating or displaying output returned.
Test Suite Manager: A tool that allows testers to organize test scripts by function or other grouping.
https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
Test Summary Report: A document that describes testing activities and results and evaluates the
corresponding test items.
Tracing: A process that follows the flow of computer logic at execution time. Tracing demonstrates the
sequence of instructions or a path followed in accomplishing a given task. The two main types of trace are
tracing instructions in computer programs as they are executed, or tracing the path through a database to
locate predetermined pieces of information.
Unit Test: Testing individual programs, modules, or components to demonstrate that the work package
executes per specification, and validate the design and technical quality of the application. The focus is on
ensuring that the detailed logic within the component is accurate and reliable according to pre-determined
specifications. Testing stubs or drivers may be used to simulate behaviour of interfacing modules.
Usability Test: The purpose of this event is to review the application user interface and other human factors of
the application with the people who will be using the application. This is to ensure that the design (layout and
sequence, etc.) enables the business functions to be executed as easily and intuitively as possible. This review
includes assuring that the user interface adheres to documented User Interface standards, and should be
conducted early in the design stage of development. Ideally, an application prototype is used to walk the client
group through various business scenarios, although paper copies of screens, windows, menus, and reports can
be used.
User Acceptance Test: User Acceptance Testing (UAT) is conducted to ensure that the system meets the needs
of the organization and the end user/customer. It validates that the system will work as intended by the user
in the real world, and is based on real world business scenarios, not system requirements. Essentially, this test
validates that the right system was built.
Valid Input: Test data that lie within the domain of the function represented by the program.
Validation: Determination of the correctness of the final program or software produced from a development
project with respect to the user needs and requirements. Validation is usually accomplished by verifying each
stage of the software development life cycle.
Values (Sociology): The ideals, customs, instructions, etc., of a society toward which the people have an
affective regard. These values may be positive, as cleanliness, freedom, or education, or negative, as cruelty,
crime, or blasphemy. Any object or quality desired as a means or as an end in itself.
Verification: 1. The process of determining whether the products of a given phase of the software
development cycle fulfil the requirements established during the previous phase. 2. The act of reviewing,
inspecting, testing, checking, auditing, or otherwise establishing and documenting whether items, processes,
services, or documents conform to specified requirements.
Vision: A vision is a statement that describes the desired future state of a unit.
Walkthroughs: During a walkthrough, the producer of a product “walks through” or paraphrases the products
content, while a team of other individuals follow along. The team’s job is to ask questions and raise issues
about the product that may lead to defect identification.
White-box Testing: A testing technique that assumes that the path of the logic in a program unit or
component is known. White-box testing usually consists of testing paths, branch by branch, to produce
predictable results. This technique is usually used during tests executed by the development team, such as
Unit or Component testing,
https://www.youtube.com/c/HaradhanAutomationLibrary?sub_confirmation=1
SQL BASICS AND
ADVANCED
INTRODUCTION
SQL is a standard language for accessing databases.
MySQL, SQL Server, Access, Oracle, Sybase, DB2, and other database systems.
SQL Syntax:
SQL Result:
Company Country
Island Trading UK
Galería del gastrónomo Spain
Laughing Bacchus Wine Cellars Canada
Paris spécialités France
Simons bistro Denmark
Wolski Zajazd Poland
What is SQL?
2
RDBMS
SQL BASICS
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers"
or "Orders"). Tables contain records (rows) with data.
Below is an example of a table called "Persons":
The table above contains three records (one for each person) and five columns (P_Id, LastName,
FirstName, Address, and City).
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.
The following SQL statement will select all the records in the "Persons" table:
Note:
• SQL is not case sensitive
• Semicolon after SQL Statements?
• Some database systems require a semicolon at the end of each SQL statement.
• Semicolon is the standard way to separate each SQL statement in database systems that allow
more than one SQL statement to be executed in the same call to the server.
• We are using MS Access and SQL Server 2000 and we do not have to put a semicolon after each
SQL statement, but some database programs force you to use it.
3
SQL DML and DDL
SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition
Language (DDL).
The query and update commands form the DML part of SQL:
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys),
specify links between tables, and impose constraints between tables. The most important DDL statements
in SQL are:
SELECT column_name(s)
FROM table_name
And
SELECT * FROM table_name
4
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Now we want to select the content of the columns named "LastName" and "FirstName" from the table
above.
LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari
SELECT * Example
Now we want to select all the columns from the "Persons" table.
We use the following SELECT statement:
In a table, some of the columns may contain duplicate values. This is not a problem, however,
sometimes you will want to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct (different) values.
5
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Now we want to select only the distinct values from the column named "City" from the table above.
We use the following SELECT statement:
City
Sandnes
Stavanger
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
Now we want to select only the persons living in the city "Sandnes" from the table above.
We use the following SELECT statement:
6
The result-set will look like this:
SQL uses single quotes around text values (most database systems will also accept double quotes).
Although, numeric values should not be enclosed in quotes.
This is correct:
SELECT * FROM Persons WHERE FirstName='Tove'
This is wrong:
SELECT * FROM Persons WHERE FirstName=Tove
This is correct:
SELECT * FROM Persons WHERE Year=1965
This is wrong:
SELECT * FROM Persons WHERE Year='1965'
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want to return for at least one of the columns
7
The AND & OR Operators
The AND & OR operators are used to filter records based on more than one condition.
The AND operator displays a record if both the first condition and the second condition is true.
The OR operator displays a record if either the first condition or the second condition is true.
Now we want to select only the persons with the first name equal to "Tove" AND the last name equal to
"Svendson":
OR Operator Example
Now we want to select only the persons with the first name equal to "Tove" OR the first name equal to
"Ola":
8
2 Svendson Tove Borgvn 23 Sandnes
Combining AND & OR
You can also combine AND and OR (use parenthesis to form complex expressions).
Now we want to select only the persons with the last name equal to "Svendson" AND the first name equal
to "Tove" OR to "Ola":
SELECT column_name(s)
FROM table_name ORDER BY column_name(s) ASC|DESC
ORDER BY Example
9
The result-set will look like this:
Now we want to select all the persons from the table above, however, we want to sort the persons
descending by their last name.
The second form specifies both the column names and the values to be inserted:
10
SQL INSERT INTO Example
The following SQL statement will add a new row, but only add data in the "P_Id", "LastName" and the
"FirstName" columns:
INSERT INTO Persons (P_Id, LastName, FirstName) VALUES (5, 'Tjessem', 'Jakob')
11
The UPDATE statement is used to update records in a table.
The UPDATE statement is used to update existing records in a table.
SQL UPDATE Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or
records that should be updated. If you omit the WHERE clause, all records will be updated!
Now we want to update the person "Tjessem, Jakob" in the "Persons" table.
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob'
12
Be careful when updating records. If we had omitted the WHERE clause in the example above, like this:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!
Now we want to delete the person "Tjessem, Jakob" in the "Persons" table.
13
DELETE FROM Persons
WHERE LastName='Tjessem' AND FirstName='Jakob'
It is possible to delete all rows in a table without deleting the table. This means that the table structure,
attributes, and indexes will be intact:
or
SQL ADVANCE
• MySQL Syntax:
SELECT column_name(s)
FROM table_name
LIMIT number
14
Example:
SELECT *
FROM Persons
LIMIT 5
• Oracle Syntax
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number
Example
SELECT *
FROM Persons
WHERE ROWNUM <=5
Now we want to select only the two first records in the table above.
15
1 Hansen Ola Timoteivn 10 Sandnes
Now we want to select only 50% of the records in the table above.
SQL Wildcards
SQL wildcards can be used when searching for data in a database.
SQL wildcards can substitute for one or more characters when searching for data in a database.
16
SQL wildcards must be used with the SQL LIKE operator.
With SQL, the following wildcards can be used:
Wildcard Description
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
[^charlist] Any single character not in charlist
or
[!charlist]
Next, we want to select the persons living in a city that contains the pattern "nes" from the "Persons"
table.
17
SELECT * FROM Persons
WHERE City LIKE '%nes%'
Next, we want to select the persons with a last name that starts with "S", followed by any character,
followed by "end", followed by any character, followed by "on" from the "Persons" table.
18
We use the following SELECT statement:
Next, we want to select the persons with a last name that do not start with "b" or "s" or "p" from the
"Persons" table.
19
P_Id LastName FirstName Address City
Now we want to select the persons living in a city that starts with "s" from the table above.
The "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the
pattern.
Next, we want to select the persons living in a city that ends with an "s" from the "Persons" table.
20
1 Hansen Ola Timoteivn 10 Sandnes
Next, we want to select the persons living in a city that contains the pattern "tav" from the "Persons"
table.
It is also possible to select the persons living in a city that NOT contains the pattern "tav" from the
"Persons" table, by using the NOT keyword.
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
21
SQL IN Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
IN Operator Example
The "Persons" table:
Now we want to select the persons with a last name equal to "Hansen" or "Pettersen" from the table
above.
22
The BETWEEN operator is used in a WHERE clause to select a range of data between two
values.
The BETWEEN operator selects a range of data between two values. The values can be numbers,
text, or dates.
Now we want to select the persons with a last name alphabetically between "Hansen" and "Pettersen"
from the table above.
Note:
23
The BETWEEN operator is treated differently in different databases.
In some databases, persons with the LastName of "Hansen" or "Pettersen" will not be listed, because the
BETWEEN operator only selects fields that are between and excluding the test values).
In other databases, persons with the LastName of "Hansen" or "Pettersen" will be listed, because the
BETWEEN operator selects fields that are between and including the test values).
And in other databases, persons with the LastName of "Hansen" will be listed, but "Pettersen" will not be
listed (like the example above), because the BETWEEN operator selects fields between the test values,
including the first test value and excluding the last test value.
Example 2
To display the persons outside the range in the previous example, use NOT BETWEEN:
SQL Alias
With SQL, an alias name can be given to a table or to a column.
You can give a table or a column another name by using an alias. This can be a good thing to do if
you have very long or complex table names or column names.
24
Alias Example
Assume we have a table called "Persons" and another table called "Product_Orders". We will give the
table aliases of "p" and "po" respectively.
Now we want to list all the orders that "Ola Hansen" is responsible for.
Notes: As you'll see from the two SELECT statements above; aliases can make queries easier to both
write and to read.
SQL JOIN
SQL joins are used to query data from two or more tables, based on a relationship between certain
columns in these tables.
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a
relationship between certain columns in these tables.
Tables in a database are often related to each other with keys.
A primary key is a column (or a combination of columns) with a unique value for each row. Each
primary key value must be unique within the table. The purpose is to bind data together, across
tables, without repeating all of the data in every table.
Note that the "P_Id" column is the primary key in the "Persons" table. This means that no two rows can
have the same P_Id. The P_Id distinguishes two persons even if they have the same name.
25
Next, we have the "Orders" table:
Note that the "O_Id" column is the primary key in the "Orders" table and that the "P_Id" column refers to
the persons in the "Persons" table without using their names.
Notice that the relationship between the two tables above is the "P_Id" column.
• JOIN: Return rows when there is at least one match in both tables
• LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
• RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
• FULL JOIN: Return rows when there is a match in one of the tables
26
2 Svendson Tove Borgvn 23 Sandnes
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
The INNER JOIN keyword return rows when there is at least one match in both tables. If there are rows
in "Persons" that do not have matches in "Orders", those rows will NOT be listed.
27
SQL LEFT JOIN Keyword
The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no
matches in the right table (table_name2).
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons and their orders - if any, from the tables above.
28
We use the following SELECT statement:
Svendson Tove
Notes: The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no
matches in the right table (Orders).
29
SQL RIGHT JOIN Example
The "Persons" table:
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the orders with containing persons - if any, from the tables above.
30
LastName FirstName OrderNo
34764
Notes: The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no
matches in the left table (Persons).
31
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons and their orders, and all the orders with their persons.
FROM Persons
FULL JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
Svendson Tove
34764
Notes: The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows from
the right table (Orders). If there are rows in "Persons" that do not have matches in "Orders", or if there are
rows in "Orders" that do not have matches in "Persons", those rows will be listed as well.
32
The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns.
The columns must also have similar data types. Also, the columns in each SELECT statement
must be in the same order.
Note: The UNION operator selects only distinct values by default. To allow duplicate values,
use UNION ALL.
PS: The column names in the result-set of a UNION are always equal to the column names in the
first SELECT statement in the UNION.
"Employees_Norway":
E_ID E_Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari
"Employees_USA":
E_ID E_Name
01 Turner, Sally
33
02 Kent, Clark
03 Svendson, Stephen
04 Scott, Stephen
Now we want to list all the different employees in Norway and USA.
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Scott, Stephen
Note: This command cannot be used to list all employees in Norway and USA. In the example above we
have two employees with equal names, and only one of them will be listed. The UNION command selects
only distinct values.
34
Result
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Svendson, Stephen
Scott, Stephen
The SELECT INTO statement is most often used to create backup copies of tables.
SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_tablename
Or we can select only the columns we want into the new table:
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_tablename
35
SQL SELECT INTO Example
Make a Backup Copy - Now we want to make an exact copy of the data in our "Persons" table.
SELECT *
INTO Persons_Backup
FROM Persons
We can also use the IN clause to copy the table into another database:
SELECT *
INTO Persons_Backup IN 'Backup.mdb'
FROM Persons
We can also copy only a few fields into the new table:
SELECT LastName,FirstName
INTO Persons_Backup
FROM Persons
The following SQL statement creates a "Persons_Backup" table with only the persons who lives in the
city "Sandnes":
SELECT LastName,Firstname
INTO Persons_Backup
FROM Persons
WHERE City='Sandnes'
The following example creates a "Persons_Order_Backup" table contains data from the two tables
"Persons" and "Orders":
36
SELECT Persons.LastName,Orders.OrderNo
INTO Persons_Order_Backup
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
The data type specifies what type of data the column can hold. For a complete reference of all the data
types available in MS Access, MySQL, and SQL Server.
37
CREATE TABLE Persons
(
P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
The P_Id column is of type int and will hold a number. The LastName, FirstName, Address, and City
columns are of type varchar with a maximum length of 255 characters.
The empty table can be filled with data with the INSERT INTO statement.
SQL Constraints
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE statement) or
after the table is created (with the ALTER TABLE statement).
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• DEFAULT
38
The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values:
MySQL:
39
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns,
use the following SQL syntax:
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns,
use the following SQL syntax:
MySQL:
40
ALTER TABLE Persons
DROP CONSTRAINT uc_PersonID
MySQL:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on
multiple columns, use the following SQL syntax:
41
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on
multiple columns, use the following SQL syntax:
Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must
already have been declared to not contain NULL values (when the table was first created).
MySQL:
42
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Let's illustrate the foreign key with an example. Look at the following two tables:
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table.
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
The FOREIGN KEY constraint also prevents that invalid data form being inserted into the foreign key
column, because it has to be one of the values contained in the table it points to.
MySQL:
43
SQL Server / Oracle / MS Access:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on
multiple columns, use the following SQL syntax:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on
multiple columns, use the following SQL syntax:
44
To drop a FOREIGN KEY constraint, use the following SQL:
MySQL:
My SQL:
45
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use
the following SQL syntax:
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use
the following SQL syntax:
46
The default value will be added to all new records, if no other value is specified.
The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():
MySQL:
47
MySQL:
Indexes
The CREATE INDEX statement is used to create indexes in tables.
Indexes allow the database application to find data fast; without reading the whole table.
An index can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without (because the indexes
also need an update). So you should only create indexes on columns (and tables) that will be frequently
searched against.
Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for
creating indexes in your database.
48
If you want to create an index on a combination of columns, you can list the column names within the
parentheses, separated by commas:
49
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
To delete a column in a table, use the following syntax (notice that some database systems don't allow
deleting a column):
To change the data type of a column in a table, use the following syntax:
Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data type
specifies what type of data the column can hold. For a complete reference of all the data types available in
MS Access, MySQL, and SQL Server, go to our complete Data Types reference.
50
P_Id LastName FirstName Address City DateOfBirth
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two-digit or
four-digit format.
51
Auto-increment allows a unique number to be generated when a new record is inserted into a
table.
Very often we would like the value of the primary key field to be created automatically every
time a new record is inserted.
The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the
"Persons" table:
By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new
record.
To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column
(a unique value will be added automatically):
The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would
be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName" column
would be set to "Monsen".
The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the
"Persons" table:
52
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.
By default, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
To specify that the "P_Id" column should start at value 10 and increment by 5, change the identity to
IDENTITY(10,5).
To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column
(a unique value will be added automatically):
The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would
be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName" column
would be set to "Monsen".
The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the
"Persons" table:
By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for each new
record.
To specify that the "P_Id" column should start at value 10 and increment by 5, change the autoincrement
to AUTOINCREMENT(10,5).
To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column
(a unique value will be added automatically):
53
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen')
The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would
be assigned a unique value. The "FirstName" column would be set to "Lars" and the "LastName" column
would be set to "Monsen".
You will have to create an auto-increment field with the sequence object (this object generates a number
sequence).
The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It
will also cache up to 10 values for performance. The cache option specifies how many sequence values
will be stored in memory for faster access.
To insert a new record into the "Persons" table, we will have to use the nextval function (this function
retrieves the next value from seq_person sequence):
The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would
be assigned the next number from the seq_person sequence. The "FirstName" column would be set to
"Lars" and the "LastName" column would be set to "Monsen".
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if
the data were coming from one single table.
54
FROM table_name
WHERE condition
Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL
statement, every time a user queries a view.
The view "Current Product List" lists all active products (products that are not discontinued) from the
"Products" table. The view is created with the following SQL:
Another view in the Northwind sample database selects every product in the "Products" table with a unit
price higher than the average unit price:
Another view in the Northwind database calculates the total sale for each category in 1997. Note that this
view selects its data from another view called "Product Sales for 1997":
We can also add a condition to the query. Now we want to see the total sale only for the category
"Beverages":
55
SELECT * FROM [Category Sales For 1997]
WHERE CategoryName='Beverages'
Now we want to add the "Category" column to the "Current Product List" view. We will update the view
with the following SQL:
SQL Dates
The most difficult part when working with dates is to be sure that the format of the date you are trying to
insert, matches the format of the date column in the database.
As long as your data contains only the date portion, your queries will work as expected. However, if a
time portion is involved, it gets complicated.
Before talking about the complications of querying for dates, we will look at the most important built-in
functions for working with dates.
56
Function Description
NOW() Returns the current date and time
CURDATE() Returns the current date
CURTIME() Returns the current time
DATE() Extracts the date part of a date or date/time expression
EXTRACT() Returns a single part of a date/time
DATE_ADD() Adds a specified time interval to a date
DATE_SUB() Subtracts a specified time interval from a date
DATEDIFF() Returns the number of days between two dates
DATE_FORMAT() Displays date/time data in different formats
Function Description
GETDATE() Returns the current date and time
DATEPART() Returns a single part of a date/time
DATEADD() Adds or subtracts a specified time interval from a date
DATEDIFF() Returns the time between two dates
CONVERT() Displays date/time data in different formats
SQL Server comes with the following data types for storing a date or a date/time value in the database:
57
Note: The date types are chosen for a column when you create a new table in your database!
Now we want to select the records with an OrderDate of "2008-11-11" from the table above.
Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate"
column):
we will get no result! This is because the query is looking only for dates with no time portion.
58
Tip: If you want to keep your queries simple and easy to maintain, do not allow time components in your
dates!
Syntax
NOW()
Example
SELECT NOW(),CURDATE(),CURTIME()
Example
The following SQL creates an "Orders" table with a datetime column (OrderDate):
Notice that the OrderDate column specifies NOW() as the default value. As a result, when you insert a
row into the table, the current date and time are automatically inserted into the column.
59
Definition and Usage
Syntax
CURDATE()
Example
SELECT NOW(),CURDATE(),CURTIME()
Example
The following SQL creates an "Orders" table with a datetime column (OrderDate):
Notice that the OrderDate column specifies CURDATE() as the default value. As a result, when you insert
a row into the table, the current date are automatically inserted into the column.
60
Definition and Usage
Syntax
CURTIME()
Example
SELECT NOW(),CURDATE(),CURTIME()
The DATE() function extracts the date part of a date or date/time expression.
Syntax
DATE(date)
Example
61
ProductName OrderDate
The EXTRACT() function is used to return a single part of a date/time, such as year, month, day, hour,
minute, etc.
Syntax
EXTRACT(unit FROM date)
Where date is a valid date expression and unit can be one of the following:
Unit Value
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
SECOND_MICROSECOND
MINUTE_MICROSECOND
MINUTE_SECOND
HOUR_MICROSECOND
HOUR_SECOND
62
HOUR_MINUTE
DAY_MICROSECOND
DAY_SECOND
DAY_MINUTE
DAY_HOUR
YEAR_MONTH
Example
2008 11 11
Syntax
DATE_ADD(date,INTERVAL expr type)
Where date is a valid date expression and expr is the number of interval you want to add.
63
Type Value
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
SECOND_MICROSECOND
MINUTE_MICROSECOND
MINUTE_SECOND
HOUR_MICROSECOND
HOUR_SECOND
HOUR_MINUTE
DAY_MICROSECOND
DAY_SECOND
DAY_MINUTE
DAY_HOUR
YEAR_MONTH
Example
64
OrderId ProductName OrderDate
Now we want to add 45 days to the "OrderDate", to find the payment date.
Result:
OrderId OrderPayDate
1 2008-12-26 13:23:44.657
Syntax
DATE_SUB(date,INTERVAL expr type)
Where date is a valid date expression and expr is the number of interval you want to subtract.
Type Value
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
65
QUARTER
YEAR
SECOND_MICROSECOND
MINUTE_MICROSECOND
MINUTE_SECOND
HOUR_MICROSECOND
HOUR_SECOND
HOUR_MINUTE
DAY_MICROSECOND
DAY_SECOND
DAY_MINUTE
DAY_HOUR
YEAR_MONTH
Example
Result:
66
OrderId SubtractDate
1 2008-11-06 13:23:44.657
Syntax
DATEDIFF(date1,date2)
Note: Only the date parts of the values are used in the calculation.
Example
DiffDate
Example
DiffDate
-1
67
The DATE_FORMAT() function is used to display date/time data in different formats.
Syntax
DATE_FORMAT(date,format)
Where date is a valid date and format specifies the output format for the date/time.
Format Description
%c Month, numeric
%f Microseconds
%H Hour (00-23)
%h Hour (01-12)
%I Hour (01-12)
%k Hour (0-23)
%l Hour (1-12)
%M Month name
%p AM or PM
68
%S Seconds (00-59)
%s Seconds (00-59)
%V Week (01-53) where Sunday is the first day of week, used with %X
%v Week (01-53) where Monday is the first day of week, used with %x
%W Weekday name
%X Year of the week where Sunday is the first day of week, four digits, used with %V
%x Year of the week where Monday is the first day of week, four digits, used with %v
Example
The following script uses the DATE_FORMAT() function to display different formats. We will use the
NOW() function to get the current date/time:
69
The GETDATE() function returns the current date and time from the SQL Server.
Syntax
GETDATE()
Example
CurrentDateTime
2008-11-11 12:45:34.243
Note: The time part above goes all the way to milliseconds.
Example
The following SQL creates an "Orders" table with a datetime column (OrderDate):
Notice that the OrderDate column specifies GETDATE() as the default value. As a result, when you insert
a row into the table, the current date and time are automatically inserted into the column.
70
Definition and Usage
The DATEPART() function is used to return a single part of a date/time, such as year, month, day, hour,
minute, etc.
Syntax
DATEPART(datepart,date)
Where date is a valid date expression and datepart can be one of the following:
datepart Abbreviation
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
Example
71
OrderId ProductName OrderDate
2008 11 11
The DATEADD() function is adds or subtracts a specified time interval from a date.
Syntax
DATEADD(datepart,number,date)
Where date is a valid date expression and number is the number of interval you want to add. The number
can either be positive, for dates in the future, or negative, for dates in the past.
datepart Abbreviation
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
72
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
Example
Now we want to add 45 days to the "OrderDate", to find the payment date.
Result:
OrderId OrderPayDate
1 2008-12-26 13:23:44.657
Syntax
DATEDIFF(datepart,startdate,enddate)
73
Where startdate and enddate are valid date expressions and datepart can be one of the following:
datepart Abbreviation
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
Example
Result:
DiffDate
61
74
Example
Now we want to get the number of days between two dates (notice that the second date is "earlier" than
the first date, and will result in a negative number).
Result:
DiffDate
-61
The CONVERT() function is a general function for converting data into a new data type.
The CONVERT() function can be used to display date/time data in different formats.
Syntax
CONVERT(data_type(length),data_to_be_converted,style)
Where data_type(length) specifies the target data type (with an optional length), data_to_be_converted
contains the value to be converted, and style specifies the output format for the date/time.
101 mm/dd/yy
102 yy.mm.dd
103 dd/mm/yy
104 dd.mm.yy
105 dd-mm-yy
75
106 dd mon yy
108 hh:mm:ss
110 mm-dd-yy
111 yy/mm/dd
112 yymmdd
114 hh:mi:ss:mmm(24h)
Example
The following script uses the CONVERT() function to display different formats. We will use the
GETDATE() function to get the current date/time:
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
76
NULL values represent missing unknown data. By default, a table column can hold NULL values.
Suppose that the "Address" column in the "Persons" table is optional. This means that if we insert a
record with no value for the "Address" column, the "Address" column will be saved with a NULL value.
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.
SQL IS NULL
How do we select only the records with NULL values in the "Address" column?
77
SQL IS NOT NULL
How do we select only the records with no NULL values in the "Address" column?
In the next chapter we will look at the ISNULL(), NVL(), IFNULL() and COALESCE() functions.
Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values.
SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)
FROM Products
In the example above, if any of the "UnitsOnOrder" values are NULL, the result is NULL.
Microsoft's ISNULL() function is used to specify how we want to treat NULL values.
The NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result.
Below, if "UnitsOnOrder" is NULL it will not harm the calculation, because ISNULL() returns a zero if
the value is NULL:
78
SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0))
FROM Products
Oracle
Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the
same result:
SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))
FROM Products
MySQL
MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft's
ISNULL() function.
SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0))
FROM Products
SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))
FROM Products
79
Date/Time Use for dates and times 8 bytes
Yes/No A logical field can be displayed as Yes/No, True/False, or On/Off. In code, 1 bit
use the constants True and False (equivalent to -1 and 0).Note: Null values
are not allowed in Yes/No fields
Ole Object Can store pictures, audio, video, or other BLOBs (Binary Large OBjects) up to 1GB
Hyperlink Contain links to other files, including web pages
Lookup Wizard Let you type a list of options, which can then be chosen from a drop-down 4 bytes
list
Text types:
Note: The values are sorted in the order you enter them.
Number types:
80
specified in parenthesis
SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits
may be specified in parenthesis
MEDIUMINT(size -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number
) of digits may be specified in parenthesis
INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum
number of digits may be specified in parenthesis
BIGINT(size) -9223372036854775808 to 9223372036854775807 normal. 0 to
18446744073709551615 UNSIGNED*. The maximum number of digits may be
specified in parenthesis
FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits may
be specified in the size parameter. The maximum number of digits to the right of the
decimal point is specified in the d parameter
DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits may be
specified in the size parameter. The maximum number of digits to the right of the
decimal point is specified in the d parameter
DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum
number of digits may be specified in the size parameter. The maximum number of
digits to the right of the decimal point is specified in the d parameter
*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an negative
to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a
negative number.
Date types:
*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an
INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time.
81
TIMESTAMP also accepts various formats, like YYYYMMDDHHMMSS, YYMMDDHHMMSS,
YYYYMMDD, or YYMMDD.
Unicode strings:
Binary types:
Number types:
82
int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes
bigint Allows whole numbers between -9,223,372,036,854,775,808 and 8 bytes
9,223,372,036,854,775,807
decimal(p,s) Fixed precision and scale numbers. 5-17 bytes
The p parameter indicates the maximum total number of digits that can be stored
(both to the left and to the right of the decimal point). p must be a value from 1 to
38. Default is 18.
The s parameter indicates the maximum number of digits stored to the right of the
decimal point. s must be a value from 0 to p. Default value is 0
numeric(p,s Fixed precision and scale numbers. 5-17 bytes
)
Allows numbers from -10^38 +1 to 10^38 –1.
The p parameter indicates the maximum total number of digits that can be stored
(both to the left and to the right of the decimal point). p must be a value from 1 to
38. Default is 18.
The s parameter indicates the maximum number of digits stored to the right of the
decimal point. s must be a value from 0 to p. Default value is 0
smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes
money Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytes
float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308. 4 or 8
The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) bytes
holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53.
real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes
Date types:
83
modified. The timestamp value is based upon an internal clock and does not
correspond to real time. Each table may have only one timestamp variable
SQL FUNCTIONS
84
• MID() - Extract characters from a text field
85
OrderAverage
950
Now we want to find the customers that have an OrderPrice value higher than the average OrderPrice
value.
Customer
Hansen
Nilsen
Jensen
SQL COUNT
The COUNT() function returns the number of rows that matches a specified criteria.
The COUNT(column_name) function returns the number of values (NULL values will not be counted) of
the specified column:
The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified
column:
86
Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft
Access.
The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders in total:
CustomerNilsen
NumberOfOrders
87
6
NumberOfCustomers
which is the number of unique customers (Hansen, Nilsen, and Jensen) in the "Orders" table.
88
Now we want to find the first value of the "OrderPrice" column.
FirstOrderPrice
1000
89
Now we want to find the last value of the "OrderPrice" column.
LastOrderPrice
100
90
SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Orders
LargestOrderPrice
2000
SmallestOrderPrice
100
91
The SUM() Function
The SUM() function returns the total sum of a numeric column.
OrderTotal
5700
92
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by
one or more columns.
Now we want to find the total sum (total order) of each customer.
Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000
93
Nice! Isn't it? :)
Customer SUM(OrderPrice)
Hansen 5700
Nilsen 5700
Hansen 5700
Hansen 5700
Jensen 5700
Nilsen 5700
Explanation of why the above SELECT statement cannot be used: The SELECT statement above has
two columns specified (Customer and SUM(OrderPrice). The "SUM(OrderPrice)" returns a single value
(that is the total sum of the "OrderPrice" column), while "Customer" returns 6 values (one value for each
row in the "Orders" table). This will therefore not give us the correct result. However, you have seen that
the GROUP BY statement solves this problem.
94
SQL UCASE() Example
We have the following "Persons" table:
Now we want to select the content of the "LastName" and "FirstName" columns above, and convert the
"LastName" column to uppercase.
LastName FirstName
HANSEN Ola
SVENDSON Tove
PETTERSEN Kari
95
1 Hansen Ola Timoteivn 10 Sandnes
Now we want to select the content of the "LastName" and "FirstName" columns above, and convert the
"LastName" column to lowercase.
LastName FirstName
hansen Ola
svendson Tove
pettersen Kari
Parameter Description
length Optional. The number of characters to return. If omitted, the MID() function returns the rest
of the text
96
SQL MID() Example
We have the following "Persons" table:
Now we want to extract the first four characters of the "City" column above.
SmallCity
Sand
Sand
Stav
97
2 Svendson Tove Borgvn 23 Sandnes
Now we want to select the length of the values in the "Address" column above.
LengthOfAddress
12
Parameter Description
98
We have the following "Products" table:
Now we want to display the product name and the price rounded to the nearest integer.
ProductName UnitPrice
Jarlsberg 10
Mascarpone 33
Gorgonzola 16
99
Now we want to display the products and prices per today's date.
Parameter Description
100
Now we want to display the products and prices per today's date (with today's date displayed in the
following format "YYYY-MM-DD").
101
SQL COMMANDS
Prepared By
Pandeeswari M
CONTENTS
1.FUNDAMENTALS OF SQL
2.FILTERING COMMANDS
3.ORDERING COMMANDS
4.ALIAS
5.AGGREGATE COMMANDS
6.GROUP BY COMMANDS
7.CONDITIONAL STATEMENT
8.JOINS
9.SUBQUERY
10.VIEW & INDEX
11.STRING FUNCTIONS
12.MATHEMATICAL FUNCTIONS
13. DATE-TIME FUNCTIONS
14.PATTERN MATCHING(regex)
15.DATA TYPE CONVERSION FUNCTIONS
DQL(Data Query Language)
To fetch the data from the database
Example: SELECT
CREATE
Syntax:
CREATE TABLE ‘’TABLE_NAME’’(
‘’COLUMN1’’ ‘’DATA_TYPE’’ CONSTRAINTS,
‘’COLUMN2’’ ‘’DATA_TYPE’’ CONSTRAINTS,
‘’COLUMN3’’ ‘’DATA_TYPE’’ CONSTRAINTS,
………………………………………………………………..
‘’COLUMN N’’ ‘’DATA_TYPE’’ CONSTRAINTS
);
INSERT
SELECT
Syntax
SELECT * FROM “TABLE_NAME”;
For select one column
SELECT “COLUMN_NAME” FROM “TABLE_NAME”;
For select multiple columns
SELECT “COLUMN1,COLUMN2,…”
FROM “TABLE_NAME”;
For select all columns
SELECT * FROM “TABLE_NAME”;
DISTINCT
Syntax:
SELECT DISTINCT(*) FROM “TABLE_NAME”;
WHERE
Syntax:
SELECT “COLUMN_NAME(S)”
FROM “TABLE_NAME “
WHERE CONDITION;
AND/OR
The AND/OR is used to combine multiple conditions
Syntax:
SELECT “COLUMN_NAMES(s)”
FROM “TABLE_NAME”
WHERE CONDITION AND/OR CONDITION;
UPDATE
Syntax:
UPDATE “TABLE_NAME”
SET COL_1=VAL_1,COL_2=VAL_2,…
WHERE CONDITION;
DELETE
ALTER
Syntax:
ADD COLUMN
ALTER TABLE “ TABLE_NAME”
ADD “COLUMN_NAME “ “DATA_TYPE”;
DROP COLUMN
ALETR TABLE “TABLE_NAME”
DROP “COLUMN_NAME”;
MODIFY DATA TYPE
ALTER TABLE “TABLE_NAME”
ALTER COLUMN “COL_NAME” TYPE NEW_DATA_TYPE;
RENAME COLUMN
ALTER TABLE “TABLE_NAME”
RENAME COLUMN “COL_NAME” TO “NEW_NAME”;
ADD CONSTRAINTS
ALTER TABLE “TABLE_NAME”
ADD CONSTRAINT COL_NAME CHECK CONDITION;
2.Filtering Commands
IN
Syntax:
SELECT “COL_NAME” FROM “TABLE_NAME”
WHERE “COL_NAME” IN (‘VAL1’, ’VAL2’,…);
BETWEEN
LIKE
Syntax:
SELECT “COL_NAME” FROM “TABLE_NAME”
WHERE “COL_NAME” LIKE ‘PATTERN’;
3.Ordering Commands
ORDER BY
LIMIT
Syntax:
SELECT “COL_NAME(S)” FROM “TABLE_NAME”
[WHERE & ORDER BY – Optional]
LIMIT “LIMIT_VALUE”;
4.ALIAS
AS
5.AGGREGATE COMMANDS
COUNT
Syntax:
SELECT COUNT(COL_NAME) FROM “TABLE_NAME”;
SUM
Syntax:
SELECT SUM(COL_NAME) FROM “TABLE_NAME”;
AVG
Syntax:
SELECT AVG(COL_NAME) FROM “TABLE_NAME”;
MIN
Syntax:
SELECT MIN(COL_NAME) FROM “TABLE_NAME”;
MAX
Syntax:
SELECT MAX(COL_NAME) FROM “TABLE_NAME”;
6.GROUP BY COMMANDS
GROUP BY
Syntax:
SELECT “COL_1”, “COL_2”,…… FROM “TABLE_NAME”
GROUP BY “COL_NAME”;
HAVING
Syntax:
SELECT “COL_1”, “COL_2”,…… FROM “TABLE_NAME”
GROUP BY “COL_NAME”
HAVING ‘CONDITION’;
7.CONDITIONAL STATEMENT
CASE
Syntax:
CASE
WHEN CONDITION THEN RESULT
[WHEN CONDITION THEN RESULT]
[WHEN CONDITION THEN RESULT]
ELSE RESULT
END
8.JOINS
JOINS used to fetch data from multiple tables
TYPES:
INNER JOIN
LEFT JOIN
Syntax:
SELECT COL_1,COL_2,…
FROM “TABLE_1”
LEFT JOIN “TABLE_2”
ON TABLE_1. COMMON_COL = TABLE_2. COMMON_COL;
RIGHT JOIN
FULL JOIN
Syntax:
SELECT COL_1,COL_2,…
FROM “TABLE_1”
FULL JOIN “TABLE_2”
ON TABLE_1.COMMON_COL = TABLE_2. COMMON_COL;
CROSS JOIN
Syntax:
SELECT TAB1.COL,TAB2.COL,…..
FROM “TABLE_1”, “TABLE_2”,……..
EXCEPT
Syntax:
SELECT COL1,COL2,……..
FROM TABLE_A [WHERE]
EXCEPT
SELECT COL_1,COL_2,……
FROM TABLE_B [WHERE];
UNION
Syntax:
SELECT COL1,COL2,……..
FROM TABLE_A [WHERE]
UNION
SELECT COL_1,COL_2,……
FROM TABLE_B [WHERE];
SUBQUERY
VIEW
INDEX
An INDEX creates an entry for each value that
appears in the indexed column
Syntax:
CREATE[UNIQUE] INDEX “index_name”
ON “TABLE_NAME”
(index_col1 [ASC/DESC],………..
11.STRING FUNCTIONS
LENGTH:
UPPER/LOWER
REPLACE
TRIM
RTRIM
LTRIM
LTRIM function removes all specified characters
from LHS of the string
Syntax:
LTRIM(‘string’, trim char)
CONCATENATION
SUBSTRING
STRING_AGG
String aggregate function concatenates input
values into a string, separated by a delimiter
Syntax
STRING_AGG(‘expression’, delimiter)
12.MATHEMATICAL FUNCTIONS
CEIL
FLOOR
SETSEED
ROUND
CURRENT_DATE
CURRENT_TIME
AGE
EXTRACT
TO_CHAR
TO_DATE
T0_NUMBER
Format Description
. decimal point
(period)
MI Minus sign in the specified position for numbers that are less than
0.
PL Plus sign in the specified position for numbers that are greater
than 0.
Pattern Description
W Week of month (1-5) (the first week starts on the first day
of the month)
MI Minute (0-59)
SS Second (0-59)
MS Millisecond (000-999)
US Microsecond (000000-999999)
Test Strategy
A Test Strategy document is a high level document and normally developed by project manager. This document defines “Software Testing
Approach” to achieve testing objectives. The Test Strategy is normally derived from the Business Requirement Specification document.
The Test Strategy document is a static document meaning that it is not updated too often. It sets the standards for testing processes and
activities and other documents such as the Test Plan draws its contents from those standards set in the Test Strategy Document.
Some companies include the “Test Approach” or “Strategy” inside the Test Plan, which is fine and it is usually the case for small projects.
However, for larger projects, there is one Test Strategy document and different number of Test Plans for each phase or level of testing.
Components of the Test Strategy document
Test Plan
The Test Plan document on the other hand, is derived from the Product Description, Software Requirement Specification SRS, or Use Case
Documents.
The Test Plan document is usually prepared by the Test Lead or Test Manager and the focus of the document is to describe what to test, how to
test, when to test and who will do what test.
It is not uncommon to have one Master Test Plan which is a common document for the test phases and each test phase have their own Test
Plan documents.
There is much debate, as to whether the Test Plan document should also be a static document like the Test Strategy document mentioned
above or should it be updated every often to reflect changes according to the direction of the project and activities.
My own personal view is that when a testing phase starts and the Test Manager is “controlling” the activities, the test plan should be updated
to reflect any deviation from the original plan. After all, Planning and Control are continuous activities in the formal test process.
Effort Variance % Effort Variance = (Actual Effort (Hrs.) - Estimated Effort (Hrs.)) / (Estimated Effort (Hrs.)) * 100
Onsite-Offshore Ratio Onsite Ratio = (Total Onshore Associates / Total resources) * 100
Offshore Ratio = (Total Offshore Associates / Total resources) * 100
QA Cost as % of Total IT Cost QA Cost as a % of Total IT Cost = Total QA Cost / Total IT Cost * 100
QA Effort as % of Total IT Effort QA Effort as a % of Total IT Effort = Total QA Effort / Total IT Effort * 100
Automation Effort Saving % Regression Automation Effort Savings % = (Actual Effort for Manual test execution - Actual Effort for
Automated test execution) / Actual Effort for Manual execution * 100%
Defect Leakage Defect Leakage = ((Number of defects unidentified during testing phase but found in production /
(Number of defects unidentified during testing phase but found in production + Total number of valid
defects identified during testing phase)) * 100
Test Effectiveness = ((Number of defects identified during QA testing phase - Number of invalid
Test Effectiveness defects) / (Number of defects identified during testing phase + Total number of valid defects in UAT
phase)) * 100
Test Case Pass Rate % Cumulative Test Case Pass Rate % = (Total Number of Test Cases Passed / Total Number of instances
executed [ First Run + Repeat ] ) * 100
Requirement Stability Index Requirement Stability Index = (Number of Original Baseline Test conditions + Number of Baseline
Test conditions changed + Number of New Test conditions added to Baseline Test conditions +
number of baseline Test conditions deleted) / (Number of Original Baseline Test Conditions)
Defect Re-Open Rate = (Total Number of times defects re-opened / Total Number of times Defects
Defect Reopen Rate %
Fixed ) * 100
Defect Discovery Rate % Defect Discovery Rate = (Total number of defects found / Number of Test Cases executed) * 100
Test Design Coverage = (Number of requirements covered in test design by QA /Scope of the
Test Design Coverage % Requirements to be covered as mentioned in Test plan (after finalizing any Risk Based approach) *
100
Test Execution Coverage % Test Execution Coverage = (Total number of Planned Test Case Executed (Pass+ Fail+ Blocked) / Total
Number of Planned Test Cases) * 100
Schedule Compliance %(Applicable
Schedule Compliance = (Total number of requests not available for UAT / Total number of requests
for Bond)
for the release) * 100
Schedule Variation %( All other
Schedule Variation = Network Days of ((Actual End Date - Planned End Date) / (Planned End Date-
LOB's)
Planned Start Date)) till the reporting period *100
Test Design Productivity- TCP Test Design Productivity (TCP) = ((Number of TCP Created) / ( Total Effort spent for Test design
activity))
Test Execution Productivity- TCP
Test Execution Productivity (TCP) = ((Number of TCP Executed) / (Effort spent for Test Case
Execution))
Regression Automation % = (Total Number of Regression Test Cases Automated / Total Number of
Regression Automation %
Regression Test Cases ) * 100
Test Reports
1) Severity:
It is the extent to which the defect can affect the software. In other words it defines the impact that a given defect has on the
system. For example: If an application or web page crashes when a remote link is clicked, in this case clicking the remote link by
an user is rare but the impact of application crashing is severe. So the severity is high but priority is low.
Severity can be of following types:
▪ Critical: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable and there is no acceptable alternative method to
achieve the required results then the severity will be stated as critical.
▪ Major: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable but there exists an acceptable alternative method
to achieve the required results then the severity will be stated as major.
▪ Moderate: The defect that does not result in the termination, but causes the system to produce incorrect, incomplete or
inconsistent results then the severity will be stated as moderate.
▪ Minor: The defect that does not result in the termination and does not damage the usability of the system and the
desired results can be easily obtained by working around the defects then the severity is stated as minor.
▪ Cosmetic: The defect that is related to the enhancement of the system where the changes are related to the look and
field of the application then the severity is stated as cosmetic.
2) Priority:
Priority defines the order in which we should resolve a defect. Should we fix it now, or can it wait? This priority status is set by
the tester to the developer mentioning the time frame to fix the defect. If high priority is mentioned then the developer has to
fix it at the earliest. The priority status is set based on the customer requirements. For example: If the company name is
misspelled in the home page of the website, then the priority is high and severity is low to fix it.
Priority can be of following types:
▪ Low: The defect is an irritant which should be repaired, but repair can be deferred until after more serious defect have
been fixed.
▪ Medium: The defect should be resolved in the normal course of development activities. It can wait until a new build or
version is created.
▪ High: The defect must be resolved as soon as possible because the defect is affecting the application or the product
severely. The system cannot be used until the repair has been done.
Few very important scenarios related to the severity and priority which are asked during the interview:
High Priority & High Severity: An error which occurs on the basic functionality of the application and will not allow the user to
use the system. (E.g. A site maintaining the student details, on saving record if it, doesn’t allow to save the record then this is
high priority and high severity bug.)
High Priority & Low Severity: The spelling mistakes that happens on the cover page or heading or title of an application.
High Severity & Low Priority: An error which occurs on the functionality of the application (for which there is no workaround)
and will not allow the user to use the system but on click of link which is rarely used by the end user.
Low Priority and Low Severity: Any cosmetic or spelling issues which is within a paragraph or in the report (Not on cover page,
heading, title).
Effort Estimations
Testing scope || Availability of Resources || Type of Testing || No of Test Cycle || Failure Rate (10% to 20%) ||
Productivity || Contingency Factor || Non Testing Activities || Buffer time for Resource onboarding
Risk management
The process of identifying the risk (Product risk or Project risk), analyzing the risk and then mitigating the risk or controlling the
risk is known as Risk Management.
1. Test planning
2. Test case design(end) or sometimes in the test execution phase
1. Risk identification
2. Risk impact analysis
3. Risk mitigation
Risk identification
As it is said, the first step to solving a problem is identifying it. This stage involves making a list of everything that might potentially come up and
disrupt the normal flow of events.
This risk based testing step is commonly led by the QA lead/Manager/representative. However, the lead alone will not be able to come up the
entire list- the entire QA team’s input makes a huge impact. We can say this is a collective activity led by the QA lead.
Also, the risks that are identified during the Test planning phase are more ‘managerial’ in orientation- meaning, we are going to look at
anything that might impact the QA project’s schedule, effort, budget, infrastructure changes, etc. The focus here is not the AUT, but the way
the QA phase will go on.
The following is a sample list of risks that might be listed during test planning phase. Please note, that the AUT and its functionality is not the
focus here.
#1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond the UAT scheduled
start date.
#2. Not enough resources, resources on boarding too late (process takes around 15 days.)
#3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear specifications and
are time consuming to resolve.
At this point, you can choose to be as thorough as you would like, depending on the amount of time available.
Once, all the risks are listed, we progress to Risk assessment/Risk impact analysis.
Risk Analysis in software testing: All the risks are quantified and prioritized in this step. Every risk’s probability (the chance of occurrence) and
impact (amount of loss that it would cause when this risk materializes) are determined systematically.
High – medium – low, values are assigned to both the probability and impact for each risk. The risks with “high” probability and “High” impact
are taken care of first and then the order follows.
Following these steps, the risk impact analysis table for the above risks listed would look something like this (all values are hypothetical and
only for understanding purposes):
1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond
High High
the UAT scheduled start date.
2. Not enough resources, resources on boarding too late (process takes around 15 days.) Medium High
3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear
Medium High
specifications and are time consuming to resolve.
Risk Mitigation
The final step in this Risk Based Testing (RBT) process is to find solutions to plan how to handle each one of these situations. These plans can
differ from company to company, project to project and even person to person.
Here is an example of what the Risk’s table transforms into when this phase is complete:
SCHEDULE • The testing team can control the preparation tasks (in advance) and
Testing schedule is tight. If the start of the testing is the early communication with involved parties.
High High
delayed due to design tasks, the test cannot be • Some buffer has been added to the schedule for contingencies,
extended beyond the UAT scheduled start date. although not as much as best practices advise.
RESOURCES Holidays and vacation have been estimated and built into the
Not enough resources, resources on boarding too Medium High schedule; deviations from the estimation could derive in delays in the
late (process takes around 15 days. testing.
DEFECTS
Defects are found at a late stage of the cycle or at a
Defect management plan is in place to ensure prompt communication
late cycle; defects discovered late are most likely be Medium High
and fixing of issues.
due to unclear specifications and are time consuming
to resolve.
SCOPE Scope is well defined but the changes are in the functionality are not
Medium Medium
Scope completely defined yet finalized or keep on changing.
Non-availability of Independent Test environment Due to non-availability of the environment, the schedule gets impacted
Medium High
and accessibility and will lead to delayed start of Test execution.
During testing, there is a good chance that some “new” defects may be
identified and may become an issue that will take time to resolve.
There are defects that can be raised during testing because of unclear
document specification. These defects can yield to an issue that will
need time to be resolved.
Delayed Testing Due To new Issues Medium High
If these issues become showstoppers, it will greatly impact on the
overall project schedule.
If new defects are discovered, the defect management and issue
management procedures are in place to immediately provide a
resolution.
A few points to note:
1. The sooner risk management starts in a QA project planning phase, the better.
2. Of all 3 steps, risk identification is the most important. If anything is not listed and considered for further steps, the risk goes
unhandled.
3. Try to find an ideal time frame for this activity. Remember, too much planning leaves too little time for doing.
4. Also, after the risk management process, if a new situation comes up, the risk management plan can be altered or updated to reflect
the most current condition.
5. Historical data can be very useful for the success of this process.
Risk Based Testing (RBT) is a testing process with unique features. It is basically for those project and application that is based on risk. Using risk,
Risk based testing prioritize and emphasize the suitable tests at the time of test execution. In other word, Risk is the chance of event of an
unwanted outcome. This unwanted outcome is also related with an impact. Some time it is difficult to test all functionality of the application or
it is might not possible. Use Risk based testing in that case; it tests the functionality which has the highest impact and probability of failure.
It’s better to start risk based testing with product risk analysis. There are numerous methods used for this are,
• Clear understanding of software requirements specification, design documents and other documents.
• Brainstorming with the project stakeholders.
Risk-based testing is the process to understand testing efforts in a way that reduces the remaining level of product risk when the system is
developed,
• Risk-based testing applied to the project at very initial level, identifies risks of the project that expose the quality of the project, this
knowledge guides to testing planning, specification, preparation and execution.
• Risk-based testing includes both mitigation (testing to give chances to decrease the likelihood of faults, specially high-impact faults)
and contingency (testing to know work-around to create the defects that do get past us less painful).
• Risk-based testing also includes measurement process that recognizes how well we are working at finding and removing faults in key
areas.
• Risk-based testing also uses risk analysis to recognize proactive chances to take out or avoid defects through non-testing activities
and to help us select which test activities to perform.
Major processes to execute the Risk-based testing are described below:
Test Plan,
Test Management Test Plan Test Plan Test Steps,
Test Coverage Gap
Test Lab,
Test Lab,
Test Result History,
Cycle Status,
Test Lab, Cycle Status,
Test Execution Management Failed Test,
Test Run Progress Failed Test,
Project Cycles,
Project Cycles,
Test Run Progress
Test Run Progress
Requirement Priority,
Requirement Management Requirement Status Requirement Status Traceability Matrix,
Requirement Status
Defect Triage, Defect Triage,
Defect Management Defect Assignee Not Verified Defects, Not Verified Defects,
Defect Assignee Defect Assignee
Team Productivity Team Progress Team Progress Team Progress
HPQC Tabs
Dashboard (Analysis & Dashboard) // Management (Release) // Requirements //Testing (Test Plan & Test Lab) // Defects
Regression testing
Regression testing is a type of software testing that seeks to uncover new software bugs, or regressions, in existing functional and non-
functional areas of a system after changes such as enhancements, patches or configuration changes, have been made to them.
End-to-end testing is a methodology used to test whether the flow of an application is performing as designed from start to finish. The purpose
of carrying out end-to-end tests is to identify system dependencies and to ensure that the right information is passed between various system
components and systems.
Test Lead Basics Manual Testing Sample Interview
Question and Answers prepared by Haradhan Pal
Test Strategy
A Test Strategy document is a high level document and normally developed by project manager. This document defines “Software Testing
Approach” to achieve testing objectives. The Test Strategy is normally derived from the Business Requirement Specification document.
The Test Strategy document is a static document meaning that it is not updated too often. It sets the standards for testing processes and
activities and other documents such as the Test Plan draws its contents from those standards set in the Test Strategy Document.
Some companies include the “Test Approach” or “Strategy” inside the Test Plan, which is fine and it is usually the case for small projects.
However, for larger projects, there is one Test Strategy document and different number of Test Plans for each phase or level of testing.
Components of the Test Strategy document
Test Plan
The Test Plan document on the other hand, is derived from the Product Description, Software Requirement Specification SRS, or Use Case
Documents.
The Test Plan document is usually prepared by the Test Lead or Test Manager and the focus of the document is to describe what to test, how to
test, when to test and who will do what test.
It is not uncommon to have one Master Test Plan which is a common document for the test phases and each test phase have their own Test
Plan documents.
There is much debate, as to whether the Test Plan document should also be a static document like the Test Strategy document mentioned
above or should it be updated every often to reflect changes according to the direction of the project and activities.
My own personal view is that when a testing phase starts and the Test Manager is “controlling” the activities, the test plan should be updated
to reflect any deviation from the original plan. After all, Planning and Control are continuous activities in the formal test process.
Effort Variance % Effort Variance = (Actual Effort (Hrs.) - Estimated Effort (Hrs.)) / (Estimated Effort (Hrs.)) * 100
Onsite-Offshore Ratio Onsite Ratio = (Total Onshore Associates / Total resources) * 100
Offshore Ratio = (Total Offshore Associates / Total resources) * 100
QA Cost as % of Total IT Cost QA Cost as a % of Total IT Cost = Total QA Cost / Total IT Cost * 100
QA Effort as % of Total IT Effort QA Effort as a % of Total IT Effort = Total QA Effort / Total IT Effort * 100
Automation Effort Saving % Regression Automation Effort Savings % = (Actual Effort for Manual test execution - Actual Effort for
Automated test execution) / Actual Effort for Manual execution * 100%
Defect Leakage Defect Leakage = ((Number of defects unidentified during testing phase but found in production /
(Number of defects unidentified during testing phase but found in production + Total number of valid
defects identified during testing phase)) * 100
Test Effectiveness = ((Number of defects identified during QA testing phase - Number of invalid
Test Effectiveness defects) / (Number of defects identified during testing phase + Total number of valid defects in UAT
phase)) * 100
Test Case Pass Rate % Cumulative Test Case Pass Rate % = (Total Number of Test Cases Passed / Total Number of instances
executed [ First Run + Repeat ] ) * 100
Requirement Stability Index Requirement Stability Index = (Number of Original Baseline Test conditions + Number of Baseline
Test conditions changed + Number of New Test conditions added to Baseline Test conditions +
number of baseline Test conditions deleted) / (Number of Original Baseline Test Conditions)
Defect Re-Open Rate = (Total Number of times defects re-opened / Total Number of times Defects
Defect Reopen Rate %
Fixed ) * 100
Defect Discovery Rate % Defect Discovery Rate = (Total number of defects found / Number of Test Cases executed) * 100
Test Design Coverage = (Number of requirements covered in test design by QA /Scope of the
Test Design Coverage % Requirements to be covered as mentioned in Test plan (after finalizing any Risk Based approach) *
100
Test Execution Coverage % Test Execution Coverage = (Total number of Planned Test Case Executed (Pass+ Fail+ Blocked) / Total
Number of Planned Test Cases) * 100
Schedule Compliance %(Applicable
Schedule Compliance = (Total number of requests not available for UAT / Total number of requests
for Bond)
for the release) * 100
Schedule Variation %( All other
Schedule Variation = Network Days of ((Actual End Date - Planned End Date) / (Planned End Date-
LOB's)
Planned Start Date)) till the reporting period *100
Test Design Productivity- TCP Test Design Productivity (TCP) = ((Number of TCP Created) / ( Total Effort spent for Test design
activity))
Test Execution Productivity- TCP
Test Execution Productivity (TCP) = ((Number of TCP Executed) / (Effort spent for Test Case
Execution))
Regression Automation % = (Total Number of Regression Test Cases Automated / Total Number of
Regression Automation %
Regression Test Cases ) * 100
Test Reports
1) Severity:
It is the extent to which the defect can affect the software. In other words it defines the impact that a given defect has on the
system. For example: If an application or web page crashes when a remote link is clicked, in this case clicking the remote link by
an user is rare but the impact of application crashing is severe. So the severity is high but priority is low.
Severity can be of following types:
▪ Critical: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable and there is no acceptable alternative method to
achieve the required results then the severity will be stated as critical.
▪ Major: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable but there exists an acceptable alternative method
to achieve the required results then the severity will be stated as major.
▪ Moderate: The defect that does not result in the termination, but causes the system to produce incorrect, incomplete or
inconsistent results then the severity will be stated as moderate.
▪ Minor: The defect that does not result in the termination and does not damage the usability of the system and the
desired results can be easily obtained by working around the defects then the severity is stated as minor.
▪ Cosmetic: The defect that is related to the enhancement of the system where the changes are related to the look and
field of the application then the severity is stated as cosmetic.
2) Priority:
Priority defines the order in which we should resolve a defect. Should we fix it now, or can it wait? This priority status is set by
the tester to the developer mentioning the time frame to fix the defect. If high priority is mentioned then the developer has to
fix it at the earliest. The priority status is set based on the customer requirements. For example: If the company name is
misspelled in the home page of the website, then the priority is high and severity is low to fix it.
Priority can be of following types:
▪ Low: The defect is an irritant which should be repaired, but repair can be deferred until after more serious defect have
been fixed.
▪ Medium: The defect should be resolved in the normal course of development activities. It can wait until a new build or
version is created.
▪ High: The defect must be resolved as soon as possible because the defect is affecting the application or the product
severely. The system cannot be used until the repair has been done.
Few very important scenarios related to the severity and priority which are asked during the interview:
High Priority & High Severity: An error which occurs on the basic functionality of the application and will not allow the user to
use the system. (E.g. A site maintaining the student details, on saving record if it, doesn’t allow to save the record then this is
high priority and high severity bug.)
High Priority & Low Severity: The spelling mistakes that happens on the cover page or heading or title of an application.
High Severity & Low Priority: An error which occurs on the functionality of the application (for which there is no workaround)
and will not allow the user to use the system but on click of link which is rarely used by the end user.
Low Priority and Low Severity: Any cosmetic or spelling issues which is within a paragraph or in the report (Not on cover page,
heading, title).
Effort Estimations
Testing scope || Availability of Resources || Type of Testing || No of Test Cycle || Failure Rate (10% to 20%) ||
Productivity || Contingency Factor || Non Testing Activities || Buffer time for Resource onboarding
Risk management
The process of identifying the risk (Product risk or Project risk), analyzing the risk and then mitigating the risk or controlling the
risk is known as Risk Management.
1. Test planning
2. Test case design(end) or sometimes in the test execution phase
1. Risk identification
2. Risk impact analysis
3. Risk mitigation
Risk identification
As it is said, the first step to solving a problem is identifying it. This stage involves making a list of everything that might potentially come up and
disrupt the normal flow of events.
This risk based testing step is commonly led by the QA lead/Manager/representative. However, the lead alone will not be able to come up the
entire list- the entire QA team’s input makes a huge impact. We can say this is a collective activity led by the QA lead.
Also, the risks that are identified during the Test planning phase are more ‘managerial’ in orientation- meaning, we are going to look at
anything that might impact the QA project’s schedule, effort, budget, infrastructure changes, etc. The focus here is not the AUT, but the way
the QA phase will go on.
The following is a sample list of risks that might be listed during test planning phase. Please note, that the AUT and its functionality is not the
focus here.
#1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond the UAT scheduled
start date.
#2. Not enough resources, resources on boarding too late (process takes around 15 days.)
#3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear specifications and
are time consuming to resolve.
At this point, you can choose to be as thorough as you would like, depending on the amount of time available.
Once, all the risks are listed, we progress to Risk assessment/Risk impact analysis.
Risk Analysis in software testing: All the risks are quantified and prioritized in this step. Every risk’s probability (the chance of occurrence) and
impact (amount of loss that it would cause when this risk materializes) are determined systematically.
High – medium – low, values are assigned to both the probability and impact for each risk. The risks with “high” probability and “High” impact
are taken care of first and then the order follows.
Following these steps, the risk impact analysis table for the above risks listed would look something like this (all values are hypothetical and
only for understanding purposes):
1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond
High High
the UAT scheduled start date.
2. Not enough resources, resources on boarding too late (process takes around 15 days.) Medium High
3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear
Medium High
specifications and are time consuming to resolve.
Risk Mitigation
The final step in this Risk Based Testing (RBT) process is to find solutions to plan how to handle each one of these situations. These plans can
differ from company to company, project to project and even person to person.
Here is an example of what the Risk’s table transforms into when this phase is complete:
SCHEDULE • The testing team can control the preparation tasks (in advance) and
Testing schedule is tight. If the start of the testing is the early communication with involved parties.
High High
delayed due to design tasks, the test cannot be • Some buffer has been added to the schedule for contingencies,
extended beyond the UAT scheduled start date. although not as much as best practices advise.
RESOURCES Holidays and vacation have been estimated and built into the
Not enough resources, resources on boarding too Medium High schedule; deviations from the estimation could derive in delays in the
late (process takes around 15 days. testing.
DEFECTS
Defects are found at a late stage of the cycle or at a
Defect management plan is in place to ensure prompt communication
late cycle; defects discovered late are most likely be Medium High
and fixing of issues.
due to unclear specifications and are time consuming
to resolve.
SCOPE Scope is well defined but the changes are in the functionality are not
Medium Medium
Scope completely defined yet finalized or keep on changing.
Non-availability of Independent Test environment Due to non-availability of the environment, the schedule gets impacted
Medium High
and accessibility and will lead to delayed start of Test execution.
During testing, there is a good chance that some “new” defects may be
identified and may become an issue that will take time to resolve.
There are defects that can be raised during testing because of unclear
document specification. These defects can yield to an issue that will
need time to be resolved.
Delayed Testing Due To new Issues Medium High
If these issues become showstoppers, it will greatly impact on the
overall project schedule.
If new defects are discovered, the defect management and issue
management procedures are in place to immediately provide a
resolution.
A few points to note:
1. The sooner risk management starts in a QA project planning phase, the better.
2. Of all 3 steps, risk identification is the most important. If anything is not listed and considered for further steps, the risk goes
unhandled.
3. Try to find an ideal time frame for this activity. Remember, too much planning leaves too little time for doing.
4. Also, after the risk management process, if a new situation comes up, the risk management plan can be altered or updated to reflect
the most current condition.
5. Historical data can be very useful for the success of this process.
Risk Based Testing (RBT) is a testing process with unique features. It is basically for those project and application that is based on risk. Using risk,
Risk based testing prioritize and emphasize the suitable tests at the time of test execution. In other word, Risk is the chance of event of an
unwanted outcome. This unwanted outcome is also related with an impact. Some time it is difficult to test all functionality of the application or
it is might not possible. Use Risk based testing in that case; it tests the functionality which has the highest impact and probability of failure.
It’s better to start risk based testing with product risk analysis. There are numerous methods used for this are,
• Clear understanding of software requirements specification, design documents and other documents.
• Brainstorming with the project stakeholders.
Risk-based testing is the process to understand testing efforts in a way that reduces the remaining level of product risk when the system is
developed,
• Risk-based testing applied to the project at very initial level, identifies risks of the project that expose the quality of the project, this
knowledge guides to testing planning, specification, preparation and execution.
• Risk-based testing includes both mitigation (testing to give chances to decrease the likelihood of faults, specially high-impact faults)
and contingency (testing to know work-around to create the defects that do get past us less painful).
• Risk-based testing also includes measurement process that recognizes how well we are working at finding and removing faults in key
areas.
• Risk-based testing also uses risk analysis to recognize proactive chances to take out or avoid defects through non-testing activities
and to help us select which test activities to perform.
Major processes to execute the Risk-based testing are described below:
Test Plan,
Test Management Test Plan Test Plan Test Steps,
Test Coverage Gap
Test Lab,
Test Lab,
Test Result History,
Cycle Status,
Test Lab, Cycle Status,
Test Execution Management Failed Test,
Test Run Progress Failed Test,
Project Cycles,
Project Cycles,
Test Run Progress
Test Run Progress
Requirement Priority,
Requirement Management Requirement Status Requirement Status Traceability Matrix,
Requirement Status
Defect Triage, Defect Triage,
Defect Management Defect Assignee Not Verified Defects, Not Verified Defects,
Defect Assignee Defect Assignee
Team Productivity Team Progress Team Progress Team Progress
HPQC Tabs
Dashboard (Analysis & Dashboard) // Management (Release) // Requirements //Testing (Test Plan & Test Lab) // Defects
Regression testing
Regression testing is a type of software testing that seeks to uncover new software bugs, or regressions, in existing functional and non-
functional areas of a system after changes such as enhancements, patches or configuration changes, have been made to them.
End-to-end testing is a methodology used to test whether the flow of an application is performing as designed from start to finish. The purpose
of carrying out end-to-end tests is to identify system dependencies and to ensure that the right information is passed between various system
components and systems.
Test Lead Basics Sample Interview Question and
Answers prepared by Haradhan Pal
Test Strategy
A Test Strategy document is a high level document and normally developed by project manager. This document defines “Software Testing
Approach” to achieve testing objectives. The Test Strategy is normally derived from the Business Requirement Specification document.
The Test Strategy document is a static document meaning that it is not updated too often. It sets the standards for testing processes and
activities and other documents such as the Test Plan draws its contents from those standards set in the Test Strategy Document.
Some companies include the “Test Approach” or “Strategy” inside the Test Plan, which is fine and it is usually the case for small projects.
However, for larger projects, there is one Test Strategy document and different number of Test Plans for each phase or level of testing.
Components of the Test Strategy document
Test Plan
The Test Plan document on the other hand, is derived from the Product Description, Software Requirement Specification SRS, or Use Case
Documents.
The Test Plan document is usually prepared by the Test Lead or Test Manager and the focus of the document is to describe what to test, how to
test, when to test and who will do what test.
It is not uncommon to have one Master Test Plan which is a common document for the test phases and each test phase have their own Test
Plan documents.
There is much debate, as to whether the Test Plan document should also be a static document like the Test Strategy document mentioned
above or should it be updated every often to reflect changes according to the direction of the project and activities.
My own personal view is that when a testing phase starts and the Test Manager is “controlling” the activities, the test plan should be updated
to reflect any deviation from the original plan. After all, Planning and Control are continuous activities in the formal test process.
Effort Variance % Effort Variance = (Actual Effort (Hrs.) - Estimated Effort (Hrs.)) / (Estimated Effort (Hrs.)) * 100
Onsite-Offshore Ratio Onsite Ratio = (Total Onshore Associates / Total resources) * 100
Offshore Ratio = (Total Offshore Associates / Total resources) * 100
QA Cost as % of Total IT Cost QA Cost as a % of Total IT Cost = Total QA Cost / Total IT Cost * 100
QA Effort as % of Total IT Effort QA Effort as a % of Total IT Effort = Total QA Effort / Total IT Effort * 100
Automation Effort Saving % Regression Automation Effort Savings % = (Actual Effort for Manual test execution - Actual Effort for
Automated test execution) / Actual Effort for Manual execution * 100%
Defect Leakage Defect Leakage = ((Number of defects unidentified during testing phase but found in production /
(Number of defects unidentified during testing phase but found in production + Total number of valid
defects identified during testing phase)) * 100
Test Effectiveness = ((Number of defects identified during QA testing phase - Number of invalid
Test Effectiveness defects) / (Number of defects identified during testing phase + Total number of valid defects in UAT
phase)) * 100
Test Case Pass Rate % Cumulative Test Case Pass Rate % = (Total Number of Test Cases Passed / Total Number of instances
executed [ First Run + Repeat ] ) * 100
Requirement Stability Index Requirement Stability Index = (Number of Original Baseline Test conditions + Number of Baseline
Test conditions changed + Number of New Test conditions added to Baseline Test conditions +
number of baseline Test conditions deleted) / (Number of Original Baseline Test Conditions)
Defect Re-Open Rate = (Total Number of times defects re-opened / Total Number of times Defects
Defect Reopen Rate %
Fixed ) * 100
Defect Discovery Rate % Defect Discovery Rate = (Total number of defects found / Number of Test Cases executed) * 100
Test Design Coverage = (Number of requirements covered in test design by QA /Scope of the
Test Design Coverage % Requirements to be covered as mentioned in Test plan (after finalizing any Risk Based approach) *
100
Test Execution Coverage % Test Execution Coverage = (Total number of Planned Test Case Executed (Pass+ Fail+ Blocked) / Total
Number of Planned Test Cases) * 100
Schedule Compliance %(Applicable
Schedule Compliance = (Total number of requests not available for UAT / Total number of requests
for Bond)
for the release) * 100
Schedule Variation %( All other
Schedule Variation = Network Days of ((Actual End Date - Planned End Date) / (Planned End Date-
LOB's)
Planned Start Date)) till the reporting period *100
Test Design Productivity- TCP Test Design Productivity (TCP) = ((Number of TCP Created) / ( Total Effort spent for Test design
activity))
Test Execution Productivity- TCP
Test Execution Productivity (TCP) = ((Number of TCP Executed) / (Effort spent for Test Case
Execution))
Regression Automation % = (Total Number of Regression Test Cases Automated / Total Number of
Regression Automation %
Regression Test Cases ) * 100
Test Reports
1) Severity:
It is the extent to which the defect can affect the software. In other words it defines the impact that a given defect has on the
system. For example: If an application or web page crashes when a remote link is clicked, in this case clicking the remote link by
an user is rare but the impact of application crashing is severe. So the severity is high but priority is low.
Severity can be of following types:
▪ Critical: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable and there is no acceptable alternative method to
achieve the required results then the severity will be stated as critical.
▪ Major: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable but there exists an acceptable alternative method
to achieve the required results then the severity will be stated as major.
▪ Moderate: The defect that does not result in the termination, but causes the system to produce incorrect, incomplete or
inconsistent results then the severity will be stated as moderate.
▪ Minor: The defect that does not result in the termination and does not damage the usability of the system and the
desired results can be easily obtained by working around the defects then the severity is stated as minor.
▪ Cosmetic: The defect that is related to the enhancement of the system where the changes are related to the look and
field of the application then the severity is stated as cosmetic.
2) Priority:
Priority defines the order in which we should resolve a defect. Should we fix it now, or can it wait? This priority status is set by
the tester to the developer mentioning the time frame to fix the defect. If high priority is mentioned then the developer has to
fix it at the earliest. The priority status is set based on the customer requirements. For example: If the company name is
misspelled in the home page of the website, then the priority is high and severity is low to fix it.
Priority can be of following types:
▪ Low: The defect is an irritant which should be repaired, but repair can be deferred until after more serious defect have
been fixed.
▪ Medium: The defect should be resolved in the normal course of development activities. It can wait until a new build or
version is created.
▪ High: The defect must be resolved as soon as possible because the defect is affecting the application or the product
severely. The system cannot be used until the repair has been done.
Few very important scenarios related to the severity and priority which are asked during the interview:
High Priority & High Severity: An error which occurs on the basic functionality of the application and will not allow the user to
use the system. (E.g. A site maintaining the student details, on saving record if it, doesn’t allow to save the record then this is
high priority and high severity bug.)
High Priority & Low Severity: The spelling mistakes that happens on the cover page or heading or title of an application.
High Severity & Low Priority: An error which occurs on the functionality of the application (for which there is no workaround)
and will not allow the user to use the system but on click of link which is rarely used by the end user.
Low Priority and Low Severity: Any cosmetic or spelling issues which is within a paragraph or in the report (Not on cover page,
heading, title).
Effort Estimations
Testing scope || Availability of Resources || Type of Testing || No of Test Cycle || Failure Rate (10% to 20%) ||
Productivity || Contingency Factor || Non Testing Activities || Buffer time for Resource onboarding
Risk management
The process of identifying the risk (Product risk or Project risk), analyzing the risk and then mitigating the risk or controlling the
risk is known as Risk Management.
1. Test planning
2. Test case design(end) or sometimes in the test execution phase
1. Risk identification
2. Risk impact analysis
3. Risk mitigation
Risk identification
As it is said, the first step to solving a problem is identifying it. This stage involves making a list of everything that might potentially come up and
disrupt the normal flow of events.
This risk based testing step is commonly led by the QA lead/Manager/representative. However, the lead alone will not be able to come up the
entire list- the entire QA team’s input makes a huge impact. We can say this is a collective activity led by the QA lead.
Also, the risks that are identified during the Test planning phase are more ‘managerial’ in orientation- meaning, we are going to look at
anything that might impact the QA project’s schedule, effort, budget, infrastructure changes, etc. The focus here is not the AUT, but the way
the QA phase will go on.
The following is a sample list of risks that might be listed during test planning phase. Please note, that the AUT and its functionality is not the
focus here.
#1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond the UAT scheduled
start date.
#2. Not enough resources, resources on boarding too late (process takes around 15 days.)
#3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear specifications and
are time consuming to resolve.
At this point, you can choose to be as thorough as you would like, depending on the amount of time available.
Once, all the risks are listed, we progress to Risk assessment/Risk impact analysis.
Risk Analysis in software testing: All the risks are quantified and prioritized in this step. Every risk’s probability (the chance of occurrence) and
impact (amount of loss that it would cause when this risk materializes) are determined systematically.
High – medium – low, values are assigned to both the probability and impact for each risk. The risks with “high” probability and “High” impact
are taken care of first and then the order follows.
Following these steps, the risk impact analysis table for the above risks listed would look something like this (all values are hypothetical and
only for understanding purposes):
1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond
High High
the UAT scheduled start date.
2. Not enough resources, resources on boarding too late (process takes around 15 days.) Medium High
3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear
Medium High
specifications and are time consuming to resolve.
Risk Mitigation
The final step in this Risk Based Testing (RBT) process is to find solutions to plan how to handle each one of these situations. These plans can
differ from company to company, project to project and even person to person.
Here is an example of what the Risk’s table transforms into when this phase is complete:
SCHEDULE • The testing team can control the preparation tasks (in advance) and
Testing schedule is tight. If the start of the testing is the early communication with involved parties.
High High
delayed due to design tasks, the test cannot be • Some buffer has been added to the schedule for contingencies,
extended beyond the UAT scheduled start date. although not as much as best practices advise.
RESOURCES Holidays and vacation have been estimated and built into the
Not enough resources, resources on boarding too Medium High schedule; deviations from the estimation could derive in delays in the
late (process takes around 15 days. testing.
DEFECTS
Defects are found at a late stage of the cycle or at a
Defect management plan is in place to ensure prompt communication
late cycle; defects discovered late are most likely be Medium High
and fixing of issues.
due to unclear specifications and are time consuming
to resolve.
SCOPE Scope is well defined but the changes are in the functionality are not
Medium Medium
Scope completely defined yet finalized or keep on changing.
Non-availability of Independent Test environment Due to non-availability of the environment, the schedule gets impacted
Medium High
and accessibility and will lead to delayed start of Test execution.
During testing, there is a good chance that some “new” defects may be
identified and may become an issue that will take time to resolve.
There are defects that can be raised during testing because of unclear
document specification. These defects can yield to an issue that will
need time to be resolved.
Delayed Testing Due To new Issues Medium High
If these issues become showstoppers, it will greatly impact on the
overall project schedule.
If new defects are discovered, the defect management and issue
management procedures are in place to immediately provide a
resolution.
A few points to note:
1. The sooner risk management starts in a QA project planning phase, the better.
2. Of all 3 steps, risk identification is the most important. If anything is not listed and considered for further steps, the risk goes
unhandled.
3. Try to find an ideal time frame for this activity. Remember, too much planning leaves too little time for doing.
4. Also, after the risk management process, if a new situation comes up, the risk management plan can be altered or updated to reflect
the most current condition.
5. Historical data can be very useful for the success of this process.
Risk Based Testing (RBT) is a testing process with unique features. It is basically for those project and application that is based on risk. Using risk,
Risk based testing prioritize and emphasize the suitable tests at the time of test execution. In other word, Risk is the chance of event of an
unwanted outcome. This unwanted outcome is also related with an impact. Some time it is difficult to test all functionality of the application or
it is might not possible. Use Risk based testing in that case; it tests the functionality which has the highest impact and probability of failure.
It’s better to start risk based testing with product risk analysis. There are numerous methods used for this are,
• Clear understanding of software requirements specification, design documents and other documents.
• Brainstorming with the project stakeholders.
Risk-based testing is the process to understand testing efforts in a way that reduces the remaining level of product risk when the system is
developed,
• Risk-based testing applied to the project at very initial level, identifies risks of the project that expose the quality of the project, this
knowledge guides to testing planning, specification, preparation and execution.
• Risk-based testing includes both mitigation (testing to give chances to decrease the likelihood of faults, specially high-impact faults)
and contingency (testing to know work-around to create the defects that do get past us less painful).
• Risk-based testing also includes measurement process that recognizes how well we are working at finding and removing faults in key
areas.
• Risk-based testing also uses risk analysis to recognize proactive chances to take out or avoid defects through non-testing activities
and to help us select which test activities to perform.
Major processes to execute the Risk-based testing are described below:
Test Plan,
Test Management Test Plan Test Plan Test Steps,
Test Coverage Gap
Test Lab,
Test Lab,
Test Result History,
Cycle Status,
Test Lab, Cycle Status,
Test Execution Management Failed Test,
Test Run Progress Failed Test,
Project Cycles,
Project Cycles,
Test Run Progress
Test Run Progress
Requirement Priority,
Requirement Management Requirement Status Requirement Status Traceability Matrix,
Requirement Status
Defect Triage, Defect Triage,
Defect Management Defect Assignee Not Verified Defects, Not Verified Defects,
Defect Assignee Defect Assignee
Team Productivity Team Progress Team Progress Team Progress
HPQC Tabs
Dashboard (Analysis & Dashboard) // Management (Release) // Requirements //Testing (Test Plan & Test Lab) // Defects
Regression testing
Regression testing is a type of software testing that seeks to uncover new software bugs, or regressions, in existing functional and non-
functional areas of a system after changes such as enhancements, patches or configuration changes, have been made to them.
End-to-end testing is a methodology used to test whether the flow of an application is performing as designed from start to finish. The purpose
of carrying out end-to-end tests is to identify system dependencies and to ensure that the right information is passed between various system
components and systems.
Test Lead Basics Sample Interview Question and
Answers prepared by Haradhan Pal
Test Strategy
A Test Strategy document is a high level document and normally developed by project manager. This document defines “Software Testing
Approach” to achieve testing objectives. The Test Strategy is normally derived from the Business Requirement Specification document.
The Test Strategy document is a static document meaning that it is not updated too often. It sets the standards for testing processes and
activities and other documents such as the Test Plan draws its contents from those standards set in the Test Strategy Document.
Some companies include the “Test Approach” or “Strategy” inside the Test Plan, which is fine and it is usually the case for small projects.
However, for larger projects, there is one Test Strategy document and different number of Test Plans for each phase or level of testing.
Components of the Test Strategy document
Test Plan
The Test Plan document on the other hand, is derived from the Product Description, Software Requirement Specification SRS, or Use Case
Documents.
The Test Plan document is usually prepared by the Test Lead or Test Manager and the focus of the document is to describe what to test, how to
test, when to test and who will do what test.
It is not uncommon to have one Master Test Plan which is a common document for the test phases and each test phase have their own Test
Plan documents.
There is much debate, as to whether the Test Plan document should also be a static document like the Test Strategy document mentioned
above or should it be updated every often to reflect changes according to the direction of the project and activities.
My own personal view is that when a testing phase starts and the Test Manager is “controlling” the activities, the test plan should be updated
to reflect any deviation from the original plan. After all, Planning and Control are continuous activities in the formal test process.
Effort Variance % Effort Variance = (Actual Effort (Hrs.) - Estimated Effort (Hrs.)) / (Estimated Effort (Hrs.)) * 100
Onsite-Offshore Ratio Onsite Ratio = (Total Onshore Associates / Total resources) * 100
Offshore Ratio = (Total Offshore Associates / Total resources) * 100
QA Cost as % of Total IT Cost QA Cost as a % of Total IT Cost = Total QA Cost / Total IT Cost * 100
QA Effort as % of Total IT Effort QA Effort as a % of Total IT Effort = Total QA Effort / Total IT Effort * 100
Automation Effort Saving % Regression Automation Effort Savings % = (Actual Effort for Manual test execution - Actual Effort for
Automated test execution) / Actual Effort for Manual execution * 100%
Defect Leakage Defect Leakage = ((Number of defects unidentified during testing phase but found in production /
(Number of defects unidentified during testing phase but found in production + Total number of valid
defects identified during testing phase)) * 100
Test Effectiveness = ((Number of defects identified during QA testing phase - Number of invalid
Test Effectiveness defects) / (Number of defects identified during testing phase + Total number of valid defects in UAT
phase)) * 100
Test Case Pass Rate % Cumulative Test Case Pass Rate % = (Total Number of Test Cases Passed / Total Number of instances
executed [ First Run + Repeat ] ) * 100
Requirement Stability Index Requirement Stability Index = (Number of Original Baseline Test conditions + Number of Baseline
Test conditions changed + Number of New Test conditions added to Baseline Test conditions +
number of baseline Test conditions deleted) / (Number of Original Baseline Test Conditions)
Defect Re-Open Rate = (Total Number of times defects re-opened / Total Number of times Defects
Defect Reopen Rate %
Fixed ) * 100
Defect Discovery Rate % Defect Discovery Rate = (Total number of defects found / Number of Test Cases executed) * 100
Test Design Coverage = (Number of requirements covered in test design by QA /Scope of the
Test Design Coverage % Requirements to be covered as mentioned in Test plan (after finalizing any Risk Based approach) *
100
Test Execution Coverage % Test Execution Coverage = (Total number of Planned Test Case Executed (Pass+ Fail+ Blocked) / Total
Number of Planned Test Cases) * 100
Schedule Compliance %(Applicable
Schedule Compliance = (Total number of requests not available for UAT / Total number of requests
for Bond)
for the release) * 100
Schedule Variation %( All other
Schedule Variation = Network Days of ((Actual End Date - Planned End Date) / (Planned End Date-
LOB's)
Planned Start Date)) till the reporting period *100
Test Design Productivity- TCP Test Design Productivity (TCP) = ((Number of TCP Created) / ( Total Effort spent for Test design
activity))
Test Execution Productivity- TCP
Test Execution Productivity (TCP) = ((Number of TCP Executed) / (Effort spent for Test Case
Execution))
Regression Automation % = (Total Number of Regression Test Cases Automated / Total Number of
Regression Automation %
Regression Test Cases ) * 100
Test Reports
1) Severity:
It is the extent to which the defect can affect the software. In other words it defines the impact that a given defect has on the
system. For example: If an application or web page crashes when a remote link is clicked, in this case clicking the remote link by
an user is rare but the impact of application crashing is severe. So the severity is high but priority is low.
Severity can be of following types:
▪ Critical: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable and there is no acceptable alternative method to
achieve the required results then the severity will be stated as critical.
▪ Major: The defect that results in the termination of the complete system or one or more component of the system and
causes extensive corruption of the data. The failed function is unusable but there exists an acceptable alternative method
to achieve the required results then the severity will be stated as major.
▪ Moderate: The defect that does not result in the termination, but causes the system to produce incorrect, incomplete or
inconsistent results then the severity will be stated as moderate.
▪ Minor: The defect that does not result in the termination and does not damage the usability of the system and the
desired results can be easily obtained by working around the defects then the severity is stated as minor.
▪ Cosmetic: The defect that is related to the enhancement of the system where the changes are related to the look and
field of the application then the severity is stated as cosmetic.
2) Priority:
Priority defines the order in which we should resolve a defect. Should we fix it now, or can it wait? This priority status is set by
the tester to the developer mentioning the time frame to fix the defect. If high priority is mentioned then the developer has to
fix it at the earliest. The priority status is set based on the customer requirements. For example: If the company name is
misspelled in the home page of the website, then the priority is high and severity is low to fix it.
Priority can be of following types:
▪ Low: The defect is an irritant which should be repaired, but repair can be deferred until after more serious defect have
been fixed.
▪ Medium: The defect should be resolved in the normal course of development activities. It can wait until a new build or
version is created.
▪ High: The defect must be resolved as soon as possible because the defect is affecting the application or the product
severely. The system cannot be used until the repair has been done.
Few very important scenarios related to the severity and priority which are asked during the interview:
High Priority & High Severity: An error which occurs on the basic functionality of the application and will not allow the user to
use the system. (E.g. A site maintaining the student details, on saving record if it, doesn’t allow to save the record then this is
high priority and high severity bug.)
High Priority & Low Severity: The spelling mistakes that happens on the cover page or heading or title of an application.
High Severity & Low Priority: An error which occurs on the functionality of the application (for which there is no workaround)
and will not allow the user to use the system but on click of link which is rarely used by the end user.
Low Priority and Low Severity: Any cosmetic or spelling issues which is within a paragraph or in the report (Not on cover page,
heading, title).
Effort Estimations
Testing scope || Availability of Resources || Type of Testing || No of Test Cycle || Failure Rate (10% to 20%) ||
Productivity || Contingency Factor || Non Testing Activities || Buffer time for Resource onboarding
Risk management
The process of identifying the risk (Product risk or Project risk), analyzing the risk and then mitigating the risk or controlling the
risk is known as Risk Management.
1. Test planning
2. Test case design(end) or sometimes in the test execution phase
1. Risk identification
2. Risk impact analysis
3. Risk mitigation
Risk identification
As it is said, the first step to solving a problem is identifying it. This stage involves making a list of everything that might potentially come up and
disrupt the normal flow of events.
This risk based testing step is commonly led by the QA lead/Manager/representative. However, the lead alone will not be able to come up the
entire list- the entire QA team’s input makes a huge impact. We can say this is a collective activity led by the QA lead.
Also, the risks that are identified during the Test planning phase are more ‘managerial’ in orientation- meaning, we are going to look at
anything that might impact the QA project’s schedule, effort, budget, infrastructure changes, etc. The focus here is not the AUT, but the way
the QA phase will go on.
The following is a sample list of risks that might be listed during test planning phase. Please note, that the AUT and its functionality is not the
focus here.
#1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond the UAT scheduled
start date.
#2. Not enough resources, resources on boarding too late (process takes around 15 days.)
#3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear specifications and
are time consuming to resolve.
At this point, you can choose to be as thorough as you would like, depending on the amount of time available.
Once, all the risks are listed, we progress to Risk assessment/Risk impact analysis.
Risk Analysis in software testing: All the risks are quantified and prioritized in this step. Every risk’s probability (the chance of occurrence) and
impact (amount of loss that it would cause when this risk materializes) are determined systematically.
High – medium – low, values are assigned to both the probability and impact for each risk. The risks with “high” probability and “High” impact
are taken care of first and then the order follows.
Following these steps, the risk impact analysis table for the above risks listed would look something like this (all values are hypothetical and
only for understanding purposes):
1. Testing schedule is tight. If the start of the testing is delayed due to design tasks, the test cannot be extended beyond
High High
the UAT scheduled start date.
2. Not enough resources, resources on boarding too late (process takes around 15 days.) Medium High
3. Defects are found at a late stage of the cycle or at a late cycle; defects discovered late are most likely be due to unclear
Medium High
specifications and are time consuming to resolve.
Risk Mitigation
The final step in this Risk Based Testing (RBT) process is to find solutions to plan how to handle each one of these situations. These plans can
differ from company to company, project to project and even person to person.
Here is an example of what the Risk’s table transforms into when this phase is complete:
SCHEDULE • The testing team can control the preparation tasks (in advance) and
Testing schedule is tight. If the start of the testing is the early communication with involved parties.
High High
delayed due to design tasks, the test cannot be • Some buffer has been added to the schedule for contingencies,
extended beyond the UAT scheduled start date. although not as much as best practices advise.
RESOURCES Holidays and vacation have been estimated and built into the
Not enough resources, resources on boarding too Medium High schedule; deviations from the estimation could derive in delays in the
late (process takes around 15 days. testing.
DEFECTS
Defects are found at a late stage of the cycle or at a
Defect management plan is in place to ensure prompt communication
late cycle; defects discovered late are most likely be Medium High
and fixing of issues.
due to unclear specifications and are time consuming
to resolve.
SCOPE Scope is well defined but the changes are in the functionality are not
Medium Medium
Scope completely defined yet finalized or keep on changing.
Non-availability of Independent Test environment Due to non-availability of the environment, the schedule gets impacted
Medium High
and accessibility and will lead to delayed start of Test execution.
During testing, there is a good chance that some “new” defects may be
identified and may become an issue that will take time to resolve.
There are defects that can be raised during testing because of unclear
document specification. These defects can yield to an issue that will
need time to be resolved.
Delayed Testing Due To new Issues Medium High
If these issues become showstoppers, it will greatly impact on the
overall project schedule.
If new defects are discovered, the defect management and issue
management procedures are in place to immediately provide a
resolution.
A few points to note:
1. The sooner risk management starts in a QA project planning phase, the better.
2. Of all 3 steps, risk identification is the most important. If anything is not listed and considered for further steps, the risk goes
unhandled.
3. Try to find an ideal time frame for this activity. Remember, too much planning leaves too little time for doing.
4. Also, after the risk management process, if a new situation comes up, the risk management plan can be altered or updated to reflect
the most current condition.
5. Historical data can be very useful for the success of this process.
Risk Based Testing (RBT) is a testing process with unique features. It is basically for those project and application that is based on risk. Using risk,
Risk based testing prioritize and emphasize the suitable tests at the time of test execution. In other word, Risk is the chance of event of an
unwanted outcome. This unwanted outcome is also related with an impact. Some time it is difficult to test all functionality of the application or
it is might not possible. Use Risk based testing in that case; it tests the functionality which has the highest impact and probability of failure.
It’s better to start risk based testing with product risk analysis. There are numerous methods used for this are,
• Clear understanding of software requirements specification, design documents and other documents.
• Brainstorming with the project stakeholders.
Risk-based testing is the process to understand testing efforts in a way that reduces the remaining level of product risk when the system is
developed,
• Risk-based testing applied to the project at very initial level, identifies risks of the project that expose the quality of the project, this
knowledge guides to testing planning, specification, preparation and execution.
• Risk-based testing includes both mitigation (testing to give chances to decrease the likelihood of faults, specially high-impact faults)
and contingency (testing to know work-around to create the defects that do get past us less painful).
• Risk-based testing also includes measurement process that recognizes how well we are working at finding and removing faults in key
areas.
• Risk-based testing also uses risk analysis to recognize proactive chances to take out or avoid defects through non-testing activities
and to help us select which test activities to perform.
Major processes to execute the Risk-based testing are described below:
Test Plan,
Test Management Test Plan Test Plan Test Steps,
Test Coverage Gap
Test Lab,
Test Lab,
Test Result History,
Cycle Status,
Test Lab, Cycle Status,
Test Execution Management Failed Test,
Test Run Progress Failed Test,
Project Cycles,
Project Cycles,
Test Run Progress
Test Run Progress
Requirement Priority,
Requirement Management Requirement Status Requirement Status Traceability Matrix,
Requirement Status
Defect Triage, Defect Triage,
Defect Management Defect Assignee Not Verified Defects, Not Verified Defects,
Defect Assignee Defect Assignee
Team Productivity Team Progress Team Progress Team Progress
HPQC Tabs
Dashboard (Analysis & Dashboard) // Management (Release) // Requirements //Testing (Test Plan & Test Lab) // Defects
Regression testing
Regression testing is a type of software testing that seeks to uncover new software bugs, or regressions, in existing functional and non-
functional areas of a system after changes such as enhancements, patches or configuration changes, have been made to them.
End-to-end testing is a methodology used to test whether the flow of an application is performing as designed from start to finish. The purpose
of carrying out end-to-end tests is to identify system dependencies and to ensure that the right information is passed between various system
components and systems.
Test Levels In
Software Testing
Module / Unit
Testing
01
Integration
Testing
02
System
Testing
03
Acceptance
Testing
The quality assurance team does
this testing to check if the clients'
requirements are met or not.
04
Software Testing
Cyber Security
www.precisetestingsolution.com
TEST PLAN
Table of Contents
1. Introduction 3
2. Scope 3
3. Test Objective 4
4. Reference Document 4
Test Strategy
Test Schdeule
Test Resources
Pass/Fail Criteria:
Environment
Exit Criteria
1. Introduction
The Test Plan outlines the scope, approach, resources, and schedule of all testing
activities. It identifes the items and features to be tested; types of testing. It contains a
detailed and executable strategy for conducting. It defnes the detailed testing objective
specifc to a particular system, the testing approach, test environment, test conditions, and
the test plan.
2. Scope
The scope of this test plan is to ensure websiteX meets all of its technical, functional and
business requirements. The purpose of this document is to describe the overall test plan
and strategy for testing the website. The approach described in this document provides the
framework for all the testing related to website. This document will also be updated as
required with the requirement updates. We also need to make sure that all the expected
results are achieved.
3. Test Objectives
The general test objectives are to test the correctness of the generation of the
interface data fle, the content of the interface data fle, and any error conditions. The
quality objectives of testing the website are to ensure complete validation of the
business and software requirements:
Reference Documents
—--------
Requirement Analysis
Design Testing
Functionality Testing
Verify each functionlaity of the system is working as per requirement
Testing the links
Testing the forms
Cookies Testing
Validation (HTML/CSS/PHP)
Database Testing
Integration Test Specifcation
API Testing
Usability Testing
Compatibility Testing
Browser Compatibility
OS compatibility
Mobile browsing
Performance Testing
Load Testing
Stress Testing
Security Testing
Automation Testing
Smoke Testing
Beta Testing
Make sure the major scenarios and requirements are mentioned in the document. If there
is something missing, highlight the missing requiremnts and also suggest improvements if
there is any.
—-----------
And also make sure the designs for all the specifed languages and dark themes.
search engines.
Comp
5.4. API Testing
Set of procedures to verify the expected functionality, reliability, and security and ensure
the correct interaction between backend and frontend. To validate the logic of the build
architecture within a short amount of time. Each api test consists of some test actions
mentioned below. Further details of API Testing will be covered in API Test Plan
To determine design inconsistencies and usability problem areas within the user
interface and content areas.
Potential sources of error may include:
Navigation errors – failure to locate functions, excessive keystrokes to
complete a function, failure to follow recommended screen fow.
Presentation errors – failure to locate and properly act upon desired
information in screens, selection errors due to labeling ambiguities.
Control usage problems – improper toolbar or entry feld usage.
Exercise the application or web site under controlled test conditions with representative
users. Data will be used to access whether usability goals regarding an effective,
effcient, and well-received user interface have been achieved.
Establish baseline user performance and user-satisfaction levels of the use interface for
future usability evaluations.
Basic Usability:
The site should have a clear hierarchy.
Headings clearly indicate the structure of the document
Navigation should be easy to understand
Navigation is consistent throughout the site
The site uses underlined links
The site uses consistent and appropriate language
The site has easy to fnd sitemap and contact page
The site has a search tool
The site has a link to home page on every page
The site has clearly defned visited links
5.7.2 OS compatibility:
Some functionality in the web application may not be compatible with all operating
systems. All new technologies used in web development like graphics designs, interface
calls like different API’s may not be available in all Operating Systems. Testing the web
application on different operating systems like Windows, Unix, MAC, Linux, Solaris with
different OS favors.
Accept-Language
SESSION_ID/Device ID
Signature
User-Agent
Furthermore we will use Zap for security testing. It is an end-to-end web application
security scanner. This will give us a 360-degree view of the security of our website. It
is important to have an understanding of how the client (browser) and the server
communicate using HTTP. the tester should at least know the basics of SQL injection
and XSS.
Automation Testing:
Smoke testing will be performed at two stages. Once new features are added, the other is
before fnalizing the build for Production/live.
Beta testing is the fnal round of testing before releasing a product to a wide audience. The
objective is to uncover as many bugs or usability issues as possible in this controlled
setting. QA will also a perfrom the beta Testing.
6. Test Strategy
The overall strategy of this testing initiative is manual, black box testing. We are
testing the data, interface part and mplemented system in detail. The testing at the
SAP end of the interface will be covered by the SAP functional testing. Follow the
testing phases and techniques mentioned inside “Detailed Test Approach”. All type
of testing are covered in this document.
Some of the test specifcations use test data which needs to be set-up in the test
environment prior to executing the test cases.
For each level of testing, a separate test plan is prepared with the following set of
deliverables:
Test Schdeule
The test schedule is the timeline of acceptance testing activities and deliverable dates.
Requirement Analysis.
Design Testing
Develop test scenarios
Develop test cases
Review scenarios/test cases for accuracy, completeness and sequence (confrm
test data is correct)
Integration testing
API Testing
Regression Testing
Functionality Testing
Database Testing
Integration Test Specifcation
Usability Testing
Compatibility Testing
Performance Testing
Security Testing
UAT Testing
Automation Testing
Smoke Testing
Beta Testing
Severity 1 - Crash or High impact problems that often prevent a user/host from correctly
completing an experience/booking.
Severity 3 - Either moderate problems with low frequency or low problems with moderate
frequency; these are minor annoyance problems faced by a number of participants.
Severity 4 - Low impact problems faced by few participants; there is low risk of not
resolving these problems. Reward for resolution is typically exhibited in increased user
satisfaction.
9. Test Resources
Here is the list of resources with the roles those will work on website
1.
2.
11. Environment
Start testing on a staging server once a certain level is achieved, then move to Production
and give the fnal approval at Production. All the experiments should be performed at
staging. Testing data must be private at Production.
12. Test Cases and Test Scenarios
Write down the detailed test cases on the basis of requirement, technical doecument and test
plan. For testcases use the Google sheet and use the Jira for bug, suggestion reporting.
Jira wil be used for defect reporting and issue bugs/defects management and
traceability.
completed.
SELECT:
5. Show all the rows and all the columns of Staff table
ANS:
SELECT * FROM Staff;
6. Produce a list of salaries for all staff, showing only the staff number, the first and last names, and
the salary details.
ANS:
SELECT staffNo, fName, IName, salary FROM Staff;
7. List full details of all hotels in London.
ANS:
SELECT * FROM Hotel WHERE city = 'London';
8. List the unique property numbers of all properties that have been viewed.
ANS:
SELECT DISTINCT propertyNo FROM Viewing;
9. Write a SQL query to list the staff who work in London. Please show their first name, last name and
branchno.
ANS:
SELECT fname,lname,b.branchno FROM Staff s, Branch b
WHERE s.branchno=b.branchno and b.city='London';
10. Produce a list of monthly salaries for all staff, showing the staff number, the first and last names,
and the salary details.
ANS:
SELECT staffNo, fName, IName, salary/12 FROM Staff;
11. List all staff with a salary greater than $10,000.
ANS:
SELECT staffNo, fName, IName, position, salary FROM Staff WHERE salary > 10000;
12. Write a SQL query to display the name for vendor lives in New York with zipcode 07811.
(refer to A_Vendors)
ANS:
SELECT name from A_Vendors where State = 'NY' and Zipcode='07811';
13. Write a SQL query to list the unique position for female staff with salary less than 10000.
ANS:
SELECT distinct position FROM Staff WHERE sex='F' and salary < 10000;
14. List the addresses of all branch offices in London or Glasgow.
ANS:
SELECT street FROM Branch WHERE city = 'London' OR city = 'Glasgow';
15. Write a SQL query to display product names that make profit < 20. (refer to A_Products)
ANS:
SELECT name FROM A_Products WHERE sell_price - cost < 20;
16. List all staff with a salary between $20,000 and $30,000.
ANS:
SELECT staffNo, fName, IName, position, salary
FROM Staff WHERE salary BETWEEN 20000 AND 30000;
ANS 2:
SELECT staffNo, fName, IName, position, salary
FROM Staff WHERE salary > = 20000 AND salary < = 30000;
17. List all managers and supervisors.
ANS:
SELECT staffNo, fName, IName, position FROM Staff WHERE position IN ('Manager', 'Supervisor');
ANS 2:
SELECT staffNo, fName, IName, position FROM Staff WHERE position = 'Manager' OR position =
'Supervisor';
18. What is the output of the following SQL query?
SELECT clientno, propertyno FROM Viewing WHERE comment!='';
ANS:
+----------+------------+
| clientno | propertyno |
+----------+------------+
| CR56 | PA14 |
| CR62 | PA14 |
| CR76 | PG4 |
+----------+------------+
19. List all double or family rooms with a price below 40.00 per night, in ascending order of price.
ANS:
SELECT * FROM Room WHERE price < 40 AND type IN ('double', 'family') ORDER BY price;
20. Find all owners with the string ‘Glasgow’ in their address.
ANS:
SELECT ownerNo, fName, IName, address, telNo
FROM PrivateOwner WHERE address LIKE '%Glasgow%';
21. Write a SQL query to display the total number of Customers living in Union.
ANS:
SELECT count(name) FROM A_Customers WHERE address like '%Union%';
22. List the details of all viewings on property PG4 where a comment has not been supplied.
ANS:
SELECT clientNo, viewDate FROM Viewing WHERE propertyNo = 'PG4' AND comment IS NULL;
23. Produce a list of salaries for all staff, arranged in descending order of salary.
ANS:
SELECT staffNo, fName, lName, salary FROM Staff ORDER BY salary DESC;
24. Produce an abbreviated list of properties arranged in order of property type.
ANS:
SELECT propertyNo, type, rooms, rent FROM PropertyForRent ORDER BY type;
25. List the names and addresses of all guests in London, alphabetically ordered by name.
ANS:
SELECT guestName, guestAddress FROM Guest
WHERE guestAddress LIKE '%London%' ORDER BY guestName;
SUBQUERY:
44. Write a SQL query to find the staff name (first name, last name) who has salary higher than the
average salary of branchno =’B003’;
ANS:
SELECT fname,lname FROM Staff where salary > (select avg(salary) from Staff
WHERE branchno ='B003');
45. Can we run the following query without any problem?
SELECT city FROM Branch WHERE branchNo = (SELECT branchNo FROM Staff where sex='F');
ANS:
Error, Subquery returns more than 1 row. Cannot use =, should use IN
46. What is the output of the following SQL query?
SELECT c.name FROM A_Customers c WHERE c.id NOT in (SELECT c_id FROM A_Reviews);
ANS:
+-------+
| name |
+-------+
| BJ2 |
| BJ3 |
| Judy1 |
| Judy2 |
+-------+
47. What is the output of the following SQL query?
SELECT count(distinct(city)) as myCt FROM Hotel WHERE hotelno in (SELECT hotelno FROM Room
WHERE type='single');
ANS:
+------+
| myCt |
+------+
| 3 |
+------+
48. Write a SQL query to display the staffno and working branch city for the staff who has the lowest
salary.
ANS:
SELECT s.staffno,b.city FROM Staff s, Branch b
WHERE s.branchno=b.branchno and s.salary in (SELECT min(salary) FROM Staff);
49. List the staff who work in the branch at ‘163 Main St’.
ANS:
SELECT staffNo, fName, IName, position FROM Staff
WHERE branchNo = (SELECT branchNo FROM Branch WHERE street = '163 Main St');
ANS 2:
SELECT staffNo, fName, IName, position FROM Staff s, Branch b
WHERE s.branchNo = b.branchNo and street = '163 Main St';
50. List all guests staying at the Grosvenor Hotel from April 1st to August 31st, 2004.
ANS:
SELECT * FROM Guest WHERE guestNo in (
SELECT guestNo FROM Booking
WHERE dateFrom >= date('2004-04-01') AND dateFrom <= date('2004-08-31')
AND hotelNo = (SELECT hotelNo FROM Hotel WHERE hotelName = 'Grosvenor'));
51. List all staff whose salary is greater than the average salary, and show by how much their salary is
greater than the average.
ANS:
SELECT staffNo, fName, LName, position, (salary - (SELECT AVG(salary) FROM Staff)) AS salDiff FROM
Staff WHERE salary > (SELECT AVG(salary) FROM Staff);
ANS 2:
SELECT staffNo, fName, LName, position, (salary-a.avg1) AS salDiff
FROM Staff s, (SELECT AVG(salary) as avg1 FROM Staff) a WHERE salary > a.avg1;
52. List the properties that are handled by staff who work in the branch at ‘163 Main St’.
ANS:
SELECT propertyNo, street, city, postcode, type, rooms, rent
FROM PropertyForRent WHERE staffNo IN (SELECT staffNo
FROM Staff WHERE branchNo = (SELECT branchNo
FROM Branch WHERE street = '163 Main St'));
53. Find all staff whose salary is larger than the salary of at least one member of staff at branch B003.
ANS:
SELECT staffNo, fName, IName, position, salary
FROM Staff WHERE salary > SOME (SELECT salary FROM Staff WHERE branchNo = 'B003');
54. Find all staff whose salary is larger than the salary of every member of staff at branch B003.
ANS:
SELECT staffNo, fName, IName, position, salary
FROM Staff WHERE salary > ALL (SELECT salary FROM Staff WHERE branchNo = 'B003');
55. Write a SQL query to show client names who didn’t give reviews (Viewing table).
ANS:
SELECT c.fname,c.lname FROM Client c
WHERE c.clientno NOT in (SELECT clientno FROM Viewing);
56. What is the most commonly booked room type for each hotel in London?
ANS:
select hotelname, type, max_ct
from
( select hotelno, max(ct) max_ct from
(select b.hotelno,type, count(*) as ct from Booking b, Room r where r.hotelno=b.hotelno and
r.roomno=b.roomno group by b.hotelno, type) t
group by hotelno ) n,
Hotel h,
(select b.hotelno,type, count(*) as ct from Booking b, Room r where r.hotelno=b.hotelno and
r.roomno=b.roomno group by b.hotelno, type) r
where n.hotelno=h.hotelno and r.hotelno=n.hotelno and h.city='London'and max_ct=ct;
57. Write a SQL query to display the cheapest product name (A_Products table) and its price.
ANS:
SELECT name, sell_price FROM A_Products
WHERE sell_price = (SELECT min(sell_price) FROM A_Products);
(INNSER) JOIN
58. How many rows and columns will be generated from the following SQL query?
SELECT * FROM A_Students, A_Courses;
ANS:
6 columns and 8 rows
59. Write a SQL statement to show the product names provided by vendor “James”.
(refer to A_Products, A_Vendors tables)
ANS:
SELECT p.name FROM A_Products p, A_Vendors v WHERE v.name='James' and p.V_Id=v.V_Id;
60. Write a SQL query to show the first name who works at London and has salary higher than 10000.
ANS:
SELECT fname FROM Branch b, Staff s
WHERE b.branchno=s.branchno and b.city='London' and s.salary > 10000;
61. List the names of all clients who have viewed a property, along with any comments supplied.
ANS:
SELECT c.clientNo, fName, IName, propertyNo, comment
FROM Client c, Viewing v WHERE c.clientNo = v.clientNo;
62. Write a SQL query to list employee names (first name, last name) and their Supervisor names (first
name, last name). The output header must clearly indicates who is employee and Supervisor. (refer
to A_Employee table)
ANS:
SELECT e.fname as E_fname, e.lname as E_lname, m.fname as M_fname, m.lname as M_lname
FROM A_Employee e, A_Employee m WHERE e.super_ssn=m.ssn;
63. For each branch office, list the staff numbers and names of staff who manage properties and the
properties that they manage.
ANS:
SELECT s.branchNo, s.staffNo, fName, IName, propertyNo
FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo
ORDER BY s.branchNo, s.staffNo, propertyNo;
64. For each branch, list the staff numbers and names of staff who manage properties, including the city
in which the branch is located and the properties that the staff manage.
ANS:
SELECT b.branchNo, b.city, s.staffNo, fName, IName, propertyNo
FROM Branch b, Staff s, PropertyForRent p
WHERE b.branchNo = s.branchNo AND s.staffNo = p.staffNo
ORDER BY b.branchNo, s.staffNo, propertyNo;
65. Display the product names and the comments that customer BJ1 gave.
(refer to A_Cusomters, A_Reviews, A_Products)
ANS:
SELECT p.name, comments FROM A_Customers c, A_Reviews r, A_Products p
WHERE c.id=r.c_id and p.id=r.p_id and c.name='BJ1' ;
66. List the guestname, hotelname, number of days stayed, and the total amount needed to pay to the
hotel for every guest.
ANS:
select guestname, hotelname, datediff(dateto,datefrom), sum(datediff(dateto,datefrom)*price)
from Guest g, Hotel h, Room r, Booking b
where h.hotelno=b.hotelno and r.roomno=b.roomno and g.guestno=b.guestno
and dateto is not null group by guestname,hotelname;
67. Find the number of properties handled by each staff member, along with the branch number of the
member of staff.
ANS:
SELECT s.branchNo, s.staffNo, COUNT(*) AS myCount
FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo
GROUP BY s.branchNo, s.staffNo ORDER BY s.branchNo, s.staffNo;
68. Find all staff who work in a London branch office.
ANS:
SELECT staffNo, fName, IName, position
FROM Staff s WHERE EXISTS (SELECT * FROM Branch b
WHERE s.branchNo = b.branchNo AND city = 'London');
ANS 2:
SELECT staffNo, fName, IName, position
FROM Staff s, Branch b WHERE s.branFchNo = b.branchNo AND city = 'London';
OUTER JOIN:
69. List all branch offices and any properties that are in the same city.
ANS:
SELECT b.*, p.* FROM Branch1 b LEFT JOIN PropertyForRent1 p ON b.bCity = p.pCity;
70. List all properties and any branch offices that are in the same city.
ANS:
SELECT b.*, p.* FROM Branch1 b RIGHT JOIN PropertyForRent1 p ON b.bCity = p.pCity;
71. List the branch offices and properties that are in the same city along with any unmatched branches
or properties.
ANS:
SELECT b.*, p.* FROM Branch1 b FULL JOIN PropertyForRent1 p ON b.bCity = p.pCity;
72. How many rows will be generated from the following SQL statement:
SELECT * FROM Staff s RIGHT JOIN Branch b ON s.branchno=b.branchno;
ANS:
8 rows
73. Write a SQL query to display all customer names (A_Customers) and their number of Reviews
(A_Reviews). If a customer didn’t give review, his/her number of review will be 0. The output should
have customer name in alphabetic order from A to Z.
ANS:
SELECT c.name, count(r.c_id) FROM A_Customers c
LEFT JOIN A_Reviews r on r.c_id= c.id group by c.id order by c.name ASC;
INSERT:
78. Insert a new row into the Staff table supplying data for all columns.
ANS:
INSERT INTO Staff VALUES
('SG16', 'Alan', 'Brown', 'Assistant', 'M', DATE '1957-05-25', 8300, 'B003');
79. Insert a new row into the Staff table supplying data for all mandatory columns: staffNo, fName,
IName, position, salary, and branchNo.
ANS:
INSERT INTO Staff (staffNo, fName, IName, position, salary, branchNo)
VALUES ('SG44', 'Anne', 'Jones', 'Assistant', 8100, 'B003');
ANS 2:
INSERT INTO Staff VALUES ('SG44’, 'Anne’, 'Jones’, 'Assistant’, NULL, NULL, 8100, 'B003’);
80. Assume that there is a table StaffPropCount that contains the names of staff and the number of
properties they manage: StaffPropCount(staffNo, fName, IName, propCount)
Write a SQL to populate the StaffPropCount table using details from the Staff and PropertyForRent
tables.
ANS:
INSERT INTO StaffPropCount (SELECT s.staffNo, fName, IName, COUNT(*)
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo GROUP BY s.staffNo, fName, IName)
UNION
(SELECT staffNo, fName, IName, 0 FROM Staff s
WHERE NOT EXISTS (SELECT * FROM PropertyForRent p WHERE p.staffNo = s.staffNo));
UPDATE:
81. Give all staff a 3% pay increase.
ANS:
UPDATE Staff SET salary = salary*1.03;
82. Give all Managers a 5% pay increase. (Refer to Staff table)
ANS:
UPDATE Staff SET salary = salary*1.05 WHERE position = 'Manager';
83. Promote David Ford (staffNo = ‘SG14’) to Manager and change his salary to $18,000.
(Refer to Staff table)
ANS:
UPDATE Staff SET position = 'Manager', salary = 18000 WHERE staffNo = 'SG14';
DELETE:
84. Delete all viewings that relate to property PG4.
ANS:
DELETE FROM Viewing WHERE propertyNo = 'PG4';
85. Delete all rows from the Viewing table.
ANS:
DELETE FROM Viewing;
86. Delete the record that has the NULL value in QTY field in the A_Sales table
ANS:
DELETE FROM A_Sales WHERE QTY is null;
87. Create the Staff table with proper data type for each field and staffno is the primary key, branchno
is a foreign key reference to the primary key branchno in the Branch table. All the fields cannot be
NULL.
ANS:
CREATE TABLE Staff (staffno varchar(5) not null, fName varchar(15) not null, lName varchar(15) not
null, position varchar(25) not null, Sex char(1) not null, DOB date not null, salary decimal(8,2) not
null, branchno varchar(8) not null, primary key (staffno), foreign key (branchno) references
Branch(branchno));
ALTER:
88. Add a new column TEL varchar(20) to the staff table;
ANS:
ALTER TABLE Staff ADD TEL varchar(25);
89. Change the Staff table by removing the default of ‘Assistant’ for the position column and setting the
default for the sex column to female (‘F’).
ANS:
ALTER TABLE Staff ALTER position DROP DEFAULT;
ALTER TABLE Staff ALTER sex SET DEFAULT 'F';
VIEW:
90. Create a view vTest listing all double or family rooms with a price below 40.00 per night, in
ascending order of price.
ANS:
CREATE VIEW vTest as SELECT * FROM Room
WHERE price < 40 AND type IN ('double', 'family') ORDER BY price asc;
91. Create a view vTest to list the number of rooms in each hotel.
ANS:
SELECT h.hotelname, COUNT(r.roomNo) AS count
FROM Room r, Hotel h where r.hotelno=h.hotelno GROUP BY h.hotelno;
92. Create a view vTest to list the hotel name and the total number of rooms with price per room below
40.00 per night.
ANS:
CREATE VIEW vTest as SELECT h.hotelname,count(*) FROM Hotel h, Room r
WHERE h.hotelno=r.hotelno and r.price < 40 group by h.hotelno;
93. Create a view so that the manager at branch B003 can see the details only for staff who work in his
or her branch office.
ANS:
CREATE VIEW Manager3Staff AS SELECT * FROM Staff WHERE branchNo = 'B003';
94. Create a view of the staff details at branch B003 that excludes salary information, so that only
managers can access the salary details for staff who work at their branch.
ANS:
CREATE VIEW Staff3 AS SELECT staffNo, fName, IName, position, sex
FROM Staff WHERE branchNo = 'B003';
95. Create a view vTest to show the first name and the working city for staff who was born after January
first 1960.
ANS:
SELECT fname, city FROM Staff s, Branch b
WHERE s.branchno=b.branchno and birthday > '1960-01-01';
96. Create a view vTest to find the total revenue per night for each hotel and the revenue is higher than
85 dollars. Assume all rooms are booked. Your output needs to show the hotel name and the
amount of revenue.
ANS:
SELECT h.hotelno, SUM(price) as revenue FROM Hotel h, Room r
WHERE h.hotelno=r.hotelno group by h.hotelno having revenue > 85;
97. Create a view of staff who manage properties for rent, which includes the branch number they work
at, their staff number, and the number of properties they manage
ANS:
CREATE VIEW StaffPropCnt (branchNo, staffNo, cnt)
AS SELECT s.branchNo, s.staffNo, COUNT(*)
FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo GROUP BY s.branchNo, s.staffNo;
GRANT, REVOKE:
98. Give the user with authorization identifier Manager all privileges on the Staff table.
ANS:
GRANT ALL PRIVILEGES ON Staff TO Manager WITH GRANT OPTION;
99. Give users Personnel and Director the privileges SELECT and UPDATE on column salary of the Staff
table.
ANS:
GRANT SELECT, UPDATE (salary) ON Staff TO Personnel, Director;
100. Give user xyz from IP ’10.20.30.40’ the privileges SELECT on column salary of the Staff table.
ANS:
GRANT SELECT (salary) ON test TO 'xyz'@'10.20.30.40';
101. Remove user xyz’s SELECT privilege from test the test table.
ANS:
REVOKE SELECT on test from xyz;
102. Remove user xyz’s all privileges from test the test table.
ANS:
REVOKE ALL PRIVILEGES on test from xyz;
DROP:
103. Remove a table Data from the database.
ANS:
DROP TABLE table Data;
104. Remove a view vData from the database.
ANS:
DROP VIEW vData;
105. Remove a stored procedure pTest() from the database.
ANS:
DROP procedure pTest;
106. Remove a stored function fTest() from the database.
ANS:
DROP function fTest;
107. Remove a user xyz from the database.
ANS:
DROP USER xyz;
STORED ROUTINES:
120. Write the SQL statement to run a stored function named fMaxSalary()which will return the
staff’s highest salary.
ANS:
SELECT fMaxSalary();
121. Write a stored function named fMaxSalary() which will return the staff’s highest salary.
ANS:
DELIMITER $$
CREATE FUNCTION fMaxSalary() RETURNS float
BEGIN
DECLARE maxSalary float ;
SELECT max(salary) into maxSalary FROM dreamhome.Staff;
RETURN maxSalary ;
END $$
DELIMITER ;
122. Write a stored function named fMaxSalary(bno) which will return the staff’s highest salary
for a given branch no bno.
ANS:
DELIMITER $$
CREATE FUNCTION fMaxSalary(bno varchar(10)) RETURNS float
BEGIN
DECLARE maxSalary float ;
SELECT max(salary) into maxSalary FROM dreamhome.Staff
WHERE branchno=bno;
RETURN maxSalary ;
END $$
DELIMITER ;
123. Write a stored function named fMaxSalary(n) which will return the staff’s highest salary for a
given input that is a partial string in the first name field.
ANS:
DELIMITER $$
CREATE FUNCTION fMaxSalary(n varchar(10)) RETURNS float
BEGIN
DECLARE maxSalary float ;
SELECT max(salary) into maxSalary FROM dreamhome.Staff
WHERE fname like concat('%',n,'%');
RETURN maxSalary ;
END $$
DELIMITER ;
124. Write the SQL statement to run a stored procedure named pGetNames()which will display the
Staff’s first name and last name who work at branch located at a given city ‘London’.
ANS: call pGetNames('London');
125. Write a stored procedure named pGetNames (bcity) which will display the Staff’s first name and last
name who work at branch located at a given city bcity.
ANS:
DELIMITER $$
CREATE PROCEDURE pGetNames
(IN bcity VARCHAR(12))
BEGIN
SELECT fname,lname FROM dreamhome.Staff s, dreamhome.Branch b
WHERE city= bcity and b.branchno=s.branchno;
END $$
DELIMITER ;
126. Write a stored procedure named pGetNames (bcity) which will display the Staff’s first name and last
name who work at branch located at a given city bcity. If the bcity is empty ‘’, please print a message saying
“The input city cannot be empty.”
call pGetNames(''); call pGetNames('London');
+-----------------------------+ +-------+-------+
| message | | fname | lname |
+-----------------------------+ +-------+-------+
| Input city cannot be empty. | | John | White |
+-----------------------------+ | Julie | Lee |
+-------+-------+
ANS:
DELIMITER $$
CREATE PROCEDURE pGetNames
(IN bcity VARCHAR(12))
BEGIN
if (bcity='') THEN
SELECT 'Input city cannot be empty.' as message;
ELSE
SELECT fname,lname FROM dreamhome.Staff s, dreamhome.Branch b
WHERE city= bcity and b.branchno=s.branchno;
END IF;
END $$
DELIMITER ;
Table of Contents
What is API? 4
HTTP - Fundamentals 9
What is an Cookies? 10
What is Authentication? 10
API stands for the Application Programming Interface, They are basically a collection of functions and
procedures which allows us to communicate two application or library.
For example, It like a connector as seen in the picture. All data connects to our organization through API.
In one line, API is its an interface between different software programs or service.
Simple Examples is,
Suppose you go to a restaurant.
API is the messenger that takes your order(waiter) and tells the system(kitchen) what to do (to prepare food)
and in return gives back the response you asked for (waiter returns with the ordered food).
Source - Quora. https://www.quora.com/What-is-an-API
Type of APIs :-
What is API Testing?
API testing is testing that APIs and its integration with the services.
It is one of the most challenging type of testing, If we miss the certain cases in API Testing that can cause a
very big problem in production after full integration and it will hard to debug in production environment..
The REST architectural style describes six constraints. These constraints, put on the architecture, were initially
communicated by Roy Fielding in his doctoral dissertation and defines the basis of RESTful-style.
1. Uniform Interface
2. Stateless
3. Cacheable
4. Client-Server
5. Layered System
6. Code on Demand
Uniform Interface
The uniform interface constraint defines the interface between clients and servers.
In other terms,
First constraint of the REST API states that the Client and server has to communicate and agree to certain
rules based on resources(they should communicate with same resource like json, xml, html , txt) and with
proper encoding like UTF-8 extra.
Another point they should communicate with the Self-descriptive Messages e.g Use the same MIME types.
Stateless
APIs in REST are stateless and Client and server doesn’t worry about the state of the request or response..
Cacheable
According to the World Wide Web, clients can cache responses. Responses should therefore, implicitly or
explicitly, define themselves as cacheable. Its upto server when they want the cache to expired etc.
Client-Server
Client and Server are two different entity, It means that servers and clients may also be replaced and
developed independently, as long as the interface is not altered.
Layered System.
It means that the between client and server there can be any number of layered systems it does not matter.
Code on Demand
Server can store the Code or logic to themselves and transfer it whenever needed rather client side logic.
If any API fulfill all the constraints then we can it REST API.
Difference between REST API vs SOAP API.
We have already discussed REST API , Lets now Learn what is SOAP API.
SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs that run on disparate
operating systems or services like frontend or backend to communicate using Hypertext Transfer Protocol
(HTTP) and its Extensible Markup Language (XML).
SOAP uses WSDL is an XML format for describing network services as a set of endpoints operating on
messages containing either document-oriented or procedure-oriented information.
● Validate the keys with the Min. and Max range of APIs (e.g maximum and minimum length)
● Have a Testcase to do XML,JSON Schema validation.
● Keys verification. If we have JSON, XML apis we should verify it's that all the keys are coming.
● Verify that how the APIs error codes handled.
● Right now, Internet uses millions of APIs and they should be tested thoroughly.
Above image shows the architecture of an application and notice that API Testing is important part..
Now…
HTTP - Fundamentals
HTTP is an application layer protocol designed within the framework of the Internet protocol suite.
There is Client which perform a request resource which can be HTMLPage, file extra from Server and server
perform the response to the client back using the same protocol known as HTTP.
HTTP is a stateless protocol. In other words, the current request does not know what has been done in the
previous requests.
What is an Cookies?
Cookies are usually small text files, given ID tags that are stored on your computer's browser directory or
program data subfolders.
What is Authentication?
Authentication is a process of presenting your credentials like username, password or another secret key to
the system and the system to validate your credentials or you. In the API terms Authentication is used to
protect the content over web mean only a valid user with valid credentials can access that API endpoint.
These credentials tell the system about who you are. Which enables the system to ensures and confirms a
user’s identity. Here system can be anything, it can be a computer, phone, bank or any physical office
premises.
OAuth- Authentication protocol that allows you to approve one application interacting with another on your
behalf without giving away your password.
E.g OAuth 1, 2.
Just for more information, URL can be broken down into the further chunks like protocol, host , post and query
params. More discussion is out of scope for URL
.
HTTP POST Method Explained -
Now we have a HTTP Methods knowledge lets understand what are Cookie and authentication.
Before that take a look into the example api that can available freely.
https://api.chucknorris.io/jokes/random
● Runscope.com
● Postman CI/CD
● Katalon using CI/CD
● SoapUI CI/CD
● Rest Assured CI/CD
It is an API Testing tool used by developers and Testers to perform API Testing with lots of different features
like Global variables, mock request, Environment and monitoring of APIs.
You can learn more about a postman in my full Video lecture series here. Download and install it.
P.S – This article assumes that you have some experience with Postman. If not please go through my previous
tutorials.
What is API? 4
HTTP - Fundamentals 9
What is an Cookies? 10
What is Authentication? 10
API stands for the Application Programming Interface, They are basically a collection of functions and
procedures which allows us to communicate two application or library.
For example, It like a connector as seen in the picture. All data connects to our organization through API.
In one line, API is its an interface between different software programs or service.
Simple Examples is,
Suppose you go to a restaurant.
API is the messenger that takes your order(waiter) and tells the system(kitchen) what to do (to prepare food)
and in return gives back the response you asked for (waiter returns with the ordered food).
Source - Quora. https://www.quora.com/What-is-an-API
Type of APIs :-
What is API Testing?
API testing is testing that APIs and its integration with the services.
It is one of the most challenging type of testing, If we miss the certain cases in API Testing that can cause a
very big problem in production after full integration and it will hard to debug in production environment..
The REST architectural style describes six constraints. These constraints, put on the architecture, were initially
communicated by Roy Fielding in his doctoral dissertation and defines the basis of RESTful-style.
1. Uniform Interface
2. Stateless
3. Cacheable
4. Client-Server
5. Layered System
6. Code on Demand
Uniform Interface
The uniform interface constraint defines the interface between clients and servers.
In other terms,
First constraint of the REST API states that the Client and server has to communicate and agree to certain
rules based on resources(they should communicate with same resource like json, xml, html , txt) and with
proper encoding like UTF-8 extra.
Another point they should communicate with the Self-descriptive Messages e.g Use the same MIME types.
Stateless
APIs in REST are stateless and Client and server doesn’t worry about the state of the request or response..
Cacheable
According to the World Wide Web, clients can cache responses. Responses should therefore, implicitly or
explicitly, define themselves as cacheable. Its upto server when they want the cache to expired etc.
Client-Server
Client and Server are two different entity, It means that servers and clients may also be replaced and
developed independently, as long as the interface is not altered.
Layered System.
It means that the between client and server there can be any number of layered systems it does not matter.
Code on Demand
Server can store the Code or logic to themselves and transfer it whenever needed rather client side logic.
If any API fulfill all the constraints then we can it REST API.
Difference between REST API vs SOAP API.
We have already discussed REST API , Lets now Learn what is SOAP API.
SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs that run on disparate
operating systems or services like frontend or backend to communicate using Hypertext Transfer Protocol
(HTTP) and its Extensible Markup Language (XML).
SOAP uses WSDL is an XML format for describing network services as a set of endpoints operating on
messages containing either document-oriented or procedure-oriented information.
● Validate the keys with the Min. and Max range of APIs (e.g maximum and minimum length)
● Have a Testcase to do XML,JSON Schema validation.
● Keys verification. If we have JSON, XML apis we should verify it's that all the keys are coming.
● Verify that how the APIs error codes handled.
● Right now, Internet uses millions of APIs and they should be tested thoroughly.
Above image shows the architecture of an application and notice that API Testing is important part..
Now…
HTTP - Fundamentals
HTTP is an application layer protocol designed within the framework of the Internet protocol suite.
There is Client which perform a request resource which can be HTMLPage, file extra from Server and server
perform the response to the client back using the same protocol known as HTTP.
HTTP is a stateless protocol. In other words, the current request does not know what has been done in the
previous requests.
What is an Cookies?
Cookies are usually small text files, given ID tags that are stored on your computer's browser directory or
program data subfolders.
What is Authentication?
Authentication is a process of presenting your credentials like username, password or another secret key to
the system and the system to validate your credentials or you. In the API terms Authentication is used to
protect the content over web mean only a valid user with valid credentials can access that API endpoint.
These credentials tell the system about who you are. Which enables the system to ensures and confirms a
user’s identity. Here system can be anything, it can be a computer, phone, bank or any physical office
premises.
OAuth- Authentication protocol that allows you to approve one application interacting with another on your
behalf without giving away your password.
E.g OAuth 1, 2.
Just for more information, URL can be broken down into the further chunks like protocol, host , post and query
params. More discussion is out of scope for URL
.
HTTP POST Method Explained -
Now we have a HTTP Methods knowledge lets understand what are Cookie and authentication.
Before that take a look into the example api that can available freely.
https://api.chucknorris.io/jokes/random
● Runscope.com
● Postman CI/CD
● Katalon using CI/CD
● SoapUI CI/CD
● Rest Assured CI/CD
It is an API Testing tool used by developers and Testers to perform API Testing with lots of different features
like Global variables, mock request, Environment and monitoring of APIs.
You can learn more about a postman in my full Video lecture series here. Download and install it.
P.S – This article assumes that you have some experience with Postman. If not please go through my previous
tutorials.
* But I have decided to open-source it and make it available for everyone who wants to learn SQA
Fundamental, Database Concepts, SCRUM Fundamentals, OOP Basics, Automation concepts like
selenium, JMeter, and API.
I added everything that you will need as an SQA Engineer Manual or Automation. The ideal use case of
this document is that you print it and keep it next to you while you are learning and practicing on your
computer.
Please approach me if you see any mistake or feel any wrong concept.
If anyone wants to get Training on Manual or Automation tools just ping me on my contact.
Enjoy! Cheers,
umar.it.376@outlook
[email protected]
www.linkedin.com/in/muhammad-
umar-arshad-005ba3139
2 Why SDLC?
Here, are prime reasons why SDLC is important for developing a software system.
3.2 Design:
In this phase the software design is prepared from the requirement
specifications which were studied in the first phase. System Design helps in specifying
hardware and system requirements and also helps in defining overall system
architecture.
In this phase the QA Engineers comes up with the Test strategy, where they mention
what to test, how to test.
3.3 Implementation / Coding:
Upon receiving system design documents, the work is divided in modules/units and
actual coding is started. Since, in this phase the code is produced so it is the main focus
for the developer. This is the longest phase of SDLC. In this phase the QA Engineers
comes up with the Test Environment setup and test Case Documentation.
3.4 Testing:
After the code is developed it is tested against the requirements to make sure that the
product is actually solving the needs addressed and gathered during the requirements
phase. During this phase all types of like unit testing, integration testing, Smoke Testing,
functional testing, Sanity Testing, system testing, acceptance testing is done as well
as non-functional testing are also done.
3.5 Deployment: After successful testing the product is delivered / deployed to the customer
for their use.
As soon as the product is given to the customers, they will first do the beta testing/User
Acceptance Testing. If any changes are required or if any bugs are caught, then they will
report it to the engineering team. Once those changes are made or the bugs are fixed
then the final deployment will happen.
4 Waterfall model
Waterfall model works well for smaller projects where requirements are very well
understood.
The waterfall is a widely accepted SDLC model. In this approach, the whole process of the
software development is divided into various phases. In this SDLC model, the outcome of one
phase acts as the input for the next phase.
This SDLC model is documentation-intensive, with earlier phases documenting what need be
performed in the subsequent phases.
5 Incremental Model
The incremental model is not a separate model. It is essentially a series of waterfall cycles. The
requirements are divided into groups at the start of the project. For each group, the SDLC
model is followed to develop software. The SDLC process is repeated, with each release adding
more functionality until all requirements are met. In this method, every cycle act as the
maintenance phase for the previous software release. Modification to the incremental model
allows development cycles to overlap. After that subsequent cycle may begin before the
previous cycle is complete.
6 V-Model
In this type of SDLC model testing and the development, the phase is planned in parallel. So,
there are verification phases on the side and the validation phase on the other side. V-Model
joins by Coding phase.
8 Spiral Model
The spiral model is a risk-driven process model. This SDLC model helps the team to adopt
elements of one or more process models like a waterfall, incremental, waterfall, etc.
This model adopts the best features of the prototyping model and the waterfall model. The
spiral methodology is a combination of rapid prototyping and concurrency in design and
development activities.
9 Prototyping Model
If you were testing this Operating system, you would realize that defects are likely to be
found in multi-tasking activity and need to be tested thoroughly which brings us to our
next principal Defect Clustering.
Early Testing - Testing should start as early as possible in the Software Development Life
Cycle. So that any defects in the requirements or design phase are captured in early
stages.
Defect Clustering which states that a small number of modules contain most of the
defects detected. If the same tests are repeated over and over again, eventually the
same test cases will no longer find new bugs.
Repetitive use of the same pesticide mix to eradicate insects during farming will over
time lead to the insects developing resistance to the pesticide Thereby ineffective of
pesticides on insects. The same applies to software testing. If the same set of repetitive
tests are conducted, the method will be useless for discovering new defects. To
overcome this, the test cases need to be regularly reviewed & revised, adding new &
different test cases to help find more defects.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
7
2.6 Testing is context depending
Testing is context dependent which basically means that the way you test an e-
commerce site will be different from the way you test a commercial off the shelf
application. All the developed software’s are not identical. You might use a different
approach, methodologies, techniques, and types of testing depending upon the
application type.
It is possible that software which is 99% bug-free is still unusable. This can be the case if
the system is tested thoroughly for the wrong requirement. The absence of Error is a
Fallacy i.e. Finding and fixing defects does not help if the system build is unusable and
does not fulfill the user's needs & requirements.
• Plan - Organization should plan and establish the process related objectives and
determine the processes that are required to deliver a high-Quality end product.
• Do - Development and testing of Processes and also "do" changes in the processes
• Check - Monitoring of processes, modify the processes, and check whether it meets the
predetermined objectives
Quality Control:
Test cases are the set of positive and negative executable steps of a test scenario, A test
case is a set of actions performed on a system to determine if it satisfies software
requirements and functions correctly.
An environment configured for testing. Test bed consists of hardware, software, network
configuration, an application under test, other related software.
Test Environment is the combination of hardware and software on which Test Team
performs testing. Example:
Test data is the data that is used by the testers to run the test cases. Whilst running the test
cases, testers need to enter some input data. To do so, testers prepare test data. It can be
prepared manually and also by using tools.
Test Harness in Software Testing is a collection of stubs, drivers and other supporting tools
required to automate test execution. Test harness executes tests by using a test library and
generates test reports. Test harness contains all the information needed to compile and run
a test like test cases, target deployment port (TDP), source file under test, stubs, etc.
Test Closure is the note prepared before test team formally completes the testing process.
This note contains the total no. of test cases, total no. of test cases executed, total no. of
defects found, total no. of defects fixed, total no. of bugs not fixed, total no of bugs rejected
etc.,
In software testing Risks are the possible problems that might endanger the objectives of
the project stakeholders. It is the possibility of a negative or undesirable outcome. A risk is
something that has not happened yet and it may never happen; it is a potential problem.
12. What are the tasks of Test Closure activities in Software Testing?
Test Artifacts handover: Tests and test environments should be handed over to those
responsible for maintenance testing. Known defects accepted or deferred should be
documented and communicated to those who will use and support the use of the system.
Lessons learned: Analyzing lessons learned to determine changes needed for future
releases and projects. In retrospective meetings, plans are established to ensure that good
practices can be repeated and poor practices are not repeated.
Result: Archiving results, logs, reports, and other documents and work products in the
CMS (configuration management system).
1. Test Strategy
2. Test Plan
3. Effort Estimation Report
4. Test Scenarios
5. Test Cases/Scripts
6. Test Data
7. Requirement Traceability Matrix (RTM)
8. Defect Report/Bug Report
9. Test Execution Report
10. Graphs and Metrics
11. Test summary report
12. Test incident report
13. Test closure report
14. Release Note
15. Installation/configuration guide
16. User guide
17. Test status report
18. Weekly status report (Project manager to client)
Requirements Traceability Matrix (RTM) is used to trace the requirements to the tests
that are needed to verify whether the requirements are fulfilled. Requirement
Traceability Matrix AKA Traceability Matrix or Cross Reference Matrix.
• Requirement ID
• Requirement Type and Description
• Test Cases with Status
In Software Engineering, traceability matrix can be divided into three major components as
mentioned below:
• Forward traceability: This matrix is used to check whether the project progresses in the
forward desired direction and for the right product. It maps requirements to test cases.
• Backward or reverse traceability: It is used to ensure whether the current product
remains on the right track. It maps test cases to requirements.
• Bi-directional traceability (Forward + Backward): This traceability matrix ensures that all
requirements are covered by test cases. It analyzes the impact of a change in
requirements affected by the Defect in a work product and vice versa.
"Verify Login, when correct ID and Password is entered, it should log in successfully"
Step 2: Identify the Technical Requirement that this test case is verifying. For our test case, the
technical requirement is T94 is being verified.
Step 4: Identify the Business Requirement for which this TR (Technical Requirement-T94) is
defined
Step 6: Do above for all Test Cases. Later Extract the First 3 Columns from your Test Suite. RTM
in testing is Ready!
Test Coverage states which requirements of the customers are to be verified when the
testing phase starts. Test Coverage is a term that determines whether the test cases are
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
16
written and executed to ensure to test the software application completely, in such a
way that minimal or NIL defects are reported.
White Box Testing is also called as Glass Box, Clear Box, and Structural Testing. It is based on
applications internal code structure. In white-box testing, an internal perspective of the
system, as well as programming skills, are used to design test cases. This testing usually was
done at the unit level.
Black Box Testing is a software testing method in which testers evaluate the functionality of the
software under test without looking at the internal code structure. This can be applied to every
level of software testing such as Unit, Integration, System and Acceptance Testing.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
18
3. What is Grey Box Testing?
Grey box is the combination of both White Box and Black Box Testing. The tester who works on
this type of testing needs to have access to design documents. This helps to create better test
cases in this process.
Alpha testing is done by the in-house developers (who developed the software) and testers.
Sometimes alpha testing is done by the client or outsourcing team with the presence of
developers or testers.
• In the first phase of alpha testing, the software is tested by in-house developers. They
use debugger software. The goal is to catch bugs quickly.
• In the second phase of alpha testing, the software is handed over to the software QA
staff, for additional testing in an environment that is similar to the intended use.
Beta testing is done by a limited number of end users before delivery. Usually, it is done in
the client place.
Gamma testing is done when the software is ready for release with specified requirements.
It is done at the client place. It is done directly by skipping all the in-house testing activities.
In simple words, what the system actually does is functional testing. To verify that each
function of the software application behaves as specified in the requirement document.
Testing all the functionalities by providing appropriate input to verify whether the actual
output is matching the expected output or not. It falls within the scope of black box testing
and the testers need not concern about the source code of the application.
Unit Testing is also called as Module Testing or Component Testing. It is done to check
whether the individual unit or module of the source code is working properly. It is done
by the developers in the developer’s environment.
Integration Testing is the process of testing the interface between the two software
units. Integration testing is done by three ways. Big Bang Approach, Top-Down
Approach, Bottom-Up Approach.
Testing the fully integrated application to evaluate the system’s compliance with its
specified requirements is called System Testing End to End testing. Verifying the
completed system to ensure that the application works as intended or not.
Smoke Testing is done to make sure if the build we received from the development
team is testable or not. It is also called as “Day 0” check. It is done at the “build level”. It
helps not to waste the testing time to simply testing the whole application when the key
features don’t work or the key bugs have not been fixed yet.
Sanity Testing is done during the release phase to check for the main functionalities of
the application without going deeper. It is also called as a subset of Regression testing. It
is done at the “release level”. We perform sanity testing when we don’t have enough
time for regression testing.
Retesting is done to make sure that the tests cases which failed in last execution are
passed after the defects are fixed. Retesting is carried out based on the defect fixes. In
Retesting, the cases which are failed earlier can be included to check if the functionality
failure in an earlier build.
Usually, this process will be carried out by domain experts. They perform testing just by
exploring the functionalities of the application without having the knowledge of the
requirements.
Perform abnormal action on the application deliberately in order to verify the stability of
the application.
Combining all the modules once and verifying the functionality after completion of
individual module testing.
Testing takes place from top to bottom. High-level modules are tested first and then low-
level modules and finally integrating the low-level modules to a high level to ensure the
system is working as intended. Stubs are used as a temporary module if a module is not
ready for integration testing.
It is a reciprocate of the Top-Down Approach. Testing takes place from bottom to up.
Lowest level modules are tested first and then high-level modules and finally integrating the
high-level modules to a low level to ensure the system is working as intended. Drivers are
used as a temporary module for integration testing.
It is also known as pre-production testing. This is done by the end users along with the
testers to validate the functionality of the application. After successful acceptance
testing. Formal testing conducted to determine whether an application is developed as per
the requirement. It allows the customer to accept or reject the application. Types of
acceptance testing are Alpha, Beta & Gamma.
Negative Testing: It is to determine what system not supposed to do. It helps to find
the defects from the software.
In simple words, how well the system performs is non-functionality testing. Non-
functional testing refers to various aspects of the software such as performance, load,
stress, scalability, security, compatibility etc., Main focus is to improve the user
experience on how fast the system responds to a request.
This type of testing determines or validates the speed, scalability, and/or stability
characteristics of the system or application under test. Performance is concerned with
achieving response times, throughput, and resource-utilization levels that meet the
performance objectives for the project or product.
It is to verify the behavior of the system once the load increases more than its design
expectations.
Concurrency testing means accessing the application at the same time by multiple users
to ensure the stability of the system. This is mainly used to identify deadlock issues.
Graphical User Interface Testing is to test the interface between the application and the
end user.
Recovery testing is performed in order to determine how quickly the system can recover
after the system crash or hardware failure. It comes under the type of non-functional
testing.
Identify the modules or functionalities which are most likely cause failures and then
testing those functionalities.
To verify whether the application is user-friendly or not and was comfortably used by an
end user or not. The main focus in this testing is to check whether the end user can
understand and operate the application easily or not. An application should be self-
exploratory and must not require training to operate it.
Security testing is a process to determine whether the system protects data and
maintains functionality as intended.
Running a system at high load for a prolonged period of time to identify the
performance problems is called Soak or Endurance Testing.
Fuzz testing is used to identify coding errors and security loopholes in an application. By
inputting massive amount of random data to the system in an attempt to make it crash
to identify if anything breaks in the application.
Ad-hoc testing is quite opposite to the formal testing. It is an informal testing type. In
Adhoc testing, testers randomly test the application without following any documents
and test design techniques. This testing is primarily performed if the knowledge of
testers in the application under test is very high. Testers randomly test the application
without any test cases or any business requirement document.
Interface testing is performed to evaluate whether two intended modules pass data and
communicate correctly to one another.
Perform testing on the application continuously for long period of time in order to verify
the stability of the application.
Inspection is a formal meeting lead by a trained moderator, certainly not by the author.
The document under inspection is prepared and checked thoroughly by the reviewers
before the meeting. In the inspection meeting, the defects found are logged and shared
with the author for appropriate actions. Post inspection, a formal follow-up process is
used to ensure a timely and corrective action.
The variation between the actual results and expected results is known as a defect. If a
developer finds an issue and corrects it by himself in the development phase, then it’s
called a defect.
If testers find any mismatch in the application/system in testing phase, then they call it
as Bug.
Once the product is deployed and customers find any issues then they call the product
as a failure product. After release, if an end user finds an issue, then that particular issue
is called as a failure.
Bug/Defect severity can be defined as the impact of the bug on customer’s business. It
can be Critical, Major or Minor. In simple words, how much effect will be there on the
system because of a particular defect.
Defect priority can be defined as how soon the defect should be fixed. It gives the order
in which a defect should be resolved. Developers decide which defect they should take
High Priority & High Severity: Submit button is not working on a login page and
customers are unable to login to the application
Low Priority & High Severity: key feature failed but there’s no impact on customer
business, e.g., calculation fault in yearly report which end user won’t use on daily basis.
High Priority & Low Severity: Spelling mistake of a company name on the homepage
Low Priority & Low Severity: FAQ page takes a long time to load
A critical bug is a show stopper which means a large piece of functionality or major
system component is completely broken and there is no workaround to move further.
For example, Due to a bug in one module, we cannot test the other modules because
that blocker bug has blocked other modules. Bugs which affect the customers’ business
are considered as critical.
Example:
1. “Sign In” button is not working on Gmail App and Gmail users are blocked to login to
their accounts.
2. An error message pops up when a customer clicks on transfer money button in a
Banking website.
Entry criteria is a set of conditions that permits a task to perform, or in absence of any of
these conditions, the task cannot be performed.
• Management Review:
• Audit:
An audit is the examination of the work products and related information to assesses
whether the standard process was followed or not.
Boundary value analysis (BVA) is based on testing the boundary values of valid and invalid
partitions. Every partition has its maximum and minimum values and these maximum and
minimum values are the boundary values of a partition.
Example:
Input condition is valid between 1 to 10
Decision Table is a Cause-Effect Table. This test technique is appropriate for functionalities
which has logical relationships between inputs (if-else logic). In Decision table technique, we
deal with combinations of inputs. To identify the test cases with decision table, we consider
conditions and actions. We take conditions as inputs and actions as outputs.
Now consider a dialogue box which will ask the user to upload photo with certain conditions
like –
If any of the conditions fails, the system will throw corresponding error message stating the
issue and if all conditions are met photo will be updated successfully.
Format .jpg .jpg .jpg .jpg Not .jpg Not .jpg Not .jpg Not .jpg
Size Less Less than >= 32kb >= 32kb Less than Less than >= 32kb >= 32kb
than 32kb 32kb 32kb
32kb
• It divides the input data of software into different equivalence data classes.
• You can apply this technique, where there is a range in the input field.
Submit
Order Pizza:
1. Any Number greater than 10 entered in the Order Pizza field (let say 11) is considered
invalid.
2. Any Number less than 1 that is 0 or below, then it is considered invalid.
3. Numbers 1 to 10 are considered valid
4. Any 3 Digit Number say -100 is invalid.
Using state transition testing, we pick test cases from an application where we need to
test different system transitions. We can apply this when an application gives a different
output for the same input, depending on what has happened in the earlier state.
Error Guessing is a software testing technique based on guessing the error which can
prevail in the code. The technique is heavily based on the experience where the test
analysts use their experience to guess the problematic part of the testing application.
Hence, the test analysts must be skilled and experienced for better error guessing.
Standalone application:
Client-Server Application:
Web Application:
Web server applications follow three-tier or n-tier architecture. The presentation layer is
in a client system, a Business layer is in an application server and Database layer is in a
Database server. It works both in Intranet and Internet.
UX design refers to the term “user experience design”, while UI stands for “user
interface design”.
There is an analogy I like to use to describe the different parts of a (digital) product:
If you imagine a product as the human body, the bones represent the code which give it
structure.
The organs represent the UX design: measuring and optimizing against input for
supporting life functions. And UI design represents the cosmetics of the body; its
presentation, its senses and reactions.
We can do System Testing only when all the units are in place and working properly. It
can only be done before User Acceptance Testing (UAT).
6.4. When to stop testing? (Or) How do you decide when you have
tested enough? imp
There are many factors involved in the real-time projects to decide when to stop testing.
Check-list:
1. look & feel
2. height
3. weight
4. material used
5. radius at top & bottom
6. capacity
7. color
8. grip
9. breakable / unbreakable
What you need and what stages you need to test when you receive the Mobile Application,
there are some major concerns I have listed and you should know.
Testing is done by certifying the requirements. like whether the application is working
based on the requirements or not.
This is a user-centric testing of the application. In this test phase, items such as
visibility of text in various screens of the app, interactive messages, alignment of
elements, the look and feel of the app for different screens, size of fields etc. are
tested under this.
This testing is done after all the modules of the app are completely developed,
tested individually and all the bugs are fixed verified.
During this testing, request/response to/from the service is tested for various
conditions.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
36
This test is mainly done to verify the response time in which the activity is performed
like refreshing data after sync or loading data after login etc.
Testing of the data flow for encryption and decryption mechanism is to be tested in
this phase. Access to stored data is also tested in this phase.
It is basically done to verify the behavior of the app when the phone has a 2G or 3G
connection. Field testing verifies if the app is crashing under slow network
connection or if it is taking too long to load the information.
This is the Offline Scenario Verification. Conditions where the communication breaks
in the middle are called as offline conditions.
Some of the conditions where interruptions of a network can be tested are as
follows:
Burn-up and burn-down charts are used to keep track of the progress of the project.
Burn-up charts represent how much work has been completed in any project
whereas Burn-down chart represents the remaining work in a project.
Product backlog is maintained by the project owner which contains every feature
and requirement of the product.
Sprint backlog can be treated as the subset of product backlog which contains
features and requirements related to that particular sprint only.
Test stub is a small code that mimics(copy) a specific component in the system and
can replace it. Its output is the same as the component it replaces.
8.13. What is the difference between Epic, User stories & Tasks?
User Stories: It defines the actual business requirement. Generally created by the
business owner.
Task: To accomplish the business requirements development team create tasks.
Epic: A group of related user stories is called an Epic.
It can be defined as a pre-preparation step to the first sprint. Activities like setting
development environment, preparing backlog, etc need to be done before starting
the first sprint and can be treated as Sprint zero.
There may be some technical issues or design problem in the project which needs to
be resolved first. To provide the solution to this problem “Spikes” are created.
Spikes are of two types- Functional and Technical.
Daily stand-up meeting is essential for any team in which team discuss,
1. How much work has been completed?
2. What are the plans to resolve technical issues?
It can be defined as a spike with the current architecture or the current set of best
practices. The purpose of a tracer bullet is to examine how an end-to-end process
will work and examine feasibility.
There are 5 types of Scrum meetings which occur at a particular time during a Sprint
cycle and each particular type serves a distinct purpose.
I Hope, these questions will help you in preparing for the Agile testing and
methodology interview.
Thanks!
Database is a collection of related data and data is a collection of facts and figures
that can be processed to produce information.
Database management system stores data in such a way that it becomes easier to
retrieve, manipulate, and produce information.
Structured Query Language SQL is a database tool that is used to create and
access the database to support software applications.
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
ALTER: The ALTER table is used for modifying the existing table object in the
database.
ALTER TABLE table_name
OR
These statements are used to manipulate the data in records. Commonly used DML
statements are INSERT, UPDATE, and DELETE.
The SELECT statement is used as a partial DML statement, used to select all or
relevant records in the table.
These statements are used to set privileges such as GRANT and REVOKE
database access permission to the specific user.
The DISTINCT statement is used with the SELECT statement. If the record contains
duplicate values, then the DISTINCT statement is used to select different values
among duplicate records.
Syntax:
SELECT DISTINCT column_name(s)
FROM table_name;
Answer:
WHERE Clause: This clause is used to define the condition, extract and display only those
records which fulfill the given condition.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition;
GROUP BY Clause: It is used with SELECT statement to group the result of the executed
query using the value specified in it. It matches the value with the column name in tables
and groups the end result accordingly.
Syntax:
SELECT column_name(s)
FROM table_name
GROUP BY column_name;
HAVING clause: This clause is used in association with the GROUP BY clause. It is
applied to each group of results or the entire result as a single group. It is much similar as
WHERE clause but the only difference is you cannot use it without GROUP BY clause
Syntax:
SELECT column_name(s)
FROM table_name
GROUP BY column_name
ORDER BY clause: This clause is used to define the order of the query output either in
ascending (ASC) or in descending (DESC). Ascending (ASC) is set as the default one but
descending (DESC) is set explicitly.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
USING clause: USING clause comes in use while working with SQL JOIN. It is used to
check equality based on columns when tables are joined. It can be used instead of the ON
clause in JOIN.
Syntax:
SELECT column_name(s)
FROM table_name
JOIN table_name
USING (column_name);
Constraints are used to set the rules for all records in the table. If any constraints get
violated then it can abort the action that caused it.
Constraints are defined while creating the database itself with the CREATE TABLE
statement or even after the table is created once with the ALTER TABLE statement.
The main difference between null and empty is that the null is used to refer to
nothing while empty is used to refer to a unique string with zero length.
4 major types of Joins are used while working on multiple tables in SQL databases:
INNER JOIN: It is also known as SIMPLE JOIN which returns all rows from BOTH tables
when it has at least one matching column.
Syntax:
SELECT column_name(s)
FROM table_name1
ON column_name1=column_name2;
For Example,
In this example, we have a table Employee with the following data:
FROM Employee
ON Employee.Emp_id = Joining.Emp_id
ORDER BY Employee.Emp_id;
LEFT JOIN (LEFT OUTER JOIN): This join returns all rows from the LEFT table and its
matched rows from a RIGHT table.
Syntax:
SELECT column_name(s)
FROM table_name1
ON column_name1=column_name2;
For Example,
In this example, we have a table Employee with the following data:
FROM Employee
ON Employee.Emp_id = Joining.Emp_id
ORDER BY Employee.Emp_id;
There will be 4 records selected. You will see the following results:
RIGHT JOIN (RIGHT OUTER JOIN): This join returns all rows from the RIGHT table and its
matched rows from the LEFT table.
Syntax:
SELECT column_name(s)
FROM table_name1
ON column_name1=column_name2;
For Example,
In this example, we have a table Employee with the following data:
ON Employee.Emp_id = Joining.Emp_id
ORDER BY Employee.Emp_id;
Output:
Emp_id Joining_Date
E0012 2016/04/18
E0013 2016/04/19
E0014 2016/05/01
FULL JOIN (FULL OUTER JOIN): This join returns all results when there is a match either
in the RIGHT table or in the LEFT table.
Syntax:
SELECT column_name(s)
FROM table_name1
ON column_name1=column_name2;
For Example,
In this example, we have a table Employee with the following data:
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
51
The second table’s name is Joining.
FROM Employee
ON Employee.Emp_id = Joining.Emp_id
ORDER BY Employee.Emp_id;
There will be 8 records selected. These are the results that you should see.
SQL Aggregate functions determine and calculate values from multiple columns in a
table and return a single value.
There are 7 aggregate functions in SQL:
• AVG(): Returns the average value from specified columns.
• COUNT(): Returns number of table rows.
• MAX(): Returns the largest value among the records.
• MIN(): Returns smallest value among the records.
• SUM(): Returns the sum of specified column values.
• FIRST(): Returns the first value.
• LAST(): Returns last value.
Syntax:
CREATE TRIGGER name {BEFORE|AFTER} (event [OR..]}
SELECT column_name(s)
FROM table_name
WHERE condition
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
WHERE condition
ON object_name
TO {user_name|PUBLIC|role_name}
In the above syntax, the GRANT option indicates that the user can grant access to
another user too.
ON object_name
FROM {user_name|PUBLIC|role_name};
9.25. How many row comparison operators are used while working
with a subquery?
There are 3-row comparison operators that are used in subqueries such as IN, ANY
and ALL.
The result of the query is the details of an employee from the Employee table.
10.1. How to write query for find the highest salary from employees
table.
10.2. How to write query for find the second highest salary from
employees table.
1st Method
SELECT name, MAX(salary) AS salary
FROM employee
WHERE salary < (SELECT MAX(salary)
FROM employee);
2nd Method
For Second max salary
Select name, salary From Employee ORDER BY Salary DESC LIMIT
1,1;
For third max salary
Select salary From Employee ORDER BY Salary DESC LIMIT 2,1;
10.4. How to write the query to find the total no of columns in Table?
Many of the new modern web applications are built using web-services, micro-services,
and APIs. As testers, we should be knowledgeable and experienced in testing APIs and
Web Services.
Here are some fundamental API Testing Interview Questions mainly aimed at software
testers.
API is a collection of routines, tools, protocols that together are required for building
the software application. Any system software or application software which consists
of multiple APIs can perform Application Programming Interface (API) testing.
This form of testing includes interaction between various or says multiple APIs as
well as the interaction between API and application program. The procedure mainly
includes making API calls using software and observing system response after
receiving the output.
API is considered as the essential connecting part of this digital world. It basically
resides in the business logic layer where it performs functions like processing
commands, application coordination, initiates logical decisions, etc.
The main consideration is returning correct results under any type of conditions.
Mainly, the output or results observed of an API are divided into three sections as
follows:
• SOAP stands for Simple Object Access Protocol whereas REST stands for
Representational State Transfer.
• SOAP is state full and REST is state less.
• SOAP is a protocol whereas REST is an architectural pattern.
• SOAP uses service interfaces to expose its functionality to client applications
while REST uses Uniform Service locators to access to the components on
the hardware device.
• SOAP needs more bandwidth for its usage whereas REST doesn’t need
much bandwidth.
• Comparing SOAP vs REST API, SOAP only works with XML formats
whereas REST work with plain text, XML, HTML and JSON.
• SOAP cannot make use of REST whereas REST can make use of SOAP.
11.7. Enlist some best practices that are followed to make API testing successful.
Performing tests repeatedly define some best practices for making testing
successful.
Enlisted below are some best practices for API testing:
• Test cases should be grouped under category with expected results that
happen consistently and other typical results.
• Test cases should include selected parameters as well as API call
declarations.
• API load tests are performed to determine system application stress.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
62
• Maintain the limits of the variables used in the tests as well as avoid ‘Test
Chaining’.
• To make ease for the testers, API call is being prioritized and call sequencing
is planned.
• Every input combination and dependencies are considered for complete test
coverage.
• Automation of the test cases, documentation is done as and when required.
11.9. What are the tools used for API test automation?
Automation testing is a must when we talk about agile development in API testing.
However, the language in which the code is written is also an important factor as it
decides the tool language.
Some important API test automation tools are:
• SOAPUI: It is an open-source API testing tool which is considered as the best
testing tool because of its feature like creating complex validation scripts and
test cases, efficient test coverage, etc.
• HP QTP/UFT: This is now known as HP UFT i.e., Unified Functional Testing.
This tool is basically used for systems without user interface like web
services, etc.
• PARASOFT: This testing tool runs on various platforms and is used to test
API which does not have a Graphical User interface (GUI).
• HTTP master
• NUnit and JUnit testing tools are used where the code is written in .Net and
Java respectively.
API framework is described by the config file which consists of the list of all APIs that
are required to be activated and are activated for any particular program run. This is
essential as every test run does not require all APIs.
The purpose of the ‘Config’ file is to describe and enlist every configurable
component within a test run.
Some free templates which make API documentation much easier and simple
are:
• Slate
• FlatDoc
• Swagger
• API blueprint
• RestDoc
• Miredot
• Web service API Specification.
11.13. Enlist some of the API examples which are very well known and popular.
There are several such examples. Enlisted below are some most popular ones:
• Google Maps API: These are designed mainly for mobile and desktop use with
the help of a flash interface and JavaScript.
• Amazon Advertising API: Amazon is known for their products and thus their
advertising API accesses their product to discover their functionality and thus
advertise accordingly.
• Twitter: The API for twitter is usually in two categories, one for accessing data
and the other for interacting with the twitter search.
• YouTube: This API used for YouTube includes various functionalities including
videos, live streaming, player, etc.
11.14. What are the testing methods that come under API testing?
The difference between API testing and Unit testing can be understood from the
below table:
UNIT testing API Testing
Unit testing is usually performed by developers API testing is performed by the testers for end to
where every functionality is tested separately. end testing of the functionality.
As they have the limited scope of testing, thus basic As they have the broader scope of testing, all
functionalities are only considered for testing. issues that are functional are considered for
testing.
Usually, unit testing is done before the code is API testing is performed after the build is ready for
included in the build. testing.
The Source code is involved in this form of testing. Source code is not involved in this form of testing.
Challenges are the part of every form of testing and the same goes with API testing
too.
Mentioned below are some common challenges that are faced in API testing:
• The first and foremost challenge is selecting an appropriate parameter and
then its combination.
• Parameter categorization
• Proper sequencing of call is required as this may lead to inadequate
coverage in testing.
• Output verification and validation
• Another important challenge is providing input values, which is very difficult
as GUI is not available in this case.
When testing is performed, then there have to be issues associated with them.
Issues observed while performing this form of testing are not new or much different
but they are common in this category.
Find below the list of such issues/defects:
• Inconsistent or absence of error handling mechanism
• Repetition or redundancy of the functionalities
• Missing required functionality in some cases
• Passing incorrect argument to the input values
• Improper messaging
• Stress and performance issues
• Reliability issues with respect to connection with other APIs
• Multithreading and improper handling issues.
11.18. Why API testing is determined as the most suitable form for Automation
testing?
Yes, it’s true that API testing is now preferred over GUI testing and is considered as
most suitable.
Below are the few reasons behind this statement.
• Verify all the functional paths of the system under test very effectively.
• Provides the most stable interface.
• Easier to maintain and provides fast feedback.
The main consideration of the UI (User Interface) level testing is to test the graphical
interface part of the application include features like font, layout, etc.
Whereas, the main consideration of the API testing is establishing communication
between different software systems and it mainly resides in business logic layer. It
never concentrates on the look of the application.
Test Api is known as the library of test building blocks which are essential for
developers and testers for creating testing tools as well as automated test suites.
When something goes wrong i.e. the outcome is not as expected then the error
occurs and warnings are described as a message in the proper format. There can be
one or multiple warnings within the same module.
Different types of warnings that can occur are:
• Parameter validation warning
• Missing module warning
Different types of errors that can occur are:
• Documentation errors
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
66
• Missing module errors
• Parameter validation errors
• Some standard error messages.
GET: The HTTP GET method is used to **read** (or retrieve) a representation of a resource.
▪ Request Method – Get, Post, Put, Delete (these are the common ones)
▪ Request URI – the URL of the resource
▪ Response Status Code – 200, 301, 404, 500 (these are the most common ones)
2x Success
Code Text Purpose
3x Redirection
401 Unauthorized This response is sent when your client failed to provide credentials
or its credentials were invalid.
404 Not Found When a particular resource doesn’t exist or couldn’t be found.
405 Method Not The resource was found, but doesn’t support the request method.
Allowed
406 Not Acceptable When the client specifies a response content type in
the Accept header that is not supported.
413 Request Entity When the client requests too many objects. For example,
Too Large the limit parameter exceeded the maximum.
422 Missing or The request cannot be processed either because it omitted required
Invalid Data fields or because it contained invalid data. See the response for
more details.
429 Too Many When an OAuth client exceeds the rate limit for API requests to a
Requests store.
500 Internal Server When an error has occurred within the API.
Error
501 Not When a request method is sent that is not supported by the API
Implemented (e.g., TRACE , PATCH ).
503 Service When the store is “Down for Maintenance,” being upgraded to a new
Unavailable version, or is suspended due to administrative action or a billing issue.
507 Insufficient When the store has reached a limitation for the resource.
Storage
Hope this article will be very helpful for your API Testing interview preparation
• Technically in encapsulation, the variables or data of a class is hidden from any other class
and can be accessed only through any member function of own class in which they are
declared.
• As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
Method Overriding is a Run time polymorphism. In method overriding, the derived class
provides the specific implementation of the method that is already provided by the base
class or parent class. In method overriding, the return type must be the same or co-variant
(return type may vary in the same direction as the derived class).
Selenium
1. is a free and open source
2. have a large user base and helping communities
3. have cross Browser compatibility (Firefox, Chrome, Internet Explorer, Safari etc.)
4. have great platform compatibility (Windows, Mac OS, Linux etc.)
5. supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)
6. has fresh and regular repository developments
7. supports distributed testing
Selenium is one of the most popular automated testing suites. Selenium is designed
in a way to support and encourage automation testing of functional aspects of web-
based applications and a wide range of browsers and platforms. Due to its existence
in the open-source community, it has become one of the most accepted tools
amongst the testing professionals.
Selenium is not just a single tool or a utility, rather a package of several testing tools
and for the same reason, it is referred to as a Suite. Each of these tools is designed
to cater different testing and test environment requirements.
13.5. What are the testing types that can be supported by Selenium?
Selenium IDE is the simplest and easiest of all the tools within the Selenium
Package. Its record and playback feature makes it exceptionally easy to learn with
minimal acquaintances to any programming language. Selenium IDE is an ideal tool
for a naïve user.
Selenese is the language which is used to write test scripts in Selenium IDE.
The locator can be termed as an address that identifies a web element uniquely
within the webpage. Thus, to identify web elements accurately and precisely we
have different types of locators in Selenium:
• ID
• ClassName
• Name
• TagName
• LinkText
• PartialLinkText
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
74
• Xpath
• CSS Selector
• DOM
Assert: Assert command checks whether the given condition is true or false. Let’s
say we assert whether the given element is present on the web page or not. If the
condition is true then the program control will execute the next test step but if the
condition is false, the execution would stop and no further test would be executed.
Verify: Verify command also checks whether the given condition is true or false.
Irrespective of the condition being true or false, the program execution doesn’t halt
i.e. any failure during verification would not stop the execution and all the test steps
would be executed.
XPath is used to locate a web element based on its XML path. XML stands for
Extensible Markup Language and is used to store, organize and transport arbitrary
data. It stores data in a key-value pair which is very much similar to HTML tags. Both
being markup languages and since they fall under the same umbrella, XPath can be
used to locate HTML elements.
The fundamental behind locating elements using XPath is the traversing between
various elements across the entire page and thus enabling a user to find an element
with the reference of another element.
13.12. What is the difference between Static Xpath and Dynamic Xpath?
An absolute xpath in HTML Document Object Modal (DOM) starts with html e.g.
1. html/body/div[5]/div[2]/div/div[2]/div[2]/h2[1]
and a relative xpath finds the closed id to the DOM element and generates xpath
starting from that element e.g.
1. //*[@id='answers']/h2[1]/a[1]
Single Slash “/” – Single slash is used to create Xpath with absolute path.
Double Slash “//” – Double slash is used to create Xpath with relative path.
Selenium Grid can be used to execute same or different test scripts on multiple
platforms and browsers concurrently so as to achieve distributed test execution,
testing under different environments and saving execution time remarkably.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
75
13.14. How do I launch the browser using WebDriver?
Implicit Wait: Implicit waits are used to provide a default waiting time (say 30
seconds) between each consecutive test step/command across the entire test script.
Thus, the subsequent test step would only execute when the 30 seconds have
elapsed after executing the previous test step/command.
Explicit Wait: Explicit waits are used to halt the execution till the time a particular
condition is met or the maximum time has elapsed. Unlike Implicit waits, explicit
waits are applied for a particular instance only.
There are some common conditions that are frequently of use when automating web
browsers.
• title_is
• title_contains
• presence_of_element_located
• visibility_of_element_located
• visibility_of
• presence_of_all_elements_located
• text_to_be_present_in_element
• text_to_be_present_in_element_value
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
76
• frame_to_be_available_and_switch_to_it
• invisibility_of_element_located
• element_to_be_clickable
• staleness_of
• element_to_be_selected
• element_located_to_be_selected
• element_selection_state_to_be
• element_located_selection_state_to_be
• alert_is_present
The user can use sendKeys(“String to be entered”) to enter the string in the textbox.
Syntax:
WebElement username = drv.findElement(By.id(“Email”));
// entering username
username.sendKeys(“sth”);
WebDriver facilitates the user with the following methods to check the visibility of the
web elements. These web elements can be buttons, drop boxes, checkboxes, radio
buttons, labels etc.
1. isDisplayed()
2. isSelected()
3. isEnabled()
Syntax:
isDisplayed():
boolean buttonPresence = driver.findElement(By.id(“gbqfba”)).isDisplayed();
isSelected():
boolean buttonSelected = driver.findElement(By.id(“gbqfba”)).isSelected();
isEnabled():
boolean searchIconEnabled = driver.findElement(By.id(“gbqfb”)).isEnabled();
Get command is used to retrieve the inner text of the specified web element. The
command doesn’t require any parameter but returns a string value. It is also one of
the extensively used commands for verification of messages, labels, errors etc
displayed on the web pages.
The value in the dropdown can be selected using WebDriver’s Select class.
Syntax:
selectByValue:
Select selectByValue = new Select(driver.findElement(By.id(“SelectID_One”)));
selectByValue.selectByValue(“greenvalue”);
selectByVisibleText:
Select selectByVisibleText = new Select
(driver.findElement(By.id(“SelectID_Two”)));
selectByVisibleText.selectByVisibleText(“Lime”);
selectByIndex:
Select selectByIndex = new Select(driver.findElement(By.id(“SelectID_Three”)));
selectByIndex.selectByIndex(2);
driver.findElement(By.linkText(“Google”)).click();
The command finds the element using link text and then click on that element and
thus the user would be re-directed to the corresponding page.
The above-mentioned link can also be accessed by using the following command.
driver.findElement(By.partialLinkText(“Goo”)).click();
An inline frame acronym as iframe is used to insert another document within the
current HTML document or simply a web page into a web page by enabling nesting.
Select iframe by id
driver.switchTo().frame(“ID of the frame“);
Locating iframe using tagName
driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));
Locating iframe using index
frame(index)
driver.switchTo().frame(0);
frame(Name of Frame)
driver.switchTo().frame(“name of the frame”);
frame(WebElement element)
Select Parent Window
driver.switchTo().defaultContent();
findElement(): findElement() is used to find the first element in the current web page
matching to the specified locator value. Take a note that only first matching element
would be fetched.
Syntax:
WebElement element = driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
findElements(): findElements() is used to find all the elements in the current web
page matching to the specified locator value. Take a note that all the matching
elements would be fetched and stored in the list of WebElements.
Syntax:
List <WebElement> elementList
= driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
WebDriver offers the users a very efficient way to handle these pop-ups using Alert
interface. There are the four methods that we would be using along with the Alert
interface.
• void dismiss() – The dismiss() method clicks on the “Cancel” button as soon
as the pop-up window appears.
• void accept() – The accept() method clicks on the “Ok” button as soon as the
pop-up window appears.
• String getText() – The getText() method returns the text displayed on the alert
box.
• void sendKeys(String stringToSend) – The sendKeys() method enters the
specified string pattern into the alert box.
Syntax:
// accepting javascript alert
Alert alert = driver.switchTo().alert();
alert.accept();
WebDriver offers a wide range of interaction utilities that the user can exploit to
automate mouse and keyboard events. Action Interface is one such utility which
simulates the single user interactions.
Thus, In the following scenario, we have used Action Interface to mouse hover on a
drop down which then opens a list of options.
Sample Code:
// Instantiating Action Interface
subLinkOption.click();
The values of the css properties can be retrieved using a get() method:
Syntax:
driver.findElement(By.id(“id“)).getCssValue(“name of css attribute”);
driver.findElement(By.id(“id“)).getCssValue(“font-size”);
Example: Write the behavior of the application for entering the username and
password.
Scenario: Login check
Given I am on the login page
When I enter "username" username
And I enter "Password" password
And I click on the "Login" button
Then I am able to login successfully.
Page Object Model (POM) is a design pattern, popularly used in test automation that
creates Object Repository for web UI elements. The advantage of the model is that it
reduces code duplication and improves test maintenance.
Advantages of POM
1. Page Object Design Pattern says operations and flows in the UI should be
separated from verification. This concept makes our code cleaner and easy to
understand.
2. The Second benefit is the object repository is independent of test cases, so
we can use the same object repository for a different purpose with different
tools.
3. Code becomes less and optimized because of the reusable page methods in
the POM classes.
4. Methods get more realistic names which can be easily mapped with the
operation happening in UI. i.e. if after clicking on the button we land on the
home page, the method name will be like 'gotoHomePage()'.
Test data can efficiently be read from excel using JXL or POI API.
Browser Selenium supports almost all the popular QTP supports Internet Explorer, Firefox and
Compatibility browsers like Firefox, Chrome, Safari, Internet Chrome. QTP only supports Windows
Explorer, Opera etc. Operating System
Distribution Selenium is distributed as an open-source tool QTP is distributed as a licensed tool and is
and is freely available commercialized
Application Selenium supports testing of only web-based QTP supports testing of both the web-based
under Test applications application and windows based application
Object Object Repository needs to be created as a QTP automatically creates and maintains
Repository separate entity Object Repository
Vendor Support As Selenium is a free tool, user would not get Users can easily get the vendor’s support in
the vendor’s support in troubleshooting issues case of any issue
Object Repository is a term used to refer to the collection of web elements belonging
to Application Under Test (AUT) along with their locator values. Thus, whenever the
element is required within the script, the locator value can be populated from the
Object Repository. Object Repository is used to store locators in a centralized
location instead of hardcoding them within the scripts.
In Selenium, objects can be stored in an excel sheet which can be populated inside
the script whenever required.
Exceptions are events due to which java program ends abruptly without giving
expected output. Java provides a framework where a user can handle exceptions.
When you start working with Selenium webdriver, you will come across different
exceptions based on the code you write. When an exception occurs, the normal flow
of program halts and an exception object is created. Exception Handling is a
mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
• NoSuchElementException
• NoSuchWindowException
• NoSuchFrameException
• NoAlertPresentException
• InvalidSelectorException
• ElementNotVisibleException
• ElementNotSelectableException
• TimeoutException
• NoSuchSessionException
• StaleElementReferenceException
p = driver.current_window_handle
parent = driver.window_handles[0]
child = driver.window_handles[1]
driver.switch_to.window(child)
__init__ method
"__init__" is a reserved method in python classes. It is called as a constructor in
object oriented terminology. This method is called when an object is created from
a class and it allows the class to initialize the attributes of the class.
Hope in this article you will find answers to most frequently asked Selenium and
WebDriver Interview questions.
No, JMeter does not support the actual browser behavior. It does not render the
HTML webpages as the normal browser does. The response can be viewed in
HTML format but the actual timings are not present in the generated samples.
Distributed Testing means using multiple machines for load testing in which one of
the machines can be made master and others can be kept as a slave. It is very
important to note that all the machines should be on the same network and should
have the same version of Java and JMeter.
Regular Expression is used for extracting some values dynamically from the
responses. These values can be used in the subsequent request or can be saved for
reporting purposes. Regular Expression is used in both Pre-Processors as well as
Post Processors.
Basically, there are two types of processors in JMeter namely Pre-Processor and
Post Processor.
Pre-Processors execute before the main sampler and can change the scope of the
sampler whereas Post Processors execute after the main sampler and are
applicable to all samplers in the same scope of Test Plan. They can be used to
extract some fields from the server response and store them in variables.
Data Parametrization makes the scripts reusable where the values is not required to
be hardcoded for the same request with different parameters.
Below is the data parametrization that is supported in JMeter:
• CSV Data Set Config
• User-Defined Variables.
Both Gaussian and Poisson Timers work on a mathematical formula with some
constant delay and additional offset. Difference between the two lies in the fact that
how the lambda value is calculated in the case of Poisson timer and how deviation is
calculated in the case of Gaussian Timer.
14.9. What are the major differences between JMeter and Load Runner?
It has more technical capabilities. Less technically sound as compared to Load Runner.
Supports SAP, Siebel and Peoplesoft. Doesn’t support SAP and Siebel
Co-relation is a process of extracting the values from the server response and
storing it in a variable to be used in any other request which is to follow.
For Example, for testing any login functionality if you have to use the session
ID/cookie ID, you can extract the values from the response of GET Request of the
login page and then dynamically use the same while making POST request for a
login.
Listeners are used for storing the execution results of load testing in different forms
be it in a table, graph, tree or in any other presentable format so that it can be
presented to the client. There are different type of inbuild listeners in JMeter and
many others can be imported into it by using plugins as per the requirement.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
87
Some of the inbuild listeners are:
• View results in Table
• View results in Tree
• Graph results
• Aggregate graph
• Aggregate report
• Assertion results
• Response time graph
HTTP(s) Test Script Recorder is used to record all the Http(s) requests going to the
server from your application. Some configurations require to be done in JMeter in
order to make it work.
Steps followed to record https traffic are:
• Add HTTP(s) Test script recorder to WorkBench.
• Enter the port number to start your proxy server.
• Choose the target either as “Workbench” or add a Recording Controller in your
test plan and select the same target for storing all the recordings under it.
• Start the proxy server.
• Configure your browser with manual proxy settings pointing to the same port
number used in the test script recorder.
Yes, JMeter can record HTTP or Https request going to the server from your mobile
application also. It is required that mobile and JMeter are on the same network.
Below is the configuration required:
• Configure your proxy server in JMeter to run at a specified port.
• Set up the proxy on your mobile wifi settings and enter the same port number
that is used in the recorder.
• Install the Root CA certificate on your mobile.
• Hit server requests from your mobile and observe it getting captured by the
specified controller.
Just as in any other programming language, variables and functions are used in
JMeter also in order to make the scripts reusable.
Syntax of Variable – ${var}
There are many inbuilt functions that are available in JMeter to perform various
actions. Function string can be generated from the Function Dialogue Box itself.
For Example, if you want to get the machine IP stored in a machineIP variable, you
can use the string ${__machineIP(machineIP)}.
JMeter tests can be run both GUI as well as Non-GUI Mode. It is highly
recommended to run the load test in non-GUI mode because the AWT event thread
can kill the tests in case of high load scenarios.
The various non-GUI mode supported with JMeter are:
• Command-line
• ANT plugin
• MAVEN plugin
• Jenkins
Yes, it is possible to run selenium scripts in JMeter to get some ideas on their
performance.
There are two ways of doing it. Either you can use JUnit libraries to build selenium
scripts and save as Jars and copy the same in the JMeter directory. And then add
JUnit sampler to your test plan and import the Jar file.
Otherwise, the Webdriver sampler plugin can be added in the JMeter ext folder.
Restart the JMeter. Write your selenium code in the Webdriver sampler and then
execute it to see the performance.
Prepared by: Mr. Umar Arshad | Software Quality Assurance Engineer
89
14.19. How do you manage sessions and cookies in JMeter?
Sessions and cookies can be managed in JMeter by using config elements such as
HTTP Cache Manager which provides an option to clear the cookies in every
iteration and also allows to add user-defined cookies.
HTTP Cache manager helps you in clearing cache after each iteration as per your
requirement in the load tests and also limits the number of elements that can be
stored in the cache. Both of these config elements can be attached to the HTTP
sampler.
14.20. What are the important steps for testing JDBC request?
JDBC requests are used to establish a connection with the databases and then
measure the response time of the queries.
Important steps for testing JDBC requests are:
• Setting up Config Element, JDBC Connection configuration in which
Database URL and JDBC Driver Class needs to be added as per the
database which is being used. Also, add the variable name for this
connection configuration so as to use it in the sampler.
• Add JDBC Request. Add the same variable name added above and write
your queries to the test.
14.22. Can JMeter measure the performance of a complete application? For Example,
you have multiple screens in your mobile app. Can JMeter measure the time
taken to flip the screens?
No, JMeter does not measure the transition time between the screens. It can only
measure the server actions not the UI interactions.
14.24. Which factors decide the maximum threads that one should generate per
system?
Tidy Parsing is a type of parsing that is used in Xpath extractor. If the response is in
pure XML then tidy parsing is not required whereas, in the case of XHTML, it is
mandatory to check the tidy parsing option in order to fetch the correct results.
14.26. What are the important plugins that are supported in JMeter?
JMeter supports different types of plugins which are helpful in generating high-quality
results.
Below are the major plugins that are supported:
• Thread group plugin – Stepping thread group plugin.
• Samplers’ plugins like Webdriver.
• Listener’s plugins.
How does a Jmeter knows what type of request has been sent to server???
It is through Samplers. Samplers are a must to add to a Test Plan as only it can let
Jmeter know what type of request need to go to which server and with any
predefined parameters or not. Requests could be HTTP, HTTP(s), FTP, TCP,
SMTP, SOAP, JDBC etc.
Till now, we have covered how JMeter hits the server and how the responses are
displayed via listeners. To ensure that the response received is correct and as per
expectation, we need to add assertions. Assertions are simply validations which we
need to put on responses to compare the results.
Below are the types of assertions commonly used:
• Response Assertion
I’m sure that this article on JMeter interview questions would have helped to enrich your
knowledge on JMeter concepts to a great extent.
A thorough understanding of all the questions covered here would help you to crack any
interview confidently.
15.1. If you have a 5-litre jug and a 3-litre jug, how would you measure exactly 4
liters?
Answer
1. Fill the 3L jug fully and empty it in the 5L jug
2. Now again fill 3L fully and pour its water in the 5L jug (remember it already has 3 liters of
water in it) until it full.
3. Now you're left with only 1 liter of water in the 3L jug (*hope you are getting it)
4. Now empty 5L jug and pour that remaining 1-liter water that we got in step 3 into the 5L
jug.
a. Now 5L jug contains 1 liter of water.
5. Now fill the 3L jug fully and empty it into the 5L jug so you will now have 4 liters of water
in 5L jug.
That's how you get 4litres of water.
15.2. I give you 4 tablets which contain 2 for fever and 2 for cold, all the same
size, shape, taste, weight and color, no cover. You have to take 1 cold and 1
fever tablet right now. How will you choose correctly?
Answer
So basically, you have 4 tablets. 2 for cold and other 2 for fever. Now start dividing the
tablets into half. Keep one half in your hand and other half on table. Once you are
done dividing all the tablets into half, take either of them. Problem solved.
15.3. There is a room with a door (closed) and three light bulbs. Outside the
room, there are three switches, connected to the bulbs. You may manipulate
the switches as you wish, but once you open the door you can’t change
them. Identify each switch with its bulb. All bulbs are in working condition.
Answer
Answer
Firstly, break each of the pills in half, and as you do this pop one half in your mouth
and lay the other half aside for tomorrow. When he’s done this with all four pills he will
have consumed one red pill and one blue pill. And have the same leftover.
Answer
On the back of 45, it is 46. The pages are such that for each page p, 65-p
will be also on the same page.
Then,
65-45 = 20
65-46 = 19
So, the four pages in this sheet are 19, 20, 45, 46.
Answer
Step 1: Cut the cake into quarters (4 pieces) using 2 of the cuts – one
horizontally down the center of the cake and the other vertically down the
center of the cake. This will leave you with 4 pieces (or slices) of cake.
Step 2: Then take all 4 pieces and arrange them in a stack that is 4 pieces
high.
Step 3: Finally, you can just cut that stack of 4 pieces in half – using your third
and final cut – and then you will end up with 8 pieces of cake!
15.8. A Lady (L) bought an item of Rs 100 from the Shopkeeper (C). She paid him
through a 500 Rs Note. Realizing that he did not have change, the
shopkeeper C got change for that note from another shopkeeper (S) and
paid Rs 400 to the Lady.
After a few days, S realized that the note is fake, And this railed at C and took
500 Rs back from him.
So in this whole process how much money did C loose in the end?
Answer: 500
This is based on the user perspective for the perfect solution based on the situation
where in it is used.
This is because each of the n people can shake hands with n - 1 people (they would
not shake their own hand), and the handshake between two people is not counted
twice.
# handshakes = 5*(4)/2.
# handshakes = 20/2.
# handshakes = 10
15.11. You have 9 balls, equally big, equally heavy - except for one, which is a little
heavier.
How would you identify the heavier ball if you could use a pair of balance
scales only twice?
ANS:
Divide the 9 balls into 3 groups of 3. Compare the weight of two of those groups.
The heavier group should then be obvious, it will either tip the scales, or, if the scales
stay balanced, then it is the group you didn't include.
Now, choose 2 balls from this group and compare their weights, and using the same
logic as before, the heavier ball will be obvious.
Thanks
What is API? 4
HTTP - Fundamentals 9
What is an Cookies? 10
What is Authentication? 10
API stands for the Application Programming Interface, They are basically a collection of functions and
procedures which allows us to communicate two application or library.
For example, It like a connector as seen in the picture. All data connects to our organization through API.
In one line, API is its an interface between different software programs or service.
Simple Examples is,
Suppose you go to a restaurant.
API is the messenger that takes your order(waiter) and tells the system(kitchen) what to do (to prepare food)
and in return gives back the response you asked for (waiter returns with the ordered food).
Source - Quora. https://www.quora.com/What-is-an-API
Type of APIs :-
What is API Testing?
API testing is testing that APIs and its integration with the services.
It is one of the most challenging type of testing, If we miss the certain cases in API Testing that can cause a
very big problem in production after full integration and it will hard to debug in production environment..
The REST architectural style describes six constraints. These constraints, put on the architecture, were initially
communicated by Roy Fielding in his doctoral dissertation and defines the basis of RESTful-style.
1. Uniform Interface
2. Stateless
3. Cacheable
4. Client-Server
5. Layered System
6. Code on Demand
Uniform Interface
The uniform interface constraint defines the interface between clients and servers.
In other terms,
First constraint of the REST API states that the Client and server has to communicate and agree to certain
rules based on resources(they should communicate with same resource like json, xml, html , txt) and with
proper encoding like UTF-8 extra.
Another point they should communicate with the Self-descriptive Messages e.g Use the same MIME types.
Stateless
APIs in REST are stateless and Client and server doesn’t worry about the state of the request or response..
Cacheable
According to the World Wide Web, clients can cache responses. Responses should therefore, implicitly or
explicitly, define themselves as cacheable. Its upto server when they want the cache to expired etc.
Client-Server
Client and Server are two different entity, It means that servers and clients may also be replaced and
developed independently, as long as the interface is not altered.
Layered System.
It means that the between client and server there can be any number of layered systems it does not matter.
Code on Demand
Server can store the Code or logic to themselves and transfer it whenever needed rather client side logic.
If any API fulfill all the constraints then we can it REST API.
Difference between REST API vs SOAP API.
We have already discussed REST API , Lets now Learn what is SOAP API.
SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs that run on disparate
operating systems or services like frontend or backend to communicate using Hypertext Transfer Protocol
(HTTP) and its Extensible Markup Language (XML).
SOAP uses WSDL is an XML format for describing network services as a set of endpoints operating on
messages containing either document-oriented or procedure-oriented information.
● Validate the keys with the Min. and Max range of APIs (e.g maximum and minimum length)
● Have a Testcase to do XML,JSON Schema validation.
● Keys verification. If we have JSON, XML apis we should verify it's that all the keys are coming.
● Verify that how the APIs error codes handled.
● Right now, Internet uses millions of APIs and they should be tested thoroughly.
Above image shows the architecture of an application and notice that API Testing is important part..
Now…
HTTP - Fundamentals
HTTP is an application layer protocol designed within the framework of the Internet protocol suite.
There is Client which perform a request resource which can be HTMLPage, file extra from Server and server
perform the response to the client back using the same protocol known as HTTP.
HTTP is a stateless protocol. In other words, the current request does not know what has been done in the
previous requests.
What is an Cookies?
Cookies are usually small text files, given ID tags that are stored on your computer's browser directory or
program data subfolders.
What is Authentication?
Authentication is a process of presenting your credentials like username, password or another secret key to
the system and the system to validate your credentials or you. In the API terms Authentication is used to
protect the content over web mean only a valid user with valid credentials can access that API endpoint.
These credentials tell the system about who you are. Which enables the system to ensures and confirms a
user’s identity. Here system can be anything, it can be a computer, phone, bank or any physical office
premises.
OAuth- Authentication protocol that allows you to approve one application interacting with another on your
behalf without giving away your password.
E.g OAuth 1, 2.
Just for more information, URL can be broken down into the further chunks like protocol, host , post and query
params. More discussion is out of scope for URL
.
HTTP POST Method Explained -
Now we have a HTTP Methods knowledge lets understand what are Cookie and authentication.
Before that take a look into the example api that can available freely.
https://api.chucknorris.io/jokes/random
● Runscope.com
● Postman CI/CD
● Katalon using CI/CD
● SoapUI CI/CD
● Rest Assured CI/CD
It is an API Testing tool used by developers and Testers to perform API Testing with lots of different features
like Global variables, mock request, Environment and monitoring of APIs.
You can learn more about a postman in my full Video lecture series here. Download and install it.
P.S – This article assumes that you have some experience with Postman. If not please go through my previous
tutorials.
4. WHAT IS SDLC?
Manual testing interview question
Ans. Software Development Life Cycle refers to all the activities that are performed
during software development, including - requirement analysis, designing,
implementation, testing, deployment and maintenance phases.
• Requirement analyses and validation - In this phase the requirements documents are
analysed and validated and scope of testing is defined.
• Test planning - In this phase test plan strategy is defined, estimation of test effort is
defined along with automation strategy and tool selection is done.
• Test Design and analysis - In this phase test cases are designed, test data is prepared and
automation scripts are implemented.
• Test environment setup - A test environment closely simulating the real world
environment is prepared.
• Test execution - The test cases are prepared, bugs are reported and retested once
resolved.
• Test closure and reporting - A test closure report is prepared having the final test results
summary, learning and test metrics.
o Fixed: When a developer makes a necessary code change and verifies the change, he or
she can make bug status as "Fixed."
o Pending retest: after fixing the defect the developer gives a particular code for retesting
the code to the tester. Here the testing is pending on the testers end, the status assigned
is "pending request."
o Retest: Tester does the retesting of the code at, to check whether the defect is fixed by
the developer or not and changes the status to "Re-test."
• Verified: The tester re-tests the bug after it got fixed by the developer. If there is no bug
detected in the software, then the bug is fixed and the status assigned is "verified."
• Reopen: If the bug persists even after the developer has fixed the bug, the tester
changes the status to "reopened". Once again the bug goes through the life cycle.
• Closed: If the bug is no longer exists then tester assigns the status "Closed."
• Duplicate: If the defect is repeated twice or the defect corresponds to the same concept
of the bug, the status is changed to "duplicate."
• Rejected: If the developer feels the defect is not a genuine defect then it changes the
defect to "rejected."
• Deferred: If the present bug is not of a prime priority and if it is expected to get fixed in
the next release, then status "Deferred" is assigned to such bugs
• Not a bug: If it does not affect the functionality of the application then the status assign
to a bug is "Not a bug".
Smoke Testing is performed to ascertain that Sanity Testing is done to check the new
the critical functionalities of the program is functionality/bugs have been fixed
working fine
The objective of this testing is to verify the The objective of the testing is to verify the
"stability" of the system in order to proceed "rationality" of the system in order to
with more rigorous testing proceed with more rigorous testing
This testing is performed by the developers Sanity testing is usually performed by testers
or testers
Smoke testing is usually documented or Sanity testing is usually not documented and
scripted is unscripted
Smoke testing exercises the entire system Sanity testing exercises only the particular
from end to end component of the entire system
Smoke testing is like General Health Check Sanity Testing is like specialized health check
Up up
29. Give an example of Low priority-Low severity, Low priority-High severity, High
priority-Low severity, High priority-High severity defects.
o Because of this meeting, if the one person is absent the another person from same team
can complete his work. So project isn’t paused and dependency on one person is not
happened. This is the main advantage of this model.
o Sprint is dividing the project into modules and distributing these modules among both
the team’s so that the team is working parallelly.
o When to use:- when the project is big/medium and we have to deliver it as soon as
possible then we will use this model. Quality is maintained.
1. Product Owner - The product owner owns the whole development of the product, assign
tasks to the team and act as an interface between the scrum team(development team)
and the stakeholders.
2. Scrum Master - The scrum master monitors that scrum rules get followed in the team
and conducts scrum meeting.
3. Scrum Team - A scrum team participate in the scrum meetings and perform the tasks
assigned.
test cases. It is also called as a part of stress and –ve testing. e.g. if the test data lies in the
range of 0-100, the boundary value analysis will include test data - 0,1, 99, 100.
43. WHAT ARE SOME DEFECT REPORTING ATTRIBUTES?
Ans. Some of the attributes of a Defect resport are-
DefectId - A unique identifier of the defect.
Defect Summary - A one line summary of the defect, more like a defect title.
Defect Description - A detailed description of the defect.
Steps to reproduce - The steps to reproduce the defect.
Expected Result - The expected behaviour from which the application is deviating because of
the defect.
Actual Result- The current erroneous state of the application w.r.t. the defect.
Defect Severity - Based on the criticality of the defect, this field can be set to minor, medium,
major or show stopper.
Priority - Based on the urgency of the defect, this field can be set on a scale of P0 to P3.
Ans - It is the process of analysing any given piece of software to determine if it meets
shareholders’ needs as well as detecting defects, and ascertaining the item’s overall quality
by measuring its performance, features, quality, utility, and completeness. Bottom line, it’s
quality control.
2. What is quality control, and how does it differ from quality assurance?
Ans - Quality control is the process of running a program to determine if it has any defects,
as well as making sure that the software meets all of the requirements put forth by the
stakeholders. Quality assurance is a process-oriented approach that focuses on making sure
that the methods, techniques, and processes used to create quality deliverables are applied
correctly.
3. What exactly is manual software testing, and how does it differ from automated software
testing?
Ans- Manual software testing is a process where human testers manually run test cases,
then generate the resulting test reports. With automation software testing, these functions
are executed by automation tools such as test scripts and code. The tester takes the end
user’s role to determine how well the app works.
It’s cheaper
Some tasks may be difficult to accomplish manually, requiring more time to complete
The cost adds up, so it’s more expensive in the long run
You cannot record the manual testing process, so it’s hard to replicate it.
6. What kind of skills are needed for someone to become a software tester?
Problem-solving skills
Detail-oriented
Organizational skills
Ans - This is an acronym for Software Development Life Cycle and encompasses all of the
stages of software development, including requirement gathering and analysis, designing,
coding, testing, deployment, and maintenance.
Ans - Test case is used to check whether an application complies with its requirements. It is
a documented set of circumstances including prerequisites, input values, and expected
outcomes.
Ans - A test scenario is derived from a use case. It's used to test an application's feature
from beginning to end. Multiple test cases can be accommodated by a single test scenario.
When there is a time constraint during testing, scenario testing comes in handy.
10. What is a test plan?
Ans - A test plan is a formal document that specifies the scope of testing, the method to be
used, the resources needed, and the estimated time to complete the testing process. It is
derived from the specifications (Software Requirement Specifications).
Ans - Test data is information that is used to test software with various inputs and
determine whether the resulting output matches the intended result. This data is generated
based on the needs of the company.
Ans - An automated test case created in any programming or scripting language is known as
a test script. These are essentially a collection of instructions for evaluating an application's
functionality.
13. What types of manual testing are there? Break them down.
Black Box
White Box
Integration
Unit
System
Acceptance
14. What is black box testing, and what are the various techniques?
Ans -Software testers employ black-box testing when they do not know the internal
architecture or code structure. The techniques are-
Equivalence Partitioning
Ans - Unlike black-box testing, white box involves analysing the system’s internal
architecture and/or its implementation, in addition to its source code quality.
Statement Coverage
Decision Coverage
Ans - Verification evaluates the software at the development phase, ascertaining whether or
not a product meets the expected requirements. On the other hand, validation evaluates
the software after the development phase, making it sure it meets the requirements of the
customer.
Ans - It’s not furniture. A testbed is an environment used for testing an application,
including the hardware as well as any software needed to run the program to be tested.
Ans - Sanity testing is testing done at the release level to test the main functionalities. It’s
also considered an aspect of regression testing.
Unit/component/program/module testing
Integration testing
System testing
Acceptance testing
Ans - A bug is a fault in the software that’s detected during testing time, while a defect is a
variance between expected results and actual results, detected by the developer after the
product goes live.
Ans -This tests the interface between the software and the end-user. Short for Graphics
User Interface.
These were some basic manual testing interview questions. In the coming section, we bring
to you some advanced level manual testing interview questions.
Ans - Functional testing is a type of black-box testing. It focuses on the software's functional
requirements rather than its internal implementation. A functional requirement refers to
the system's needed behaviour in terms of input and output.
It checks the software against the functional requirements or specification, ignoring non-
functional characteristics like performance, usability, and dependability.
The purpose of functional testing is to ensure that the software up to snuff in terms of
functionality and to solve the difficulties of its target users.
Unit Testing
Integration Testing
Regression Testing
System Testing
Smoke Testing
Performance Testing
Stress Testing
Ans - Non-functional testing examines the system's non-functional requirements, which are
characteristics or qualities of the system that the client has specifically requested.
Performance, security, scalability, and usability are among them.
Human mistakes are eliminated during testing when test scripts are carefully prepared.
CI tools like Jenkins, which may also be set to distribute daily test results to key
stakeholders, can be used to schedule test execution for a nightly run.
Automation testing uses a lot less resources. Test execution requires nearly no time from
QAs once the tests have been automated. QA bandwidth can be used for other exploratory
work.
Ans - Regression Testing is a full or partial selection of already executed test cases that are
re-executed to ensure existing functionalities work fine.
Re-testing: All of the tests in the current test suite are run again. It turns out to be both
pricey and time-consuming.
Regression tests are divided into three categories: feature tests, integration tests, and end-
to-end testing. Some of the tests are chosen in this step.
Prioritization of test cases: The test cases are ranked according to their business impact and
important functionalities.
Ans - A test harness is a collection of software and test data used to put a programme unit
to the test by running it under various conditions such as stress, load, and data-driven data
while monitoring its behaviour and outputs.
Negative Testing
Positive testing ensures that your software performs as expected. The test fails if an error
occurs during positive testing.
Negative testing guarantees that your app can gracefully deal with unexpected user
behaviour or incorrect input.
In this testing, the tester always looks for a single set of valid data.
Testers use as much ingenuity as possible when validating the app against erroneous data.
33. What is a Critical Bug?
Ans - A critical bug is one that has the potential to affect the bulk of an application's
functioning. It indicates that a significant portion of functionality or a critical system
component is utterly broken, with no way to proceed. The application cannot be delivered
to end users until the critical bug has been fixed.
Ans -Test Closure is a document that summarises all of the tests performed throughout the
software development life cycle, as well as a full analysis of the defects fixed and errors
discovered. The total number of experiments, the total number of experiments executed,
the total number of flaws detected, the total number of defects settled, the total number of
bugs not settled, the total number of bugs rejected, and so on are all included in this memo.
Ans -A defect life cycle is a process by which a defect progresses through numerous stages
over the course of its existence. The cycle begins when a fault is discovered and concludes
when the defect is closed after it has been verified that it will not be recreated.
Ans - According to the pesticide paradox, if the same tests are done repeatedly, the same
test cases will eventually stop finding new bugs. Developers will be especially cautious in
regions where testers discovered more flaws, and they may over look Positive and Negative
Testing?
To create a completely new set of test cases to put various aspects of the software to the
test.
To create new test cases and incorporate them into existing test cases.
It is possible to detect more flaws in areas where defect levels have decreased using these
methods.
Ans - API testing is a sort of software testing that entails evaluating application
programming interfaces (APIs) to see if they meet functionality, reliability, performance, and
security requirements. Simply put, API testing is designed to detect defects, inconsistencies,
or departures from an API's expected behaviour. Typically, applications are divided into
three layers:
For business logical processing, the Business Layer or application user interface is used.
API testing is done at the most vital and important layer of software architecture, the
Business Layer, for modelling and manipulating data.
Ans -System testing is a type of testing in which the entire software is tested. System testing
examines the application's compliance with its business requirements.
Ans - Acceptance testing is a type of testing done by a possible end-user or customer to see
if the software meets the business requirements and can be used.
Ans - Bug Leakage - When tested software is pushed into the market and the end-user
discovers defects, this is known as bug leakage. These are bugs that the testing team
overlooked throughout the testing phase.
Bug Release - When a certain version of software is launched into the market with some
known bugs that are expected to be fixed in later versions, this is known as a bug release.
These are low-priority issues that are highlighted in the release notes when sharing with
end-users.
Ans -Defect triage is a procedure in which defects are prioritised depending on a variety of
characteristics such as severity, risk, and the amount of time it will take to fix the fault. The
defect triage meeting brings together several stakeholders - the development team, testing
team, project manager, BAs, and so on – to determine the order in which defects should be
fixed.
Big Bang Integration Testing — After all of the modules have been merged, big bang
integration testing begins.
Hybrid Integration Testing — Hybrid integration testing combines top-down and bottom-up
integration testing techniques. The integration with this approach starts at the middle layer,
and testing is done in both directions.
Ans - Many times, when top-down integration testing is performed, lower-level modules are
not produced until top-level modules are tested and integrated. Stubs or dummy modules
are used in these circumstances to emulate module behaviour by delivering a hard-coded or
predicted result based on the input variables.
Ans - The quantity of code covered by the test scripts is referred to as code coverage. It
conveys the scope of the test suite's coverage of the application.
Ans - A cause-effect graph testing technique is a black-box test design technique that uses a
graphical representation of the input (cause) and output (effect) to construct the test. This
method employs a variety of notations to describe AND, OR, NOT, and other relationships
between the input and output conditions.
Ans -The border values of the classes of the equivalence class partitioning are used as input
to the test cases in boundary value analysis, which is a software testing technique for
designing test cases.
48. What is your approach towards a severely buggy program? How would you handle it?
Ans - In such cases, the best course of action is for testers to go through the process of
reporting any flaws or blocking-type issues that arise, with an emphasis on critical bugs.
Because this sort of crisis might result in serious issues such as insufficient unit or
integration testing, poor design, wrong build or release methods, and so on, management
should be contacted and given documentation as proof of the problem.
49. What if an organization's growth is so rapid that standard testing procedures are no
longer feasible? What should you do in such a situation?
Ans -This is a very prevalent issue in the software industry, especially with the new
technologies that are being used in product development. In this case, there is no simple
answer; however, you could:
Quality issues should be ‘fiercely prioritised' by management, with a constant focus on the
client.
Everyone in the company should understand what the term "quality" implies to the end-
user.
50. When can you say for sure that the code has met its specifications?
Ans - Most businesses have coding "standards" that all developers are expected to follow,
but everyone has their own opinion on what is best, as well as how many regulations are
too many or too few. There are many methods available, such as a traceability matrix, to
guarantee that requirements are linked to test cases. And when all of the test cases pass,
that means the code satisfies the requirement.