 Must-Know [LATEST] Coding Interview Questions and Answers

# Must-Know [LATEST] Coding Interview Questions and Answers

Last updated on 18th Nov 2021, Blog, Interview Questions

Niyati Joshi (Java Software Engineer )

Niyati Joshi is a Java Software Engineer with 5+ years of experience as a Java Specialist. She is an expert in JavaScript, HTML/CSS, SQL, Python, Looker ML, DBT, PDT Looker, Looker API, Lightdash, Snowsight, and CARTO's SQL API. (5.0) | 19178 Ratings 3505

In this Tutorial, we have Provided the Most Common Coding Interview Questions & Answers with Program Logic & Code Examples for you to Practice Programming. We are all aware that answering the most basic coding or programming interview questions determines how we perform in an interview. The interview may be for Java, C++, or a Javascript requirement, but the basis remains the same, that is how strong we are in the foundations of programming logic. Also if our approach is prompt and subtle in an interview, the probability of selection is higher. So read on for cracking the coding interview questions.

1.How can you find the first non-repeated character in a word?

Ans:

In order to answer this question, you first need to understand what must be done to promote this function. A function needs to be written that accepts strings and returns the first non-repeated characters.

For example, in the word, ‘passage’, ‘p’ is the first non-repeated character or in the word, ‘turtle’, ‘u’ is the first non-repeated character. So, how do we solve this problem? We can create a table for storing the repetitions for all the characters and then select the first entries that are not repeated.

In order to write a code that will return the first non-repeated letters, we can use LinkedHashMap to store the character count. This HashMap follows the order of the insertion and characters are initialised in the same position as in the string. The scanned string must be iterated using LinkedHashMap to choose the required entry with the value of 1. Another way to approach this problem is by using firstNonRepeatingChar(String word). This allows the non-repeated character which appears first to be identified in a single pass. This approach used two storage to replace an interaction. This method stores non-repeated and repeated characters separately and when the iteration ends, the required character is the first element in the list.

2.How do you calculate the number of vowels and consonants in a String?

Ans:

• Loop through the string.
• Increase the vowel variable by one whenever the character is found to be a vowel, using the if condition. Otherwise, increment the consonant variable.
• Print the values of both the vowel and the consonant count.

3.How can we check if a number is a prime number?

Ans:

This is one of the most common coding interview questions that involve finding out if the given number is a prime number or not. These kinds of programs are the foundations of algorithmic thinking as we must come up with solutions that are based on the fact that prime numbers are all natural numbers that cannot be divided by positive numbers other than 1.

We must write code to create loops that check each number starting from 1 to the target number to see if the target number is divisible by any other positive number other than itself or 1.

This function will lead us to the solution. When checking for a number that is especially large, then we can simply check till the square root of N, N being the target number. There is no need to check till N in the case of an eligible square root.

If the number is not divisible by 2, there is no need to check if it is divisible by other even numbers, thus decreasing the time required to find the solution. This is an optimized version of the solution where analysing the number before writing the solution comes in handy.

4.How can you check if strings contain only digits?

Ans:

If you wish to write regular expressions for checking if strings are only numbers or if they contain non-digit characters, you must first get comfortable with using character sets in Java regular expressions. Programming languages such as Java support regular expressions with the help of java.util.regex.Matcher class and java.util.regex.Pattern. Java.util.regex is a dedicated package for this purpose.

In order to validate the existence of only numbers using regular expressions, we can use code to analyse if strings contain a raw integer. We will check if the string contains only digits within 0 – 9. Even if the string contains digits but also other characters, it is not a simple numeric string. Regular expressions only check for integer numbers and do not consider dot characters (.), thus, making decimal numbers and floating points fail the test.

5.How can you reverse the words in a target sentence without the help of library methods?

Ans:

This is also one of the very common coding interview questions. First, we must understand the requirement and how to fill the gap in this requirement. When faced with questions such as these, we must first concentrate on asking the right questions. Strings are nothing but sentences of decided characters that might contain a single word or multiple words.

