competitive programming.doc
competitive programming.doc
Ans: Data structures play a major role in programming. Let us know some of the
important reasons.
2. Non-Decreasing Array
You have been given an integer array/list 'ARR' of size 'N'. Write a solution to check if it
could become non-decreasing by modifying at most 1 element. We define an array as
non-decreasing, if ARR[i] <= ARR[i + 1] holds for every i (0-based) such that (0 <= i <=
N - 2).
Input format :
The first line of each test case contains an Integer 'N' denoting the size of the array/list.
The second line of each test case contains 'N' space-separated Integers denoting the
array/list.
Output format :
For each test case, print a single line containing "true" if it's possible to make 'ARR'
non-decreasing array with modifying at most one element or "false" otherwise. The
output for every test case will be printed in a separate line.
Solution:
As we are allowed at most one modification, we can try it on every index separately and
naively check whether the array becomes non-decreasing by any modification. For this,
we can modify the starting index (i.e. 0) to a very less value (say INT_MIN) and the rest
of the indexes as the value of the preceding element if present (i.e. ARR[i] = ARR[i - 1]).
Space Complexity: O (1)
Time Complexity: O (N ^ 2), where ‘N’ is the length of the array. For every index, we
are modifying it and linearly checking if this modification makes the array
non-decreasing. Hence, time complexity will be O (N ^ 2).
3. Merge K Sorted Arrays
You have been given ‘K’ different arrays/lists, which are sorted individually (in
ascending order). You need to merge all the given arrays/list such that the output
array/list should be sorted in ascending order.
Solution:
Create an output array ‘RESULT’. Traverse all the given arrays from start to end and
insert all the elements in the output array ‘RESULT’. Sort the ‘RESULT’ and return it.
Space Complexity Explanation:
O (N * K), Where ‘K’ is the number of arrays and ‘N’ is the average number of elements
in every array. We are using an array/list of size O (N * K) to store all the elements of the
‘K’ arrays/lists. Then, we are sorting the output array in ascending order which takes
at-least log (N * K) additional space. Thus, the total space complexity is O (K * N).
Time Complexity: O((N * K) * log(N * K)), Where ‘K’ is the number of arrays and ‘N’
is the average number of elements in every array. We are traversing all the ‘K’ arrays and
then we are sorting the output array. Thus, the total time complexity will be
The idea is based on the divide and conquers strategy. We take pairs of arrays at each
step. Then merge the pairs using the two-pointer technique of merging two sorted arrays.
Thus, after merging all the pairs, the number of arrays will reduce by half. We will
continue this till the number of remaining arrays doesn’t become 1.
4. Find Unique
You have been given an integer array/list (ARR) of size N. Where N is equal to [2M + 1].
Now, in the given array/list, 'M' numbers are present twice and one number is present
only once. You need to find and return that number which is unique in the array/list.
Solution:
The task is to find the unique number in an array where all other numbers occur twice.
The array size is given by N = 2M + 1, where M is the number of elements occurring
twice. Loop through the array and use a hash map to count the occurrences of each
number. Return the number with a count of 1, as it is the unique number. Space
Complexity: O (1), Time Complexity: O(N)
5. Sort Linked List
You are given a Singly Linked List of integers which is sorted based on absolute value.
You have to sort the Linked List based on actual values. The absolute value of a real
number x, denoted |x|, is the non-negative value of x without regard to its sign.
Example: If the given list is {1 -> -2 -> 3} (which is sorted on absolute value), the
returned list should be {-2 -> 1 -> 3}.
Solution:
We will use the ‘Insertion Sort’ algorithm to sort the given linked list.
Algorithm:
We will make a list ‘SORTED_LIST’ which is initially empty and it stores the list after
sorting.
We will traverse the given list and insert the node in the ‘SORTED_LIST’ such that
nodes are present in sorted order.
If ‘SORTED_LIST’ is empty or the head of the ‘SORTED_LIST’ has a value greater than
the node, in this case, the current node will become the new head of ‘SORTED_LIST’.
Else, we will traverse the ‘SORTED_LIST’ until we find the node that has a value greater
than the current node or until we reach the end.
We will insert the node at this position and change it’s ‘next’ value such that it points to
the node which is greater than the current node.
Space Complexity: O(n) Explanation: O(N), where ‘N’ is the number of nodes in the
linked list.
In the worst case, it takes O(N) time to insert the node in ‘SORTED_LIST’, and
traversing the list takes O(N) time. Thus, the final time complexity is O(N ^ 2).
Space Complexity: O (N), Where N is the number of nodes in the linked list. We are
storing node values in a stack which will take O (N) extra space.
Time Complexity: O(N), Where N is the number of nodes in the linked list. We are
traversing the list twice and traversing a list takes O(N) time, thus the final time
complexity is O(2 * N) = O(N).
bool isPalindrome(Node *head) {
stack visitedNodes;
// push all nodes in the stack
Node *cur = head;
while (cur != NULL)
{
visitedNodes.push(cur);
cur = cur->next;
}
cur = head;
while (cur != NULL)
{
// compare node values
Node *temp = visitedNodes.top();
if (cur->data != temp->data)
{
return false;
}
visitedNodes.pop();
cur = cur->next;
} return true;
}
7. Diameter Of Binary Tree
You are given a Binary Tree. You are supposed to return the length of the diameter of the
tree. The diameter of a binary tree is the length of the longest path between any two end
nodes in a tree.
Recursion
The basic idea of this approach is to break the problem into subproblems. Now, there are
three possible cases:
The diameter of the tree is present in the left subtree.
The diameter of the tree is present in the right subtree.
The diameter of the tree passes through the root node.
Let us define a recursive function, ‘getDiamter’, which takes the root of the binary tree as
input parameter and returns the diameter of the given subtree rooted at the “root” node.
We can easily find the diameter of the left subtree and right subtree by recursion. The
main task is to calculate the diameter of the tree corresponding to point 3 mentioned
above.
From the above figure, we can observe that if the diameter passes through the root node,
then it can be written as the length of the longest path between the leaves which passes
through the root. And we can get that using the height of the left and right subtrees. Now,
assume a function, ‘getHeight,’ which returns the height of the subtree rooted at the
“root” node. The longest path length(i.e., Number of edges in the path) between the
leaves can be written as: 1 + getHeight(left child of the root node) + getHeight(right child
of the root node)
Algorithm:
If the ‘root’ node is NULL, return 0. The diameter of an empty tree is 0.
Recur for the left subtree and store the diameter of the left subtree in a variable
‘leftDiameter’, i.e. ‘leftDiameter’ = getDiameter(left child of the root node)
Similarly, recur for the right subtree and store the diameter of the right subtree in a
variable ‘rightDiameter’ i.e. ‘rightDiameter’ = getDiameter(right child of the root node)
Now, get the height of the left subtree and right subtree and store it in a variable.
‘leftHeight’ = getHeight(left child of the root node)
‘rightHeight’ = getHeight(right child of the root node)
The diameter of the given tree will be the maximum of the following terms:
‘leftDiameter’
‘rightDiameter’
1 + ‘leftHeight’ + ‘rightHeight’
Return the maximum of above terms i.e.max(leftDiameter, rightDiameter, 1 + leftHeight
+ rightHeight).
Space Complexity: O(n) Explanation: O(N), Where ‘N’ is the number of nodes in the
given binary tree. Since we are doing a recursive tree traversal and in the worst case
(Skewed Trees), all nodes of the given tree can be stored in the call stack. So the overall
space complexity will be O(N).
Time Complexity: O (n^2) Explanation: O (N^2), Where ‘N’ is the number of nodes in
the given binary tree. We are traversing through every node of the binary time that takes
O(N) time, and we are calculating the height for every node, and in the worst case
(Skewed Trees), the getHeight() function will take O(N) time. So the overall time
complexity will be O (N^2).
int getHeight(TreeNode *root) {
if (root == NULL)
{
// Height of empty tree is 0.
return 0;
} // Get the height of left subtree.
int leftHeight = getHeight(root->left);
// Get the height of right subtree.
int rightHeight = getHeight(root->right);
// Height of the given binary tree will be 1 greater than maximum of "leftHeight" and
"rightHeight".
int height = max(leftHeight, rightHeight) + 1;
return height;
}
int getDiameter(TreeNode *root)
{
if (root == NULL)
{
// Diameter of an empty tree will be 0.
return 0;
}
// Get the height of left and right subtrees.
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
// Recur for left subtree and get the diameter.
int leftDiameter = getDiameter(root->left);
// Recur for right subtree and get the diameter.
int rightDiameter = getDiameter(root->right);
// Diameter of given binary tree.
int diameter = max(leftDiameter, max(rightDiameter, leftHeight + rightHeight));
return diameter;
}
int diameterOfBinaryTree(TreeNode *root)
{
return getDiameter(root);
}
Examples:
Input: 1 1
/ \ / \
2 3 2 3
/ /
4 4
Input: 1 1
/ \ / \
2 3 5 3
/ /
4 4
Time Complexity: O(min(N, M)), Where N and M are the sizes of the trees
Auxiliary Space: O(log min(N, M)), due to auxiliary stack space used by
recursion calls
Using Morris traversal:
The basic idea behind the Morris traversal approach to solve the problem of
checking if two binary trees are identical is to use the Morris traversal
algorithm to traverse both trees in-order simultaneously, and compare the nodes
visited at each step.
Time Complexity: O(V + E), the Time Complexity of this method is the same
as the time complexity of DFS traversal which is O(V+E).
Auxiliary Space: O(V). To store the visited and recursion stack O(V) space is
needed.
MCQ
1) Which of the following commands will you use to load data files into tables?
a) mysqlimport
b) mysqldump
c) mysqlexport
d) mysqladmin
4) MySQL is capable of reading input from a file in batch mode. This is also
known as the non-interactive mode. A lot of typing and time can be saved
when commands are stored in a file and executed from a file.
Is the above statement True or False?
a) True
b) False
6) Which one is the correct declaration for choosing the character set other than
default?
a) Varchar(20) character set;
b) Varchar(20) character set utf8;
c) Varchar(20);
d) None of the above
12) Can we use a BOOLEAN datatype in functions that are called from SQL
statements?
a) Yes
b) Sometimes yes depending on the condition
c) No
13) Which among the below statements is used for terminating a loop based
on a condition in PL/SQL?
a) GOTO
b) KILL
c) EXIT WHEN
d) CONTINUE WHEN
1)
2)
3)
4)
5)
6)
7)
8)
9)
10)
11)
12)
13)
14)
15) What is the default state of an uninitialized associative array variable?
a) Error
b) Undefined
c) NULL
d) Empty
16) Which among the below keywords is used for initializing the variables
instead of using the assignment operator?
a) NOTNULL
b) %TYPE
c) %ROWTYPE
d) DEFAULT
17) An SQL query to delete a table from the database and memory while
keeping the structure of the table intact?
a) DROP TABLE table_name;
b) DROP FROM TABLE table_name;
c) DELETE FROM TABLE table_name;
d) TRUNCATE TABLE table_name;
26) What allows us to define how various tables are related to each other
formally in a database?
a) Views
b) Foreign Key Constraints
c) Primary Key Constraints
d) Database manager
30) What command is used for restoring the backup of PostgreSQL which
was created using pg_dump?
a) psql -R db_dump.psql db_name
b) psql -r db_dump.psql db_name
c) psql -f db_dump.psql db_name
d) psql -F db_dump.psql db_name
SQL Vs MySQL
Key Category SQL MySQL
MySQL PostgreSQL
1) It is a Relational Database Management 1) It is an Object-Relational Database Management
System. System.
2) MySQL was developed by a Swedish 2) PostgreSQL was developed by the Department
company called MySQL AB in 1995. of Computer Science, University of California.
3) MySQL is not completely ACID compliant.
It supports ACID only when used in InnoDB 3) PostgreSQL is completely ACID compliant.
and NDB.
4) In addition to its simplicity and reliability, 4) The PostgreSQL database is more complex and
MySQL is also fast and efficient. slower than MySQL.
MySQL PostgreSQL
5) MySQL is easy to troubleshoot as it has a
5) PostgreSQL is not easy to troubleshoot.
nice and devoted community ready to help.
6) Users cannot be assigned object-level
6) Users can be assigned object-level privileges.
privileges.
7) Only partially SQL compliant. 7) PostgreSQL is fully SQL compliant.
8) It is licensed under GNU GPU 8) It is licensed under the MIT style.
9) It is written in C/C++. 9) It is written in C.
10) MySQL is best suited for simple operations
10) In general, PostgreSQL is a good fit for systems
like read and write. For web-based projects
that perform large and complex queries, as well
requiring only simple data transactions,
as those that store and analyze data.
MySQL is a good choice.
11) PostgreSQL supports standard data types and in
11) MySQL supports standard data types like addition to these data types, PostgreSQL also
string, numeric, date and time, etc. supports advanced data types such as arrays,
hstore, and user-defined data types.
12) There is no support for table inheritance and
materialized views in MySQL. A 12) Table inheritance and materialized views are
materialized view is a pre-computed query both supported by PostgreSQL.
result that can be used later
13) It does not provide table inheritance. 13) It provides table inheritance.
14) PostgreSQL has a number of join capabilities
14) Join capabilities in MySQL are limited. like inner join, right join, left join, cross join,
full outer join, natural join, and self join.
15) MVCC is one of the most important reasons
15) MySQL does not provide support for
companies choose PostgreSQL. It handles
MVCC.
concurrency better than MySQL.
16) MySQL has a multilayer structure having a 16) PostgreSQL is a unified database storage server
set of storage engines. and has a single storage engine.
17) MySQL provides a workbench as a user 17) PostgreSQL provides PgAdmin as a user
interface. interface.
18) Every connection created in MySQL is an 18) Every connection created in PostgreSQL is an
Operating System (OS) thread. Operating System (OS) process.
19) It has native Server Sockets Layer (SSL)
support. SSL is a security protocol that 19) It has native Transport Layer Security (TLS)
creates a secure encrypted link between a support. TLS is an improved version of SSL.
web server and a web browser.
20) It does not support partial, bitmap, or 20) PostgreSQL supports partial, bitmap, or
expression indexes. expression indexes all of these.
21) Replication in PostgreSQL is synchronous
21) Replication in MySQL is one-way
replication where the master database is
asynchronous replication where one server
synchronized with the slave database. It utilizes
is used as primary and others as replicas.
two database instances running simultaneously.
MySQL PostgreSQL
22) Companies that use MySQL: 22) Companies that use PostgreSQL:
Facebook, Tesla, YouTube, Airbnb, NASA Apple, Cisco, Netflix, Reddit, Spotify, Fujitsu
SQL PL/SQL
SQL is a natural language meant for the interactive
PL/SQL is a procedural extension of SQL.
processing of data in the database.
PL/SQL supports all features of procedural language
Decision-making and looping are not allowed in SQL.
such as conditional and looping statements.
All SQL statements are executed at a time by the
PL/SQL statements are executed one block at a time
database server which is why it becomes a
thereby reducing the network traffic.
time-consuming process.
There is no error handling mechanism in SQL. This supports an error handling mechanism.
SQL vs NoSQL
SQL databases are a type of system NoSQL databases are a type of software
software that supports management, that allows to maintain and retrieve
Define
analysis, capturing and querying the structured, unstructured, polymorphic data
structured data in a relational format. for different purposes.
Query SQL databases support Structured NonSQL does not have any declarative
Language Query Languages. query language.
SQL does not support hierarchical NoSQL is best suited for hierarchical
Data Storage
storage of data. storage of data.
SQL databases can only be run on a NoSQL databases are designed to follow
Distributed
single system and hence, does not data distribution features like repetition,
Data
follow distribution of data. partition.
Top
Companies Microsoft, Dell, Cognizant, etc. Amazon, Capgemini, Adobe, etc.
Using
SQL supports databases like MySQL, Nosql databases are Hbase, MongoDB,
Examples
SQL Server, Oracle, etc. Redis, etc.
What is Normalization?
What is Denormalization?
Normal Forms are used to eliminate or reduce redundancy in database tables. The
different forms are as follows:
Students Table
Windsor Street
Ansh Dracula (Bram Stoker) Mr.
777
As we can observe, the Books Issued field has more than one value per record, and
to convert it into 1NF, this has to be resolved into separate individual records for
each book issued. Check the following table in 1NF form -
A relation is in second normal form if it satisfies the conditions for the first normal
form and does not contain any partial dependency. A relation in 2NF has no
partial dependency, i.e., it has no non-prime attribute that depends on any proper
subset of any candidate key of the table. Often, specifying a single column Primary
Key is the solution to the problem. Examples -
Example 1 - Consider the above example. As we can observe, the Students Table
in the 1NF form has a candidate key in the form of [Student, Address] that can
uniquely identify all records in the table. The field Books Issued (non-prime
attribute) depends partially on the Student field. Hence, the table is not in 2NF. To
convert it into the 2nd Normal Form, we will partition the tables into two while
specifying a new Primary Key attribute to identify the individual records in the
Students table. The Foreign Key constraint will be set on the other table to ensure
referential integrity.
Here, WX is the only candidate key and there is no partial dependency, i.e., any
proper subset of WX doesn’t determine any non-prime attribute in the relation.
A relation is said to be in the third normal form, if it satisfies the conditions for the
second normal form and there is no transitive dependency between the non-prime
attributes, i.e., all non-prime attributes are determined only by the candidate keys
of the relation and not by any other non-prime attribute.
1 Ms.
2 Mr.
3 Mrs.
P -> QR
RS -> T
Q -> S
T -> P
For the above relation to exist in 3NF, all possible candidate keys in the above
relation should be {P, RS, QR, T}.
Note: All aggregate functions described above ignore NULL values except for the
COUNT function.
A scalar function returns a single value based on the input value. Following are the
widely used SQL scalar functions:
● ROUND() - Calculates the round-off integer value for a numeric field (or
decimal point values).
1) In the Student table, the marks column contains a list of values separated by
commas. How can you determine the number of values in this
comma-separated list?
);
FROM Student
WHERE id = 1;
Output:
1 SELECT GETDATE();
1 SELECT SYSTDATE();
5. Write a query to retrieve the first four characters of EmpLname from the
EmployeeInfo table.
6. Write a query to fetch only the place name(string before brackets) from the
Address column of EmployeeInfo table.
Using SUBSTRING
7. Write a query to create a new table which consists of data and structure
copied from the other table.
9. Write a query to find the names of employees that begin with ‘S’
SELECT COUNT(*), Gender FROM EmployeeInfo WHERE DOB BETWEEN '02/05/1970 ' AND
1
'31/12/1975' GROUP BY Gender;
Q13. Write a query to fetch all the records from the EmployeeInfo table
ordered by EmpLname in descending order and Department in the
ascending order.
To order the records in ascending and descnding order, you have to use the ORDER BY
statement in SQL.
To retrieve the even records from a table, you have to use the MOD() function as
follows:
1 SELECT EmpID FROM (SELECT rowno, EmpID from EmployeeInfo) WHERE MOD(rowno,2)=0;
Similarly, to retrieve the odd records from a table, you can write a query as follows:
1 SELECT EmpID FROM (SELECT rowno, EmpID from EmployeeInfo) WHERE MOD(rowno,2)=1;
Q20. Write a SQL query to retrieve employee details from EmployeeInfo
table who have a date of joining in the EmployeePosition table.
Q21. Write a query to retrieve two minimum and maximum salaries from
the EmployeePosition table.
To retrieve two minimum salaries, you can write a query as below:
1 SELECT DISTINCT Salary FROM EmployeePosition E1
2 WHERE 2 >= (SELECTCOUNT(DISTINCT Salary)FROM EmployeePosition E2
3 WHERE E1.Salary >= E2.Salary) ORDER BY E1.Salary DESC;
To retrieve two maximum salaries, you can write a query as below:
1 SELECT DISTINCT Salary FROM EmployeePosition E1
2 WHERE 2 >= (SELECTCOUNT(DISTINCT Salary) FROM EmployeePosition E2
3 WHERE E1.Salary <= E2.Salary) ORDER BY E1.Salary DESC;
Q22. Write a query to find the Nth highest salary from the table without
using TOP/limit keyword.
1 SELECT Salary
2 FROM EmployeePosition E1
3 WHERE N-1 = (
4 SELECT COUNT( DISTINCT ( E2.Salary ) )
5 FROM EmployeePosition E2
6 WHERE E2.Salary > E1.Salary );
Q23. Write a query to retrieve duplicate records from a table.
To display the first record from the EmployeeInfo table, you can write a query as follows:
1 SELECT * FROM EmployeeInfo WHERE EmpID <= (SELECT COUNT(EmpID)/2 from EmployeeInfo);
Q32. How do you read the last five records from a database using a SQL
query?
To retrieve the last five records from a database using a SQL query, you can use the ORDER
BY clause combined with LIMIT. Here’s an example query:
SELECT *
FROM your_table
ORDER BY id DESC
LIMIT 5;
Q33. Write a SQL query that will provide you with the 10th-highest
employee salary from an Employee table.
Here’s an example SQL query:
SELECT salary
FROM (
FROM Employee
) AS ranked_salary
● Primitive
o Numbers
o Strings
o Boolean
o Symbol
● Trivial
o Undefined
o Null
● Composite
o Objects
o Functions
o Arrays
3. Which symbol is used for comments in JavaScript?
Comments prevent the execution of statements. Comments are ignored while the
compiler executes the code. There are two type of symbols to represent comments
in JavaScript:
/*
Multi-line comments
...
*/
Here, 3 and 2 behave like an integer, and “7” behaves like a string. So 3 plus 2
will be 5. Then the output will be 5+”7″ = 57.
The negative infinity is a constant value represents the lowest available value. It
means that no other number is lesser than this value. It can be generate using a
self-made function or by an arithmetic operation. JavaScript shows the
NEGATIVE_INFINITY value as -Infinity.
Yes, it is possible to break the JavaScript code into several lines in a string
statement. It can be broken by using the backslash n ‘\n’.
For example:
1. Undefined: It occurs when a variable is declare not not assign any value.
Undefined is not a keyword.
5. <!DOCTYPE html>
6. <html lang="en">
7. <head>
8. <title>Document</title>
9. </head>
10.
11. <body>
12. <button onclick="create()">
13. Click Here!
14. </button>
15.
16. <script>
17. function create() {
18. let geeks = document.createElement('geeks');
19. geeks.textContent = "Geeksforgeeks";
20. geeks.setAttribute('class', 'note');
21. document.body.appendChild(geeks);
22. }
23. </script>
24. </body>
25. </html>
10. What are global variables? How are these variables declared, and what are
the problems associated with them?
In contrast, global variables are the variables that define outside of functions.
These variables have a global scope, so they can be used by any function
without passing them to the function as parameters.
Example:
javascript
26. let petName = "Rocky"; // Global Variable
27. myFunction();
28.
29. function myFunction() {
30. console.log("Inside myFunction - Type of petName:", typeof
petName);
31. console.log("Inside myFunction - petName:", petName);
32. }
33.
34. console.log("Outside myFunction - Type of petName:", typeof petName);
35. console.log("Outside myFunction - petName:", petName);
Output
36. Inside myFunction - Type of petName: string
37. Inside myFunction - petName: Rocky
38. Outside myFunction - Type of petName: string
39. Outside myFunction - petName: Rocky
It is difficult to debug and test the code that relies on global variables.
The prompt box is a dialog box with an optional message prompting the user to
input some text. It is often used if the user wants to input a value before entering a
page. It returns a string containing the text entered by the user, or null.
14. What is the ‘this’ keyword in JavaScript?
15. Explain the working of timers in JavaScript. Also elucidate the drawbacks
of using the timer, if any.
The timer executes some specific code at a specific time or any small amount of
code in repetition to do that you need to use the
functions setTimout, setInterval, and clearInterval. If the JavaScript code sets
the timer to 2 minutes and when the times are up then the page displays an alert
message “times up”. The setTimeout() method calls a function or evaluates an
expression after a specified number of milliseconds.
● SessionState: It is user specific that can access all the data on the web
pages.
● while loop:
● for loop:
● do while:
22. Explain how to read and write a file using JavaScript?
The readFile() functions is used for reading operation.
The variable typing is the type of variable used to store a number and using that
same variable to assign a “string”.
Geeks = 42;
Geeks = "GeeksforGeeks";
25. Explain how to detect the operating system on the client machine?
To detect the operating system on the client machine, one can simply use
navigator.appVersion or navigator.userAgent property. The Navigator appVersion
property is a read-only property and it returns the string that represents the version
information of the browser.
● Alert
● Confirm
● Prompt
27. What is the difference between an alert box and a confirmation box?
An alert box will display only one button which is the OK button. It is used to
inform the user about the agreement has to agree. But a Confirmation box displays
two buttons OK and cancel, where the user can decide to agree or not.
The void(0) is used to call another method without refreshing the page during the
calling time parameter “zero” will be passed.
30. What is the ‘Strict’ mode in JavaScript and how can it be enabled?
Strict Mode is a new feature in ECMAScript 5 that allows you to place a program
or a function in a “strict” operating context. This strict context prevents certain
actions from being taken and throws more exceptions. The statement “use strict”
instructs the browser to use the Strict mode, which is a reduced and safer feature
set of JavaScript.
document.getElementById("GFG").checked;
console.log(get_func_inner());
console.log(get_func_inner());
console.log(get_func_inner());
Output
1
1
1
38. How many ways an HTML element can be accessed in JavaScript code?
There are four possible ways to access HTML elements in JavaScript which are:
● getElementById() Method: It is used to get the element by its id name.
● getElementsByClass() Method: It is used to get all the elements that have the
given classname.
● getElementsByTagName() Method: It is used to get all the elements that have the
given tag name.
● querySelector() Method: This function takes CSS style selector and returns the
first selected element.
1) Interactive Enhancement
2) JavaScript interacts with static web pages and makes them respond to users'
inputs.
3) Quick Feedback
4) There is no reason for a page on the internet to load again when using
JavaScript. For example, form input validation.
7) Frameworks
8) JavaScript has vast libraries and frameworks that can be widely used to
develop games and web-based applications.
● Cross-platform compatible
● Open-source
● Object-oriented
When one wants to move out of a function, one can do so using generators, and the
outer code determines when to move back into the function.
With the help of generators, one can control an asynchronous call outside the code.
Most importantly, though, the next value can come in only when needed; all values
do not need to come back at once
Pending: This is the first state of the promise and shows that the promise has been
neither fulfilled nor rejected.
Rejected: This state represents the failure of the asynchronous operation due to
some reason. In other words, the promise has been rejected.
Settled: This is the last state of the promise, showing that the promise has been
either fulfilled or rejected.
A promise constructor uses a callback with two parameters - resolve and reject - to
create a promise. The resolve function is called when the asynchronous operation
has succeeded. The reject function is called when the asynchronous operation has
failed.
Primitive
● Numbers
● Strings
● Boolean
Composite
● Objects
● Functions
● Arrays
Trivial
● Null
● Undefined
The ES6 Javascript version introduced Arrow functions. With the Arrow functions,
we can declare functions using new and shorter syntax. These functions can only
be used as function expressions. The declaration of these functions is done without
using the function keyword. Moreover, if there is a single returning expression,
then even the return keyword is not needed. Additionally, wherever the code occurs
in a single line only, we can omit the curly {} braces. If there is only one argument
in a function, then we can omit even the () parenthesis.
10. What are the main differences between Java and JavaScript?
The language was developed by Brenden Eich in 1995 when he was working as an
employee of netscape. He is also the founder of Mozilla foundation.
Classes in Javascript are templates for building objects. Classes bind the data with
code so that the data works as per the code. They were introduced in the ES6
version of Javascript and while they were created on prototypes, they also have
syntax and semantics that are not common with ES5. Classes can be seen as special
functions. There are two components of class syntax: class expressions and class
declarations.
Class expressions are one of the ways to define classes. They may or may not have
names. If a class expression has a name, it is held locally in the class body but can
be accessed through the name property. Before using class expressions, one must
declare them.
Another way to define classes is class declaration. For declaring a class, the class
keyword must be followed by the class name.
One class may use the properties of methods of another class by using the extend
keyword. Classes in Javascript must follow the strict mode. If the strict mode is not
followed, errors will appear.
The ES6 version of Javascript introduced the rest parameter and spread operator.
Rest Parameter
The use of three dots (...) before any parameter shows a rest parameter. This
improves the handling of function parameters. With the help of the rest parameter,
we can create such functions that can take a different number of arguments. By
using the rest parameter, all these arguments will be converted into arrays. The rest
parameter can also be used to extract any or all parts of an argument.
Spread Operator
Though the spread operator syntax is the same as that of the rest parameter, the
spread operators help to spread arrays and object literals. Another use of spread
operators is when one or more arguments are expected to be in a given function
call. So, while the rest parameter creates an array, a spread operator spreads an
array.
Here's a simple method to create arrays with JavaScript using the array literal:
Temporal dead zone (TDZ) was introduced for the first time in the ES6 version of
JavaScript. TDZ is a behavior that occurs when a variable is accessed before it is
initialized. It is a language construct that helps to catch errors as accessing data
before initializing it is incorrect. When let and const keywords are used to declare
variables a TDZ may occur.
WeakMap object stores key-value pairs with weakly referenced keys. Keys in
WeakMap must only be objects, while values can be arbitrary. Primitive data types
cannot be keys in WeakMap. Since native WeakMap contains weakly referenced
keys, these keys can be garbage collected and therefore references get removed.
Also, because of the weak referencing, garbage collection of values in WeakMap is
not prevented. When information about a key is valuable ‘only if’ the key is not
garbage collected, WeakMap is useful in mapping keys to the information about
them.
● Variable names can't start with a numeric value. They should only begin with
the letter or underscore character.
In JavaScript, the functions are objects that can take different functions as
arguments and be returned by other functions. A callback is a JavaScript function
passed to another function as an argument, or parameter. This function is executed
when the function that it is passed to gets executed.
23. How to debug JavaScript code?
Modern web browsers, such as Chrome, Firefox, etc., include a built-in debugger
that can be opened anytime by pressing the appropriate key, typically the key F12.
The negative infinity is a constant value that represents the lowest available value.
This means that no number is less than this value. Negative Infinity is calculated
by dividing a negative number by zero.
25. Which character is used to split JavaScript Code spanning into multiple lines?
The backslash, '' character, is used at the end of the first line if the JavaScript code
is spread across multiple lines.
Undeclared variables are variables that do not exist in the program and therefore
are not declared. If a program attempts to determine the values of an undefined
variable, it will fail because of a runtime error.
Undefined variables refer to ones declared by the program but not given a value. If
the program attempts to find the values of an undefined variable the variable is
returned with an undefined value.
It displays an interactive dialog box that displays an optional prompt for users to
enter some text. It is typically used when users want to enter a number before
entering a webpage. This returns either a string containing the user's input text or a
null.
29. What is NULL in JavaScript?
"this" refers to an object running the current line of code. It is a reference to the
object which executes the current function. If the function that is being referenced
is a regular one, "this" references the global object. If the function is a method of
the object, "this" refers to the object itself.
Timers can be used to execute the code at an exact time or repeat the code within
an interval. This can be accomplished by employing the methods setTimeout,
setInterval, and clearInterval.
The // character is for single-line comments, and the /* */ characters are used for
multi-line comments.
SessionState: It's user-specific containing the data of the user session and allows
access to all data on the web pages.
The === operator is a strict comparison operator, meaning it checks for both the
value and the type of two variables.
JavaScript supports automatic type conversion. This is the most common method
of type conversion that JavaScript developers use.
36. Define Variable Typing in JavaScript.
Variable typing allows you to assign a numerical value to a variable. The same
variable could be assigned to a string.
37. What is the main difference between "==" and "===" in JavaScript?
== tests only for value equality; however, "===" is a stricter equality test that
returns false if the value or the type of two variables is different.
38. How to find the operating system in the client machine using JavaScript?
The pop-up boxes available in JavaScript are Alert, Confirm, and Prompt.
Void(0) stops pages from refreshing, and "zero" is used to pass the parameter while
calling.
An alert box shows only one button, an OK button. A confirmation box has two
buttons: the OK and Cancel buttons.
Cookies are small text files saved on the computer. They are created to store the
required information when users browse the website. Examples include Users
Name information and information about shopping carts from previous visits.
This pop() method works like the shift() method. However, the difference is the
shift method operates from the beginning of the array. The pop() method takes the
final element off of the given array and returns it. The array upon which it is called
is then altered.
A break statement is a way to exit the current loop. The continue statement
continues with the next statement of the loop.
The blur function removes the focus from the specified object.
The 4 and 2, in this case, behave as integers, and "8" behaves like a string.
Therefore 4 + 2 equals 6. The output is 6+"8" = 68.
By calling the window.print() method in the browser, we can print the content of
the current window in JavaScript.
while loop: A while loop control flow statement that allows code to run repeatedly
in response to a Boolean condition. The while loop is considered a repeated if
statement.
for loop: A for loop offers an easy structure to write. In contrast to a while loop, for
statement combines an initialization process, condition, and increment/decrement
in one line, thereby giving a simpler, easier-to-understand looping structure.
do while: A do-while loop can be like a while loop, but with the exception that it
examines the condition after executing the statements, which is why it's an instance
of the Exit Control Loop.
The process of reading a cookie with JavaScript is also very easy. We can use the
document.cookie string to store the cookies we have just created with the string.
If you'd like to delete a cookie, so that future attempts to read it in JavaScript return
nothing, then you must change the date of expiration to a date in the past. Defining
the cookie's path is important to ensure you erase the correct cookie. Certain
browsers won't allow you to delete a cookie if the path is not specified.
To create cookies using JavaScript, you must assign a string value to the
document.cookie object.
Attributes- It provides more details on an element like id, type, value, etc.
Here are the methods by which an HTML element can be used in JavaScript code:
getElementsByClass('classname'): Gets all the elements that have the given class
name.
getElementsByTagName('tagname'): Gets all the elements with the given tag name.
querySelector(): It returns the first selected element using a CSS style selector.
There are three ways that a JavaScript code can be used in the HTML file: Inline,
Internal, and External.
Inline JavaScript
Internal JavaScript
External JavaScript
It's used to add elements to the front of the array and provides the updated length
of the array. It's similar to a push method, which inserts elements at the beginning
of the array.
13. What is a Typed language?
Dynamically: In this case, the variable could contain multiple types; just like in JS
variables, a variable can be a number or characters.
Statically: In this case, the variable can only hold one data type. Like Java, the
variable declared of string can hold only one set of characters.
15. What is the difference between Local storage & Session storage?
Local Storage: The data is not transmitted directly to the server with each HTTP
request (HTML, images, JavaScript, CSS, etc), thus reducing the traffic between
the server and the client. It remains until removed manually through settings or
software.
Session Storage: It is identical to local storage; the only difference is that while the
data stored locally does not expire, whereas in session storage, it is deleted when
the session is over. Session Storage is removed once the browser closes.
JavaScript window can be described as a global object that contains properties and
methods that interact with it.
The document is a part of the window and is considered as the property of the
window.
innerText - innerText returning the entire text that is contained within an element as
well as its child elements.
This parseInt() function can convert numbers between different bases. This
function returns an integer of a base specified in the second argument of the
parseInt() method.
Imports and exports allow the writing of modular JavaScript code. With the help of
exports and imports, we can break the code into multiple files.
Strict Mode in JavaScript is a way to opt into a restricted variant of the language,
which enforces stricter parsing and error handling rules. It helps developers write
more secure and efficient code by catching common mistakes and potential bugs
that might otherwise go unnoticed.
When enabled, Strict Mode may throw errors for code that previously worked
without any issues, but it does so in order to catch potential issues that could lead
to bugs or security vulnerabilities. Strict Mode also disables some features of
JavaScript that could be problematic or confusing, such as the automatic creation
of global variables.
Overall, Strict Mode is a useful tool for writing safer and more reliable JavaScript
code, but it requires developers' care and attention to use effectively.
Let and var are utilized for method and variable declarations within JavaScript.
The primary difference between them is the scope in which these variables are
used. The variables that are declared using ‘Let’ are only used within the block
where they are declared. The variables declared by ‘Var’ are available across the
function where they are declared.
22. Demonstrate the importance of isNaN() function in JavaScript.
The isNaN() function is used to determine whether the given value is an illegal
number or not. If it returns true, the value is a NaN - Not a number. Else returns
false. It differs from the Number.isNaN() method.
Syntax errors- These occur when the code violates the rules of the JavaScript
language. For example, a missing semicolon, an unclosed string, or an unexpected
token.
Logical errors - These occur when the code does not produce the desired outcome,
but there is no error message displayed. Logical errors are usually caused by
mistake in the code's logic or algorithm.
Runtime errors- These occur when the code is syntactically correct and logically
sound, but still throws an error during execution. For example, accessing an
undefined variable, calling a function that does not exist, or attempting to divide by
zero.
The first step to debugging a JavaScript program is to identify the error. This can
be done by using the JavaScript console in the browser’s developer tools. The
console will display any errors that occur during script execution such as syntax
errors, type errors, and reference errors. Once the error has been identified, the
code can be examined line by line to find the source of the issue and the issue can
be addressed.
2. How would you create a function that takes two numbers and adds them
together?
To create a function that takes two numbers and adds them together, you can use
the following code snippet:
We can retrieve a character from a certain index using the charAt() function.
The .map() and .forEach() methods are both used to iterate over an array, but the
.map() method can be used to transform an array by returning a new array with the
same number of elements but with different values. The .forEach() method is used
to perform an action on each element in the array without returning a new array.
For example:
8. How would you go about creating a method that returns the sum of all the
elements in an array?
To create a method that returns the sum of all the elements in an array, you can use
the Array.prototype.reduce() method. For example:
document.getElementById("myText").style.fontSize = "14px;
document.getElementById("myText").className = "anyclass";
10. How can you get rid of duplicates from a JavaScript array?
There are two ways we can eliminate duplicates from the JavaScript array:
The filter() method can use three arguments: arrays, current element, and the
current element's index.
The For loop involves iterating through the original array and checking whether
each element has already been added to a new array. If it hasn't, the element is
added; if it has, it is skipped.
11. Explain how to read and write a file using JavaScript?
12. How can you target a particular frame from a hyperlink in JavaScript?
This can be done by using the target attribute in the hyperlink. Like
JavaScript:
JScript:
14. How can we hide JavaScript code from old browsers that don't support
JavaScript?
To hide the JavaScript codes from old browsers that do not have support for
JavaScript, you can make use of:
The majority of browsers from the past will consider it as a long comment of
HTML. New browsers that support JavaScript will treat it as an online message.
Alternatively, you could use the "noscript" element to provide alternative content
that will display for users who do not have JavaScript enabled.
15. Can you explain the usage of Internal and External JavaScript Code?
When there are only a few lines of code for a particular webpage, it is preferable to
keep JavaScript code internal within the HTML document.
However, if the JavaScript code is used on multiple web pages, it is advisable to
keep the code in a separate file.
Screen objects read the information from the screen of the client. Some properties
of screen objects are
● Height: Provides the total height of the screen along with the taskbar
● Width: Provides the total width of the screen, including the taskbar
Nested functions: These are defined inside other functions and called every time
the main function is called.
When the page loads, HTML code parsing is paused by default till the time the
script has not fully executed. this happens when the server is slow or the script is
heavy, and the web page gets delayed. So by using Deferred script , scripts
execution is delayed till the HTML parser rums. this helps reduce the loading time
of web pages and they can be displayed faster.
Whenever the user clicks the link or fills out a form, events take place. Events are
the actions that come off as a result of activities. An event handler serves to
manage the proper execution of all these events. They are an extra attribute if the
object which includes the vent's name and action is taken when the event takes
place.
To define a class in JavaScript, you can use the class keyword. For example:
26. Explain event bubbling.
Window.onload is an event that is fired when the page has finished loading. This
event is often used to perform tasks that need to be done after the page has loaded,
such as setting up event handlers, initializing components, or making AJAX
requests.
On the contrary, onDocumentReady is an event that is fired when the page's HTML
document is ready to be interacted with. This event is often used to perform tasks
that need to be done when the page is ready, such as setting up event handlers,
initializing components, or making AJAX requests.