A sentence might also be empty. For example, if we are given the sentence, ‘Programming is fun.’, we must reverse it to, ‘Fun is programming.’ effectively. We must use regular expressions in Java to divide the given strings into spaces followed by applying the reverse()method from the Collections utility class.

Once you are able to divide the strings using regex’\\s’, an array of words will be returned as a result. This also takes care of the words separated using multiple spaces. As soon as the array is returned, you can then choose to create ArrayLists from these arrays followed by using the Collections.reverse()method. This reverses ArrayLists and every word will be reinitialised in the reverse order.

Now, all that is left is using StringBuilder to concatenate multiple strings through ArrayList iteration. One must make sure that size is specified as StringBuilder resizing is a costly process in terms of processing power and memory. The resizing ends up creating new arrays from copying the content from the older arrays.

6.How do you get the matching elements in an integer array?

Ans:

• Declare an array.
• Nest a couple of loops to compare the numbers with other numbers in the array.
• Print the matching elements if found.

7.How can you append texts to files in programming languages such as Java?

Ans:

Appending is very different as compared to the creation of new files and writing data into the new files. In cases of appending, files already exist and we need to simply add text at the end of the file. This is similar to log files as they are constantly updated with the system.

Log files are the perfect example of appending text as applications iteratively keep appending log details into these files. Logging frameworks are not required for this problem, but you must know how to append text into existing files. In order to solve this problem, you must be aware of convenience classes to write character files.

The class has constructors that assume the acceptability of default byte-buffer and character encoding. If you wish to specify the values yourself, you can simply construct the OutputStreamWriter using the FileOutputStream. The availability of files depends on the underlying platforms, which determine if the file might be created or not.

A few platforms allow files to be initialised for writing functions using a single FileWrite or multiple file-writing objects. However, constructors from this class will be failing once the involved file is already initialised. FileWriter is used for writing character streams and FileOutputStream can write raw byte streams.

8.How can you find the largest or smallest number in an array of integers?

Ans:

For this solution, we must code a function or method that can find the largest or smallest number from arrays that are full-fledged integers. We must first create a source file in Java using the name MaximumMinimumArrayDemo.java and copy the written code here for compilation and execution. We can use two variables that we can refer to as ‘largest’ and ‘smallest’ to store the maximum and minimum values respectively from the arrays. The smallest number can be initialised using integer.MIN_VALUE and the largest can be initialised using integer.MAX_VALUE.

With every iteration of the loops that you have initiated, you can compare current numbers with ‘largest’ and ‘smallest’ and update them accordingly. Arrays do not override the toString method in Java, so you can use Arrays.toString() for printing the contents of the target arrays.

You can use this static method to directly call the main function. You must then pass the random arrays through this method to check if the maximum and minimum values have been returned accurately. You can also choose to automate this testing through Unit tests in your IDE.

9.What is a Data Structure?

Ans:

• A data structure is a storage format that defines the way data is stored, organized, and manipulated.
• Some popular data structures are Arrays, Trees, and Graphs.

10.What is an Array?

Ans:

• An array is commonly referred to as a collection of items stored at contiguous memory locations.
• Items stored are of the same type.
• It organizes data so that a related set of values can be easily sorted or searched.

Ans:

• Like an array, a linked list refers to a linear data structure in which the elements are not necessarily stored in a contiguous manner.
• It is basically a sequence of nodes, each node points towards the next node forming a chain-like structure.

12.What is LIFO?

Ans:

• LIFO is an abbreviation for Last In First Out
• It is a way of accessing, storing and retrieving data.
• It extracts the data that was stored last first.

13.What is a Stack?

Ans:

• A stack refers to a linear data structure performing operations in a LIFO (Last In First Out) order.
• In a stack, elements can only be accessed, starting from the topmost to the bottom element.

14.What is FIFO?

Ans:

• FIFO stands for First In First Out.
• It is a way of accessing, storing and retrieving data.
• The data that was stored first is extracted first.
• Till now, you’ve covered some very fundamental coding interview questions. Going ahead you will dive deeper into the subject.

15.What is a Queue?

Ans:

• A queue refers to a linear data structure that performs operations in a FIFO order.
• In a queue, the least recently added elements are removed first as opposed to a stack.

16.How would you find the second largest number in an array?

Ans:

• Loop through the array.
• If the value of i is greater than the highest, store the value of i in highest, and store the value of highest in the second-highest variable.

17.What is Recursion?

Ans:

• Recursion refers to a function calling itself based on a terminating condition.
• It uses LIFO and therefore makes use of the stack data structure.
• The next couple of coding interview questions will explore your knowledge of OOPs.

18.What is the OOPs concept?

Ans:

OOPs stands for Object-Oriented Programming System, a paradigm that provides concepts such as objects, classes, and inheritance.

19.What are the concepts introduced in OOPs?

Ans:

Following are the concepts introduced in OOPs :

• Object – A real-world entity having a particular state and behavior. We can define it as an instance of a class.
• Class – A logical entity that defines the blueprint from which an object can be created or instantiated.
• Inheritance – A concept that refers to an object gaining all the properties and behaviors of a parent object. It provides code reusability.
• Polymorphism – A concept that allows a task to be performed in different ways. In Java, we use method overloading and method overriding to achieve polymorphism.
• Abstraction – A concept that hides the internal details of an application and only shows the functionality. In Java, we use abstract classes and interfaces to achieve abstraction.
• Encapsulation – A concept that refers to the wrapping of code and data together into a single unit.
• This is one of the very common coding interview questions, that often allows the interviewer to branch out into related topics based on the candidate’s answers.

20.ind the number of occurrences of a character in a String?

Ans:

To find the number of occurrences, loop through the string and search for that character at every iteration; whenever it is found, it will update the count.

• int count = 0;
• char search = ‘a’;
• for (int i = 0; i < length; i++) {
• if (str.charAt(i) == search) {
• count++;
• }
• }
• System.out.println(count);

Ans:

• Doubly linked lists are categorized as a special type of linked list in which traversal across the data elements can be done in both directions.
• This is made possible by the presence of two links in every node, one that links to the node next to it and another that connects to the node before it.

22.What is a Graph?

Ans:

• A graph is a particular type of data structure that contains a set of ordered pairs.
• The ordered pairs in a graph are also known as edges or arcs and are most commonly used to connect nodes where the data can be stored and retrieved.

23.Differentiate between linear and non-linear data structure?

Ans:

Linear data structure
Non-linear data structure
It is a structure in which data elements are adjacent to each other It is a structure in which each data element can connect to over two adjacent data elements
Examples of linear data structure include linked lists, arrays, queues, and stacks,Examples of nonlinear data structure include graphs and trees

24.What is a Deque?

Ans:

• A deque is a double-ended queue.
• This is a structure in which elements can be inserted or removed from either end.

25.What’s the difference between Stack and Array?

Ans:

Stack
Array
Stack follows a Last In First Out (LIFO) pattern. What this means is that data access necessarily follows a particular sequence where the last data to be stored is the first one that will be extracted. On the other hand, Arrays do not follow a specific order, but instead can be accessed or called by referring to the indexed element within the array.

26.Which sorting algorithm is the best?

Ans:

• There are many types of sorting algorithms: bubble sort, quick sort, balloon sort, merge sort, radix sort, and more.
• No algorithm can be considered as the best or fastest because they have designed each for a specific type of data structure where it performs the best.

27.Program to find the largest of three given integers

Ans:

function largestVal(a,b,c){ max_val = 0; if(a>b){ max_val=a; } else{ max_val=b; } if(c>max_val){ max_val=c; } return max_val; } largestVal(1,0,9);

28. What are dynamic data structures?

Ans:

1. Dynamic data structures have the feature where they expand and contract as a program runs. It provides a very flexible method of data manipulation because it adjusts based on the size of the data to be manipulated.

2. These 20 coding interview questions that test the conceptual understanding of the candidates give the interview a clear idea on how strong the candidate’s fundamentals are

3. The next set of coding interview questions focus tests the programming expertise of the candidates and dives deep into various related aspects.

4. The code screenshots given along with the below coding interview questions helps you provide the answer to the question, with clarity.

29.How do you reverse a string in Java?

Ans:

• Declare a string.
• Take out the length of that string.
• Loop through the characters of the string.
• Add the characters in reverse order in the new string.
• String str = “hello”;
• String reverse = “”;
• int length = str.length();
• for (int i = 0; i < length; i++) {
• reverse = str.charAt(i) + reverse;
• }
• System.out.println(reverse);

30.How do you determine if a string is a palindrome?

Ans:

31.Explain what a Binary Search Tree is.

Ans:

• A binary search tree is used to store data in a manner that it can be retrieved very efficiently.
• The left sub-tree contains nodes whose keys are less than the node’s key value.
• The right subtree contains nodes whose keys are greater than or equal to the node’s key value.

32.How to find out if the given two strings are anagrams or not?

Ans:

Two strings are anagrams if they contain a similar group of characters in a varied sequence.

• Declare a boolean variable that tells at the end of the two strings are anagrams or not.
• First, check if the length of both strings is the same, if not, they cannot be anagrams.
• Convert both the strings to character arrays and then sort them.
• Check if the sorted arrays are equal. If they are equal, print anagrams, otherwise not anagrams. ### Develop Your Skills with JavaScript Certification Training

Weekday / Weekend Batches

33.How can you remove duplicates from arrays?

Ans:

First, you must use the LinkedHashSet (Set Interface) to retain the original insertion order of the elements into the set. You must use loops or recursion functions to solve these kinds of coding interview questions.

The main factor that we must keep in mind when dealing with arrays is not the elements that have duplicates. The main problem here is removing the duplicates instead. Arrays are static data structures that are of fixed length, thus not possible to be altered. So, to delete elements from arrays, you need to create new arrays and duplicate the content into these new arrays.

First, you must convert the arrays into Arraylists and then create LinkedHashSets from these ArrayLists. If input arrays contain a larger number of duplicates then it can result in multiple temporary arrays, thus increasing the cost of importing the content. This restriction enforces that we approach this problem in a manner that requires less memory and processing power.

We must remove the duplicates but not copy them into the resulting arrays, thus not deleting the duplicates entirely but simply replacing them with 0 as the default value.

34.How would you implement the bubble sort algorithm?

Ans:

Declare an array.

Nest a couple of loops to compare the numbers in the array.

The array will be sorted in ascending order by replacing the elements if found in any other order.

• int[] a = { 1, 2, 7, 6, 4, 9, 12 };
• for (int k = 0; k < a.length; k++) {
• for (int l = 0; l < a.length - l - 1; l++) {
• if (a[l] > a[l + 1]) {
• int t = a[l];
• a[l] = a[l + 1];
• a[l + 1] = t;
• }
• }
• }

35.How to generate random numbers in Python?

Ans:

We can generate random numbers using different functions in Python. They are :

• random() – This command returns a floating point number, between 0 and 1.
• uniform(X, Y) – It returns a floating point number between the values given as X and Y.
• randint(X, Y) – This command returns a random integer between the values given as X and Y.

36.How can you replace or remove characters from strings?

Ans:

Suppose we have a string, ‘Woocommerce’, and we wish to replace the letter ‘r’ with ‘n’, there are multiple methods to achieve this. String classes in Java provide multiple approaches to replace characters inside strings using CharSequence and substrings.

You can easily call a replace method inside the string that will end up replacing the target character and returning the desired character as a result. Strings are immutable in programming languages such as Java.

Thus, every time these operations such as removal or replacements are performed on strings, new string objects are generated by default. There are 4 overloaded methods for replacing strings using Java:

• replace(char oldChar, char newChar)
• replaceAll(String regex, String replacement)
• replace(CharSequence target, CharSequence replacement)
• replaceFirst(String regex, String replacement)
• CharSequence is one of the super interfaces for strings, StringBuilder and StringBuffer, allowing us to pass off any of the objects from these as arguments for this replacement method. replaceAll() ends up replacing every single match with replacement strings while replaceFirst() only replaces the first matches.

All in all, all of these are powerful methodologies that accept regular expression. Java.lang.String class allows all these overloaded methods that can easily replace single characters or substrings in Java.

It is highly recommended to use replaceAll() as this replaces every occurrence of matching characters. Following this approach allows us to expect regular expression patterns, thus garnering more power. This method can also replace every comma with pipes for converting comma-separated files into pile delimited strings.

However, if one wishes to only replace a single character, one can just use the replace() method that takes the old and new given character into consideration.

37.How do you reverse an array?

Ans:

• Loop till the half-length of the array.
• Replace the numbers corresponding to the indexes from the starting and the end.

38.How would you swap two numbers without using a third variable?

Ans:

• Declare two variables and initialize them with values.
• Make b the sum of both numbers.
• Then subtract the sum (b) from a, so a is now swapped.
• Lastly, subtract a from the sum (b), so b is also swapped.
• int a = 10; int b = 20; b = b + a; // now b is sum of both the numbers a = b – a; // b – a = (b + – a = b (a is swapped) b = b – a; // (b + – b = a (b is swapped)

39.Print a Fibonacci series using recursion?

Ans:

The Fibonacci numbers are the numbers in the following integer sequence :

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144……

We can calculate them using the mathematical formula used in the Fibonacci recursive function.

public static int fibonacci(int n) {

if (n <= 1){

return n;{

return fibonacci(n – 1) + fibonacci(n – 2);{

}{

public static void main(String args[]) {{

int n = 10;{

System.out.println(fibonacci(n));{

}{

40.How do you find the factorial of an integer?

Ans:

• A factorial is a function that multiplies a number by every number below it. For example, 5!= 5*4*3*2*1=120.
• Recursive function multiples the numbers until it reaches 1.
• public static long factorial(long n) {

if (n == 1)

return 1;

else

return (n * factorial(n – 1));

}

41.How do you reverse a Linked List?

Ans:

Apply the descending iterator method to the linked list.

This reverses the order of elements in the linked list.

42.How would you implement Binary Search?

Ans:

• Binary search divides the array into half in every iteration step until it finds the element.
• It works on the sorted arrays since it compares the values of adjacent elements and then calculates the mid number.
• If the value of low becomes greater than high at any point, it means the element is not present in the list.

43.What are Binary Trees?

Ans:

• A binary tree is an extension of the linked list structure where each node has at most two children.
• A binary tree has two nodes at all times, a left node and a right node.

44.How do you remove all occurrences of a given character from the input string?

Ans:

Use the built-in string method “replace” to replace a character with any other character, including symbols and white spaces.

• String str1 = “Australia”;
• str1 = str1.replace(“a”, “”);
• System.out.println(str1); // australia

45.Showcase Inheritance with the help of a program?

Ans:

The class Cat inherits the property color from the class Animal by extending the parent class (Animal).

This way a class Cat can have more parent classes if it wishes to inherit their properties.

Example :

Ans:

Class Animal {

String color;

}

class Cat extends Animal {

void meow() {

System.out.println(“Meow”);

}

}

Ans:

When a class has two or more methods with the same name, they are called overloaded methods.

47.How do you check if the given number is prime?

Ans:

Use if statements to check for each condition separately :

If the number is 0 or 1, it cannot be prime.

If the number is 2, it is a prime number.

If the number is indivisible by other numbers, it is prime.

48.How do you sum all the elements in an array?

Ans:

• Use a for loop to iterate through the array and keep adding the elements in that array.
• int[] array = { 1, 2, 3, 4, 5 };
• int sum = 0;
• for (int i : array)
• sum += i;
• System.out.println(sum);

49.Why is Java known as the “platform-independent programming language”?

Ans:

Interviewers ask this question because they want to determine whether you know the basic features and foundations of Java code and their real-world benefits. When answering this question, make it clear to the interviewer you know the platform independence feature was one of the primary purposes for creating Java code and how this feature creates real-world benefits in application. You can use the STAR interview technique when describing the real-world application benefits of this feature by describing a specific example of code you have written on one platform that runs across multiple platforms.

Example answer: “One of the primary purposes for Java code was to create a programming language that developers could use across multiple platforms without having to change the source code for each platform. Platform independence means the execution of your program is not dependent on the operating system being used. Earlier programming languages, such as C and C++, require developers to compile separate source code for every operating system they run it on.

For example, at my last job, I wrote Java code using a Linux operating system. We could then run this byte code on any other operating system, such as Microsoft or MAC, by converting the code using the Java Virtual Machine, which is available to install on all operating systems. This saves the developers time as we only have to write the source code once.”

50.Give an example of a time when you had to work with a team to solve a problem.

Ans:

An interviewer might ask this question to determine your ability to work with a team and if you can add to their company culture. When answering this question, focus on the skills that would make you an asset to the company’s team and how you have used those skills to successfully complete team projects in the past.

Example answer : “In my prior role, I was a member of a team of developers working on an enterprise-class application to develop a customer relationship management system. Our team functioned by assigning each developer a different piece of code to write. After I finished writing the code assigned to me, I helped the team finish the project early by helping other developers work on their code.”

51.Write a Java program for the Fibonacci series.

Ans:

This question is another specific exercise that can show your knowledge of using Java code to complete a task. The interviewer probably wants to see that you can arrive at the correct solution in an acceptable amount of time. This is an ideal time to explain your process aloud as you write your code to show the interviewer your thought process.

Output :

52.Write a Java program to show scroll up and scroll down.

Ans:

This question is a basic task that you could receive regardless of your experience level. Remember to explain your process carefully as you write the lines.

53.Write a Java program to reverse a string without using the String inbuilt function.

Ans:

This is another specific Java coding exercise the interviewer could use to test your Java knowledge and experience.

Output :

54.Write a program to count the total number of characters in a string?

Ans:

function Charcount(string){

var length =0;

while(string[length]){

length++;

}

return length;

}

console.log(Charcount(“sikandar”));

• Explanation :– Here in console.log() we are calling the function Charcount(“sikandar”) by passing the string sikandar , and the function will return us the length of the string and console.log() will print the length of the string to the console window.
• We are initializing length with value zero in the function.
• At line 3 the loop starts the reading character starting with index zero and it will increment the length by 1 inside the loop. once it completes reading , it returns the length of the string.

55.Write a program to Capitalize the first letter of a String?

Ans:

• function Capitalize(name){
• var newName= name.charAt(0).toUpperCase()+name.slice(1);
• console.log(newName);
• }
• Capitalize(“sikandar”);
• name.charAt(0) gives the character at index zero ,toUpperCase() converts it into capital letter and name.slice(1) removes the first character of the string

56.How to Find Factorial of a number using JavaScript

Ans:

So what is the factorial of a number :-The factorial of a number is the product of all the numbers from 1 to that number.

Example :-

57.Find the longest word in a string

Ans:

We are converting the string into an array element based on space between them. We have a variable initialized with zero, loop will iterate until till the length of the array, Inside loop we check newstr[i].length>longestWord if it’s true then we are assigning the new length to the longest length. and outside of the loop we are printing it.

58.how to replace all occurrence of word in a string Javascript

Ans:

function replaceAll(str){ var patern = “tech”; console.log(str.replaceAll(patern,”technology”)); } replaceAll(“pathstage is a tech and tips and tricks blog”);

We are replacing all the occurrences of tech with technology. pretty straight forward and self explanatory.

59.Find the greatest number in the array

Ans:

We are initializing max with the value at 0 index of the array, And iterating the loop till the length of the array. Inside the loop we are checking if the value at max is less than the value at the particular index in the array then we are assigning the value in max.

60.Find the lowest number in the array

Ans:

61.How to Swap two numbers without using a third variable.

Ans:

62.What is a negative index in Python?

Ans:

Python has a special feature like a negative index in Arrays and Lists. Positive index reads the elements from the starting of an array or list but in the negative index, Python reads elements from the end of an array or list. ### Get JOB Oriented JavaScript Training for Beginners By MNC Experts

• Instructor-led Sessions
• Real-life Case Studies
• Assignments

63.Write a program to check if a value exists in an array?

Ans:

function elementExist(element){

var arr =[1,2,3,4,5,6,7];

if(arr.indexOf(element)!==-1){

console.log(“Element Exist…”);

}

else{

console.log(“Element does not exists…”);

}

}

elementExist(2);

In If condition We are using indexOf() method to check whether a given value or element exists in an array or not.indexOf() method returns the index of the element inside the array if it is found, and returns -1 if it is not found.

64.Write a program to remove duplicate from an array

Ans:

Let’s understand the code, So here we are receiving an array of elements as a function argument i.e oldarr , Then we are creating a new array i.e newarr , we are pushing all the unique elements into this array. At line 3 we are calculating the length of the array and storing in a variable len.We could do this inside for loop as well but in for loop each time there will be length calculation when the loop iterates which would be more expensive. Inside the loop we have a condition where we are checking if the element doesn’t exist in the new array using JavaScript indexOf method ,if the element doesn’t exist already then we are pushing the element.

65.Write a Program to Check Prime Number

Ans:

A prime number is a number which is divisible by 1 and itself only, In other words, n > 1 is a prime if it can’t be evenly divided by anything except 1 and n. Examples are 2, 3, 5, 7, 11, 13, 17,…

• function isPrime(num) {
• for(var i = 2; i < num; i++)
• if(num % i === 0){
• return false;
• }
• return true;
• }
• isPrime(17);

In the above program a number is passed as an argument to the function, The for loop is being used to iterate through the positive numbers to check if the number is divisible by positive numbers.

The condition number % i == 0 checks if the number is divisible by numbers other than 1 and itself.

If the remainder value is evaluated to 0, that number is not a prime number, and we are returning false else true.

66.Write a program to check a string is palindrome or not

Ans:

Pa.indrome :

Ans:

In the above code ,We are splitting the string reversing it and then joining ,this will form a new string. And then comparing the new string with the original one.

If both the strings are equal then this is a palindrome else it’s not a palindrome.

67.How to convert a list into a string?

Ans:

When we want to convert a list into a string, we can use the <”.join()> method which joins all the elements into one and returns as a string.

Example :

Ans:

Weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]

listAsString = ‘ ‘.join(weekdays)

print(listAsString)P

68.Program to check if a given positive number is multiple of 3 or multiple of 7.

Ans:

• function checkMultiple(num){
• if(num%3==0||num%7==0){
• return true;
• }
• else{
• return false;
• }
• }
• checkMultiple(12);

69.Program to check if a string starts with ‘Java’ return true else false.

Ans:

70.How does variable declaration affect memory?

Ans:

• The amount of memory that is to be reserved or allocated depends on the data type being stored in that variable.
• For example, if a variable is declared to be “integer type”, 32 bits of memory storage will then be reserved for that particular variable.

71.Program to check if the last digits of three given positive integer is same.

Ans:

function checkLast(x,y,z){

if((x>0)&&y>0&&z>0){

return (x%10==y%10 && y%10==z%10 && x%10==z%10)

}

else{

return false;

}

}

checkLast(100,50,60);

72.What is the output of the below program?

Ans:

>>>names = [‘Chris’, ‘Jack’, ‘John’, ‘Daman’],

>>>print(names[-1][-1])

T.e output is : n

73.Program to find the sum of an array of numbers.

Ans:

74.Program to Replace One Character With Another

Ans:

• function replaceChar(str, a, b){
• var newstr = [];
• for(var i=0; i< str.length;i++){
• if(str[i]=={
• newstr.push(b)
• }
• else{
• newstr.push(str[i])
• }
• }
• console.log(newstr.join(”));
• }
• replaceChar(“Hi sikandar kumar”, “r”,”.”);

75.How do you debug a Python program?

Ans:

By using this command we can debug a python program

\$ python -m pdb python-script.py

76.What is the < Yield > Keyword in Python?

Ans:

The < yield > keyword in Python can turn any function into a generator. Yields work like a standard return keyword.

But it’ll always return a generator object. Also, a function can have multiple calls to the < yield > keyword.

Example :

Ans:

def testgen(index):

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]

yield weekdays[index]

yield weekdays[index+1]

day = testgen(0)

print next(day), next(day)

Output : sun mon

77.Program to Check number is palindrome or not in JavaScript

Ans:

78.How to convert a list into a tuple?

Ans:

By using Python < tuple() > function we can convert a list into a tuple. But we can’t change the list after turning it into a tuple, because it becomes immutable.

Example :

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]

listAsTuple = tuple(weekdays)

print(listAsTuple)

Output : (‘sun’, ‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’, ‘sat’)

79.How to convert a list into a set?

Ans:

Users can convert the list into a set by using the < set() > function.

Example :

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’,’sun’,’tue’]

listAsSet = set(weekdays)

print(listAsSet)

ou.put : set([‘wed’, ‘sun’, ‘thu’, ‘tue’, ‘mon’, ‘fri’, ‘sat’])

80.How to count the occurrences of a particular element in the list?

Ans:

In Python list, we can count the occurrences of an individual element by using a < count() > function.

Example # 1 :

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sun’,’mon’,’mon’]

print(weekdays.count(‘mon’))

Ou.put : 3

Example # 2 :

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sun’,’mon’,’mon’]

print([[x,weekdays.count(x)] for x in set(weekdays)])

ou.put : [[‘wed’, 1], [‘sun’, 2], [‘thu’, 1], [‘tue’, 1], [‘mon’, 3], [‘fri’, 1]]

81.What is the NumPy array?

Ans:

NumPy arrays are more flexible than lists in Python. By using NumPy arrays, reading and writing items is faster and more efficient.

82.How can you create an Empty NumPy Array In Python?

Ans:

We can create Empty NumPy Array in two ways in Python,

1. import numpy

numpy.array([])

2.numpy.empty(shape=(0,0))

83.How to check if a key exists in a JavaScript object

Ans:

• var person ={
• name:”sikandar”,
• surname:”kumar”,
• age:27
• }
• //it will print true in case the key exists else false.
• console.log(“name” in person);

84.What is the output of the below code?

Ans:

>> import array

>>> a = [1, 2, 3]

>>> print a[-3]

>>> print a[-2]

>>> print a[-1]

The output is : 3, 2, 1

85.Program to check if two given integer values are in the range 50…99. Return true if either of them are in said range.

Ans:

• function checkInRange(x,y){
• if((x>=50 && x<=99) || (y>=50 && y<=99)){
• return true;
• }
• else{
• return false;
• }
• }
• checkInRange(60,80);

86.What is the Enumerate() Function in Python?

Ans:

The Python enumerate() function adds a counter to an iterable object. enumerate() function can accept sequential indexes starting from zero.

Python Enumerate Example :

subjects = (‘Python’, ‘Interview’, ‘Questions’)

for i, subject in enumerate(subjects):

print(i, subject)

Output :

0 Python

1 Interview

2 Questions

93.What is the output, Suppose list1 is [1, 3, 2], What is list1 * 2?

Ans:

[1, 3, 2, 1, 3, 2]

88. How do you Concatenate Strings in Python?

Ans:

We can use ‘+’ to concatenate strings.

Python Concatenating Example :

# See how to use ‘+’ to concatenate strings.

>>> print(‘Python’ + ‘ Interview’ + ‘ Questions’)

89.How would you implement the insertion sort algorithm?

Ans:

We assume the first element in the array to be sorted. The second element is stored separately in the key. This sorts the first two elements. You can then take the third element and do a comparison with the ones on the left of it. This process will go on until a point where we sort the array.

• int[] a = { 1, 2, 7, 6, 4, 9, 12 };
• for (int m = 1; m < a.length; m++) {
• int n = m;
• while (n > 0 && a[n – 1] > a[n]) {
• int k = a[n];
• a[n] = a[n – 1];
• a[n – 1] = k;
• n–;
• }
• }

90.How to print the sum of the numbers starting from 1 to 100?

Ans:

We can print sum of the numbers starting from 1 to 100 using this code :

print sum(range(1,101))

# In Python the range function does not include the end given. Here it will exclude 101.

# Sum function print sum of the elements of range function, i.e 1 to 100.

Are you looking training with Right Jobs?