51 string interview questions (coding problems with solutions)

String interview questions

String questions come up frequently in coding interviews and you'll need to understand them thoroughly if you want to land a software engineering job. 

Here's a quick list of string interview questions to get started with: 

  • Given a string, create a new string without vowels and print that string.
  • Given a string, create a new string with the same characters in a random order.
  • Given a string containing some words in (possibly nested) parentheses, calculate if all parentheses match.
  • Find the longest common prefix of two given strings.
  • Given two strings, find the shortest edit distance to transform the first into the second.

Below, we have a much more extensive list of questions, including links to high quality solutions for each question.  

And if you need a refresher on string basics, we also have a tutorial and cheat sheet towards the end of this guide. 

Now let's get to the questions!  

  • Easy string interview questions
  • Medium string interview questions
  • Hard string interview questions
  • String basics
  • String cheat sheet
  • Mock interviews for software engineers

Click here to practice coding interviews with ex-FAANG interviewers

1. easy string interview questions.

You might be tempted to try to read all of the possible questions and memorize the solutions, but this is not feasible. Interviewers will always try to find new questions, or ones that are not available online. Instead, you should use these questions to practice the fundamental concepts of strings.

As you consider each question, try to replicate the conditions you’ll encounter in your interview. Begin by writing your own solution without external resources in a fixed amount of time.

If you get stuck, go ahead and look at the solutions, but then try the next one alone again. Don’t get stuck in a loop of reading as many solutions as possible! We’ve analyzed dozens of questions and selected ones that are commonly asked and have clear and high quality answers.

Here are some of the easiest questions you might get asked in a coding interview. These questions are often asked during the ‘phone screen’ stage, so you should be comfortable answering them without being able to write code or use a whiteboard.

1.1 Remove Vowels from a String 

  • Text guide (GeeksforGeeks)
  • Video guide (Kevin Naughton Jr.)

1.2 Defanging an IP Address

  • Code example (LeetCode)

1.3 Jewels and Stones

  • Text guide (Memogrocery)

1.4 Shuffle String

  • Text guide (Medium/RKP)
  • Video guide (Knowledge Mavens)

1.5 Split a String in Balanced Strings

  • Text guide (GeeksForGeeks)

1.6 To Lower Case

  • Text guide (Dev.to/Seanpgallivan)
  • Video guide (Nick White)

1.7 Unique Morse Code Words

1.8 count substrings with only one distinct letter.

  • Text guide (HelloACM)
  • Video guide (GeeksForGeeks)

1.9 Robot Return to Origin

  • Text guide (LeetCode)

1.10 Fizz Buzz

  • Text guide (ITNext/Kevin)
  • Video guide (Tom Scott)

1.11 First Unique Character in a String

  • Text guide (AfterAcademy)

1.12 Reverse String

1.13 valid anagram.

  • Video guide (Terrible Whiteboard)

1.14 Valid Palindrome

  • Text guide (Medium/Urfan)

1.15 Implement Strstr()

  • Text guide (RedQuark)
  • Video guide (Amell Peralta)

1.16 Valid Parentheses

  • Video guide (Back to Back SWE)

1.17 Roman to Integer

  • Video guide (Thecodingworld)

1.18 Longest Common Prefix

1.19 excel sheet column number.

  • Video guide (Knowledge Center)

1.20 Palindrome Permutation

2. medium string interview questions.

Here are some moderate-level questions that are often asked in a video call or onsite interview. You should be prepared to write code or sketch out the solutions on a whiteboard if asked.

2.1 Longest Substring Without Repeating Characters

  • Text guide (Medium/Nerd For Tech)
  • Video guide (Michael Muinos)

2.2 Longest Palindromic Substring

  • Video guide (NeetCode)
  • Video guide (Errichto)

2.3 String to Integer (atoi)

  • Text guide (Medium/Hary) 
  • Video guide (TECH DOSE)

2.4 Letter Combinations of a Phone Number

  • Text guide (Dev.to/Seanpgallivan) 

2.5 Generate Parentheses

  • Text guide (RedQuark) 

2.6 Count and Say

  • Text guide (GeeksforGeeks) 

2.7 Group Anagrams

  • Text guide (Techie Delight) 

2.8 Decode Ways

  • Text guide (Toronto CS) 
  • Video guide (CS Dojo)

2.9 Palindrome Partitioning

2.10 word break.

  • Text guide (ProgrammerSought) 
  • Video guide (Happygirlzt)

2.11 Fraction to Recurring Decimal

2.12 largest number.

  • Text guide (Easy Explanations) 
  • Video guide (Jayati Tiwari)

2.13 Implement Trie (Prefix Tree)

  • Text guide (Medium/Saurav) 

2.14 Basic Calculator II

  • Text guide (Medium/Calvin) 

2.15 Longest Substring with At Least K Repeating Characters

2.16 palindrome partitioning.

  • Text guide (LeetCode) 
  • Video guide (BacktoBackSWE)

2.17 Reorganize String

2.18 zigzag conversion.

  • Video guide (Google Engineer Explains)

2.19 Decode String

  • Text guide (Medium/Signal Cat)

2.20 Multiply Strings

  • Text guide (Medium/Nikhil Anand)

3. Hard string interview questions

Similar to the medium section, these more difficult questions may be asked in an onsite or video call interview. You will likely be given more time if you are expected to create a full solution.

3.1 Regular Expression Matching

  • Video guide (NeetCode) 

3.2 Wildcard Matching

  • Text guide (Techie Delight)
  • Video guide (Tushar Roy) 

3.3 Minimum Window Substring

  • Text guide (Medium/Algo Shaft)
  • Video guide (Back to Back SWE) 

3.4 Word Ladder

  • Video guide (Nick White) 

3.5 Word Break II

  • Text guide (Educative)
  • Video guide (Babybear4812) 

3.6 Word Search II 

  • Text guide (Medium/Hary)
  • Video guide (Timothy H Chang) 

3.7 Serialize and Deserialize Binary Tree

  • Text guide (Dev.to/Akhilpolke)
  • Video guide (BacktoBack SWE) 

3.8 Longest Valid Parentheses

  • Video guide (Algorithms Made Easy) 

3.9 Edit Distance

3.10 alien dictionary (string/graph).

  • Text guide (Medium/Timothy)
  • Video guide (Happygirlzt) 

3.11 Design Search Autocomplete System

  • Code example (Cheonhyangzhang)

4. String basics

In order to crack the questions above and others like them, you’ll need to have a strong understanding of strings and how they work. Let’s get into it.

4.1 What is a string?

A string is an ordered sequence, or string, of characters. It is usually considered a data type and is often included as part of language primitives. In most languages, strings are implemented using an array of bytes. The bytes are encoded using some character encoding. Earlier systems used ASCII encoding, with Unicode encoding used in later systems.

4.1.1 Types of strings (Java, Python, C++)

C++ provides a mutable string, meaning the string contents can be changed after creation.

Python and Java provide an immutable string type. Immutable strings require a new string to be created if any changes are made. This has performance implications for string concatenation when joining a number of strings, running in quadratic time.

Java provides a mutable StringBuilder class, which should be used for concatenating multiple strings. In Python, generally the `.join` method on strings should be used, which accepts an iterable of multiple strings. Using Java's StringBuilder or Python’s `.join` provides a linear time solution for multiple string concatenations. 

Another class of strings are C-style strings, so named as they are used in the C language. These strings are simple arrays. A special terminating character is stored directly after the last character of the string. This terminating character marks the end of the string within the array, or buffer. C++ has support for C-style strings, but it is preferable to use C++ style strings in pure C++ code.

Java, Python and C++ strings are more complex data structures, with class or struct methods for manipulating and querying them.

4.1.2 How strings store data

There are generally two types of string implementations: null-terminated strings (C strings), and non-null-terminated strings. The principal difference between these types of strings is how the termination and tracking the length of the string is handled. 

Null-terminated strings (C strings) are character arrays terminated with a null (NUL) character, typically a byte with all bits set to 0. The length of the string is calculated by counting the characters in the string up to the terminating character. Care must be taken in working with C-style strings, as writing and reading past the end of the string terminator can result in buffer overflow errors, causing unexpected behaviour and security issues by overwriting or reading unrelated memory contents.

Non-null-terminated strings, as used in C++, Java and Python implementations, have the underlying array and the length stored separately. In Java this is a class with private fields for the character array and length, which are not directly accessible from outside the class. 

C++, Java and Python strings have useful class and instance methods to work with strings. Commonly used are: 

  • Substring queries to return a new string from a subset of the original string
  • Replace methods to return a new string with a specific sequence of character substituted for another
  • String formatters to create strings from a template and data variables
  • Trimming methods to create new strings without leading or trailing whitespace
  • Upper and lower case conversion methods
  • Methods to check if a string contains a given substring 

For more advanced pattern matching in strings, Regular Expressions, or regexes, are commonly used. Most modern string implementations have support for regex queries.

4.1.3 Deep dive into tries

A trie, or prefix tree, is a type of search tree, often used with strings. The strangely spelt name is from "reTrieval," but is mostly pronounced as "try." Tries are useful for answering questions like, "Given an input sequence 'cod,' what possible words could be formed?" This makes tries useful for auto-completing words in text input in a range of use cases, including search and texting . 

A trie data structure is made of nodes indexed with a single character key. Each node has references to its child nodes. The number of child nodes is bounded by the number of unique characters in the alphabet space making up the stored words. Often this is described as 26 for the English language, but it can be larger when taking into consideration accented characters, or if there are numeric and special characters in the alphabet space. Each node also has a flag signaling the end of a word, represented by a blue node below:

Strings explanation

Since each node only contains one character, the complete key to that node is distributed from its parents down to that node. Retrieval of a key is a depth-first search of the trie. A search for a key ends when the end of the word node is reached. Inserting a new key is done by following the trie through each character of the new key, and adding each character as a trie node where needed, and marking the node of the last character as the end of the word. 

Inserting and searching is O(keySize) time. Space requirements are much larger than a simple string though, at O(AlphabetSpace*keySize*n), n being the total number of keys in the trie.

5. Strings cheat sheet

String definition: A string is a sequence of characters, often implemented as an array.

String interview questions cheat sheet

You can download this cheat sheet here.

5.1 Related algorithms and techniques

  • State Machines  
  • String Builder
  • Two pointers
  • Backtracking
  • Levenshtein Distance
  • Boyer-Moore string search algorithm
  • Knuth-Morris-Pratt Algorithm
  • Rubin-Karp Algorithm
  • Bitap algorithm
  • BW Data transform

5.2 Cheat sheet explained

The cheat sheet above is a summary of information you might need to know for an interview, but it’s usually not enough to simply memorize it. Instead, aim to understand each result so that you can give the answer in context.

The cheat sheet is broken into time complexity (the processing time for the various string operations) and space complexity (the amount of memory required). While you might be asked about these directly in relation to string data structures, it’s more likely that you will need to know these in relation to specific string-related algorithms, such as substring searching, which is what the second section of the cheat sheet details.

For more information about time and space requirements of different algorithms, read our  complete guide to big-O notation and complexity analysis .

5.2.1 Time complexity

Accessing a character at a particular index in a string is an O(1) operation, as strings are stored as arrays. Deleting characters from immutable strings means creating a new string and copying the remaining characters over, so this is an O(n) operation. For mutable strings, it means removing characters and shifting remaining characters, which is also O(n). Inserting into a string is a similar level of work as deleting, again O(n) time for both mutable and immutable strings.

Searching for a substring using built-in methods in most languages is generally O(n*m), depending on the algorithm used. We explain this more in the algorithm section.

Slicing, or splitting, a string refers to creating multiple substrings by splitting a string on a character or character sequence. This is often used in parsing CSV type files. It runs in O(n) time, as each character needs to be copied out into the new strings. 

Joining, or concatenating, strings is a more complex operation. For immutable strings, concatenating multiple strings can result in O(n 2 ) time complexity for large numbers of strings. In such cases, StringBuilder, or Python's '.join()' method is recommended. For concating two mutable strings, it is O(n+m), where n and m represent the number of characters in either string. Mutable strings can concatenate faster, depending on the underlying implementation. For implementations where the array is doubled in size each time a resizing is needed, string concatenation is closer to regular array time complexity.

Comparing strings is also O(n) time, as generally each character needs to be checked. 

For tries, there are two significant operations: Inserting a new key, and retrieving (searching for) a key. Both run in O(m) time, where m is the size of the key. This makes tries very scalable, as the time complexity is not dependent on the size of the trie itself.

5.2.2 String algorithm complexity

Radix sort is usually shown in the context of sorting numbers, but it can be used to sort strings, if the buckets are indexed by characters rather than numbers. Essentially the alphabet space of the strings becomes the base as used by the radix sort algorithm.

Many string algorithms center around searching for all occurrences of a substring within a string. This is a fundamental operation in text-centered applications, from HTTP processing to word processing. The naive implementation slides the search pattern by one character over the length of the string to check for the pattern starting at each index. This makes it an O(m*(n-m+1)) operation, as the pattern needs to be checked at each character in the string. The more sophisticated algorithms in the list attempt to reduce this complexity. These algorithms reduce the time by using strategies such as precomputing tables, creating rolling hashes, and using caching state from previous matching. They also use the fact that useful information for shortcutting the naive search approach is available in the search pattern itself, for example, whether or not the search pattern has repeating characters can allow some sliding indexes to be skipped. In all, these algorithms provide ways to reduce searching to O(n) time complexity.

6. Mock interviews for software engineers

Before you start practicing interviews, you’ll want to make sure you have a strong understanding of not only linked lists but also the rest of the relevant data structures. Check out our guides for questions, explanations and helpful cheat sheets.

  • Linked lists
  • Stacks and Queues
  • Coding interview examples (with solutions)

Once you’re confident on all of the data structure topics, you’ll want to start practicing answering coding questions in an interview situation. One way of doing this is by practicing out loud, which is a very underrated way of preparing. However, sooner or later you’re probably going to want some expert interventions and feedback to really improve your interview skills.

That’s why we recommend practicing with ex-interviewers from top tech companies. If you know a software engineer who has experience running interviews at a big tech company, then that's fantastic. But for most of us, it's tough to find the right connections to make this happen. And it might also be difficult to practice multiple hours with that person unless you know them really well.

Here's the good news. We've already made the connections for you. We’ve created a coaching service where you can practice system design interviews 1-on-1 with ex-interviewers from leading tech companies. Learn more and start scheduling sessions today.

Interview coach and candidate conduct a video call

Learn Java and Programming through articles, code examples, and tutorials for developers of all levels.

  • online courses
  • certification
  • free resources

Top 21 String Programming and Coding Interview Questions With Solutions

21 string programming and coding interview questions.

21 String Coding Problems from Java Interviews

  • 75+ Coding Problems from Interviews ( questions )
  • 10 Free Courses to learn Data Structure and Algorithms ( courses )
  • 10 Books to Prepare Technical Programming/Coding Job Interviews ( books )
  • 10 Courses to Prepare for Programming Job Interviews ( courses )
  • 100+ Data Structure and Algorithms Interview Questions ( questions )
  • My favorite Free Algorithms and Data Structure Courses on FreeCodeCamp ( courses )
  • 30+ linked list interview questions with a solution ( linked list )
  • 30+ array-based interview questions for programmers ( array )
  • 10 Coding Tips and 101 Coding Questions for Interviews ( tips )
  • 50+ Algorithm based Interview questions from HackerNoon ( questions )
  • 5 Free Courses to learn Algorithms in-depth ( courses )
  • 10 Algorithms books every Programmer should read ( books )
  • Top 5 Data Structure and Algorithms Courses for Programmers ( courses )

10 comments:

Hi guys, here the first question is "How to find the maximum occurring character in given String?" but the solution link is for "How to Count Occurrences of a Character in String" Both are different, Please confirm...

string problem solving questions

Yes, you are right but once you know how to count character then the other one becomes simple because you just need to return the character with maximum count

boolean b=true;

yes both are different example 1)How to find the maximum occurring character in given String?" Malyalaum - a-3 (a is the maximum occurring character in given string) 2) How to Count Occurrences of a Character in String Malyalaum m-2 a-3 y-1 u-1 thank you,

That's correct but once you know how to count character then the other one becomes simple because you just need to return the character with maximum count

public class OccObj { public static void main(String[] args){ Scanner input=new Scanner(System.in); String s= input.next(); NoOfOcuu(s); } public static void NoOfOcuu(String s){ int c=0,c2=0; ArrayListn=new ArrayList<>(); char c1='0'; for(int i=0;i=i)&&(c2==0)) { if (s.charAt(i) == s.charAt(j)) { c++; } } } if(c>1){ n.add(s.charAt(i)); } if(c>0) { System.out.println("the vale:" + s.charAt(i) + " - " + c); } } } }

public static void NoOfOcuu(String s){ int c=0,c2=0; ArrayListn=new ArrayList<>(); char c1='0'; for(int i=0;i=i)&&(c2==0)) { if (s.charAt(i) == s.charAt(j)) { c++; } } } if(c>1){ n.add(s.charAt(i)); } if(c>0) { System.out.println("the vale:" + s.charAt(i) + " - " + c); } } }

19)function isPalindrome(str) { let emptyArr = []; for (let i = 0; i < str.length; i++) { let x = str[i]; if (x == "(" || x == "[" || x == "{") { emptyArr.push(x); continue; } if (emptyArr.length == 0) return false; let y; switch (x) { case ")": y = emptyArr.pop(); if (y == "{" || y == "[") return false; break; case "}": y = emptyArr.pop(); if (y == "(" || y == "[") return false; break; case "]": y = emptyArr.pop(); if (y == "(" || y == "{") return false; break; } } return emptyArr.length == 0; } if (isPalindrome("{}")) console.log(true); else console.log(false);

val str = "aabbbbaa" var l = str.length var s = "" while (l>0){ s = s + str.get(l-1) l-- } if(s.equals(str)) { println("palindrome string : " + s) }else{ println("No palindrome string : " + s) }

Hi guys, here is the solution for question number 4 "How to remove characters from the first String which are present in the second String?" public static void main(String[] args) { String st1 = "india is great"; String st2 = "in"; List secondStringList = st2.chars().mapToObj(c -> (char) c).collect(Collectors.toList()); String outputString = st1.chars().mapToObj(c -> (char) c).filter(c -> !secondStringList.contains(c)).map(ch -> new String(String.valueOf(ch))) .collect(Collectors.joining("")); System.out.println("outputString : " + outputString); }

Feel free to comment, ask questions if you have any doubt.

Codeforwin

String programming exercises and solutions in C

Strings are basically array of characters that represent some textual data in a program. Here are basic string programs with detailed explanation that will help to enhance your string programming skills. These exercises can be practiced by anyone a beginner or an intermediate programmers.

Required knowledge

Basic C programming , Array , Pointer , Functions , Strings

List of string programming exercises

  • Write a C program to find length of a string .
  • Write a C program to copy one string to another string .
  • Write a C program to concatenate two strings .
  • Write a C program to compare two strings .
  • Write a C program to convert lowercase string to uppercase .
  • Write a C program to convert uppercase string to lowercase .
  • Write a C program to toggle case of each character of a string .  
  • Write a C program to find total number of alphabets, digits or special character in a string .
  • Write a C program to count total number of vowels and consonants in a string .
  • Write a C program to count total number of words in a string .
  • Write a C program to find reverse of a string .
  • Write a C program to check whether a string is palindrome or not .
  • Write a C program to reverse order of words in a given string .
  • Write a C program to find first occurrence of a character in a given string .
  • Write a C program to find last occurrence of a character in a given string .
  • Write a C program to search all occurrences of a character in given string .
  • Write a C program to count occurrences of a character in given string .
  • Write a C program to find highest frequency character in a string .
  • Write a C program to find lowest frequency character in a string .
  • Write a C program to count frequency of each character in a string .
  • Write a C program to remove first occurrence of a character from string .
  • Write a C program to remove last occurrence of a character from string .
  • Write a C program to remove all occurrences of a character from string .
  • Write a C program to remove all repeated characters from a given string .
  • Write a C program to replace first occurrence of a character with another in a string .
  • Write a C program to replace last occurrence of a character with another in a string .
  • Write a C program to replace all occurrences of a character with another in a string .
  • Write a C program to find first occurrence of a word in a given string .
  • Write a C program to find last occurrence of a word in a given string .
  • Write a C program to search all occurrences of a word in given string .
  • Write a C program to count occurrences of a word in a given string .
  • Write a C program to remove first occurrence of a word from string .
  • Write a C program to remove last occurrence of a word in given string .
  • Write a C program to remove all occurrence of a word in given string .  
  • Write a C program to trim leading white space characters from given string .
  • Write a C program to trim trailing white space characters from given string .
  • Write a C program to trim both leading and trailing white space characters from given string .
  • Write a C program to remove all extra blank spaces from given string .

InterviewPrep

Top 25 String Manipulation Interview Questions and Answers

Prepare for your next coding interview with our comprehensive guide on string manipulation. Discover common questions, insightful answers, and practical examples to enhance your coding skills.

string problem solving questions

String manipulation, a fundamental aspect of any programming language, involves the ability to modify and interact with strings – sequences of characters that include letters, numbers, symbols, or spaces. The importance of string manipulation cannot be overstated as it is used in various applications such as data cleaning, pattern recognition, parsing, and so much more.

Regardless of whether you’re working in Python, Java, C++, JavaScript, or any other language, understanding how to effectively manipulate strings is an essential skill for every developer. It’s also a common area of inquiry during technical interviews, given its ubiquity in coding challenges and real-world problem-solving scenarios.

In this article, we delve into a comprehensive collection of interview questions focused on string manipulation. These questions are designed to test your knowledge about different methods of manipulating strings, finding patterns, comparing, searching, and even converting strings. Whether you’re a beginner just starting out or a seasoned programmer looking to refresh your skills, these questions will provide invaluable insights into handling one of the most commonly used data types in programming.

1. Can you explain what String Manipulation is and why it’s important in software development?

String manipulation refers to the process of handling and modifying strings, a sequence of characters, in programming. It’s crucial in software development for several reasons.

Firstly, it aids in data cleaning by removing unnecessary spaces or converting case types, enhancing data consistency. Secondly, it enables parsing where strings are broken into smaller parts for easier analysis. This is vital when dealing with large volumes of text data. Thirdly, string manipulation allows for effective communication between different systems through formatting strings to meet specific system requirements.

Moreover, it facilitates user-friendly outputs. By manipulating strings, developers can format information in a way that’s easy for users to understand. Lastly, it supports pattern matching and searching within strings, which is essential in many applications like search engines.

2. Can you describe how to reverse a string using an iterative approach in Python?

In Python, reversing a string using an iterative approach involves creating a new empty string and then appending each character from the original string to it in reverse order. This can be achieved by initializing an empty string, then iterating over the length of the original string starting from the last index (which is -1 in Python) and moving towards the first index (0). For each iteration, we append the current character to our new string. Here’s a simple code example:

This function takes an input string, iterates over it in reverse order, and appends each character to reversed_str . The result is a reversed version of the original string.

3. How would you remove all white spaces from a string without using the replace() method?

To remove all white spaces from a string without using the replace() method, we can use the split() and join() methods. The split() method splits a string into an array of substrings based on a specified delimiter, in this case, a space character. This effectively removes all spaces from the string. However, it leaves us with an array of substrings rather than a single string. To convert this back into a single string, we use the join() method which concatenates all elements of an array into a single string.

Here is a JavaScript example:

In this code snippet, ‘str’ initially contains a string with spaces. We then call the split() method on ‘str’, passing in a space character as the argument. This splits ‘str’ into an array of words. We immediately call join() on this array, passing in an empty string as the argument. This joins all the words together into a single string with no spaces.

4. What algorithms would you use to check if a string is a palindrome?

To check if a string is a palindrome, two algorithms can be used: the Two-Pointer Technique and the Stack Method.

The Two-Pointer Technique involves initializing two pointers at both ends of the string. The characters at these pointer positions are compared. If they match, the pointers move towards each other until they meet in the middle or cross paths. If all character comparisons match, the string is a palindrome.

The Stack Method uses a stack data structure to store half the string’s characters. It then pops off each character from the stack and compares it with the remaining half of the string. A matching sequence indicates a palindrome.

5. How would you go about finding the duplicate characters in a string?

To find duplicate characters in a string, I would use a hash map data structure. The key-value pair of the hash map would be character-frequency pairs. First, iterate through each character in the string and add it to the hash map with its frequency count. If a character is already present in the hash map, increment its frequency by one. After iterating through all characters, traverse the hash map. Any character with a frequency greater than one is a duplicate.

6. Can you explain the concept of string immutability? What are its implications in programming?

String immutability refers to the property of strings that prevents their modification once created. In programming languages like Python and Java, strings are immutable objects. This means when you try to update the value of an immutable string, a new object is created instead of modifying the original one.

The implications of string immutability in programming are significant. It enhances performance by allowing strings to be reused without creating additional copies. This saves memory space and improves efficiency. However, it can also lead to increased processing time if large numbers of strings need to be concatenated or manipulated, as each operation results in a new string object.

Immutable strings also contribute to safer code. Since they cannot be changed after creation, they can be used as keys in dictionaries or elements in sets without fear of unexpected changes. Moreover, they help maintain thread safety in multi-threaded environments because they eliminate the risk of data corruption due to simultaneous modifications from different threads.

7. How would you implement a case-insensitive string comparison function?

To implement a case-insensitive string comparison function, we can use the built-in functions provided by most programming languages. For instance, in Python, we would convert both strings to lower or upper case using the .lower() or .upper() methods respectively before comparing them.

Here’s an example:

In this code snippet, str1 and str2 are the two input strings. The .lower() method is called on each string to convert all characters to lowercase. Then, the equality operator ( == ) compares these modified strings. If they match, the function returns True; otherwise, it returns False.

8. In JavaScript, how would you convert a string to a number and vice versa?

In JavaScript, to convert a string to a number, you can use the Number() function or the parseInt() and parseFloat() functions. The Number() function converts the entire string while parseInt() and parseFloat() stop at the first non-numeric character.

Example: let str = “123”; let num = Number(str); // 123

For converting a number to a string, we use the toString() method. This method returns a string representing the specified number object.

Example: let num = 123; let str = num.toString(); // “123”

9. How would you check if two strings are anagrams of each other in a highly efficient way?

An efficient way to check if two strings are anagrams is by using a frequency count method. This involves creating a character array of size 26 for each string, representing the English alphabet. Each index in the array corresponds to a letter and its value represents the frequency of that letter in the string.

Firstly, initialize both arrays with zeros. Then iterate through each character in the first string, incrementing the corresponding index in the first array. Repeat this process for the second string but decrement the corresponding index in the second array.

Finally, compare the two arrays. If they’re identical, the strings are anagrams. Otherwise, they’re not. The time complexity of this approach is O(n), where n is the length of the strings.

10. Can you describe how you would find all permutations of a string?

To find all permutations of a string, we can use recursion. We start by fixing the first character and recursively generating permutations for the remaining characters. Once this is done, we swap the first character with the next one and repeat the process until we’ve swapped with every character in the string. This will generate all possible permutations as each position in the string is occupied by every character exactly once.

For example, consider the string “ABC”. Initially, ‘A’ is fixed and permutations are generated for ‘BC’. Then ‘B’ is swapped with ‘A’, so now ‘B’ is fixed and permutations are generated for ‘AC’. Finally, ‘C’ is swapped with ‘A’, so ‘C’ is fixed and permutations are generated for ‘AB’.

This method ensures that all permutations are found without repetition. However, it’s important to note that this approach has a time complexity of O(n*n!) due to the n! permutations and n recursive calls for each permutation.

11. How would you reverse words in a given sentence without using any library method?

To reverse words in a sentence without using any library method, we can follow these steps:

1. Convert the sentence into an array of words by splitting it at spaces. 2. Initialize an empty string to hold the reversed sentence. 3. Iterate over the word array from end to start. 4. For each iteration, append the current word and a space to the reversed sentence. 5. After the loop ends, remove the trailing space from the reversed sentence.

Here is a Python code example:

12. What methods would you use to find the length of a string without using the len() function?

To find the length of a string without using len(), we can use two methods. The first method is to use a for loop. Initialize a counter variable at zero, then iterate over each character in the string, incrementing the counter by one each time. At the end of the loop, the counter will hold the length of the string.

The second method involves using the reduce function from the functools module. This function applies a binary function (a function that takes two arguments) to all items in an iterable in a cumulative way. We can pass a lambda function that increments a counter for each character in the string and the string itself as the iterable.

Here’s how it looks in code:

13. Can you demonstrate how to count the occurrence of a given character in a string?

Yes, I can demonstrate this using Python. The built-in count() function is used to count the occurrence of a character in a string.

In this code, we define a function called char_count that takes two parameters: a string and a character. Inside the function, we use the count() method on the string to count the number of times the character appears. We then call this function with a test string and character, and print the result.

14. How would you convert a string to a character array in Java?

In Java, a string can be converted to a character array using the built-in method “toCharArray()”. This method is part of the String class and returns an array containing each character in the original string. Here’s how it works:

In this code snippet, we first declare a string ‘str’ with the value “Example”. Then, we call the “toCharArray()” method on ‘str’, which converts it into a character array ‘charArray’. Now, ‘charArray’ contains the individual characters of “Example”.

15. Can you explain the differences between a string and a string buffer?

A string is an immutable object in Java, meaning once it’s created, its state cannot be changed. Any modification to a String results in a new instance, leading to memory inefficiency if many modifications are made.

On the other hand, StringBuffer is mutable. Modifications like append or insert can be made without creating a new instance. This makes StringBuffer more efficient when performing repeated operations on strings.

Another difference lies in synchronization. StringBuffer methods are synchronized, making them thread-safe and suitable for multi-threading environments. In contrast, String is not thread-safe.

16. How would you implement multi-line strings in Python and Java?

In Python, multi-line strings are implemented using triple quotes. You can use either three single quotes (”’) or three double quotes (“””). For example:

Java doesn’t directly support multi-line strings. However, you can achieve this by concatenating strings with the ‘+’ operator and including newline characters (‘\n’). Alternatively, since Java 13, you can use text blocks which are enclosed in triple double quotes (“””…”””). Here’s an example:

18. Can you explain how string concatenation works in JavaScript?

In JavaScript, string concatenation is the process of joining two or more strings together. This can be achieved using the ‘+’ operator or the ‘concat()’ method.

The ‘+’ operator merges two strings into one. For example, let’s consider two strings: var str1 = “Hello”; var str2 = “World”. The concatenated string would be: var result = str1 + ” ” + str2; //result is “Hello World”.

Alternatively, the ‘concat()’ method can also be used for string concatenation. It combines the text from two (or more) strings and returns a new string. Using our previous variables, we could write: var result = str1.concat(” “, str2); //result is “Hello World”.

It’s important to note that neither the ‘+’ operator nor the ‘concat()’ method modify the original strings. They both return a new string which is the result of the concatenation.

19. How would you find the longest palindrome in a given string?

To find the longest palindrome in a string, we can use dynamic programming. We initialize a 2D array of size n*n (where n is the length of the string) to false. Each cell [i][j] represents whether the substring from index i to j is a palindrome.

We then iterate over the string in reverse order. For each character, we check all substrings that end with this character. If the substring is a palindrome, we update our answer.

The pseudocode for this algorithm would be:

20. Can you write a function to check if a string is a substring of another string without using any built-in functions?

Yes, a function can be written to check if a string is a substring of another without using built-in functions. Here’s an example in Python:

This function iterates over the main string and checks each character against the corresponding character in the potential substring. If all characters match, it returns True; otherwise, it continues checking until it has exhausted all possibilities or found a match.

21. How would you count the number of vowels and consonants in a string?

To count the number of vowels and consonants in a string, we can use an iterative approach. First, initialize two counters to zero: one for vowels and another for consonants. Then, iterate over each character in the string. If the character is a vowel (a, e, i, o, u), increment the vowel counter. If it’s a letter but not a vowel, increment the consonant counter. Here’s a Python example:

This function converts the input string to lowercase, then iterates through each character. It checks whether the character is a letter and if so, whether it’s a vowel or a consonant, updating the respective counters accordingly.

22. Can you explain the role of escape sequences in string manipulation?

Escape sequences play a crucial role in string manipulation by allowing the inclusion of special characters within strings that cannot be typed directly. They are denoted by a backslash (\) followed by a letter or combination of digits. For instance, “\n” is used for a new line, “\t” for a tab, and “\\” to include a literal backslash. Escape sequences also enable the use of non-printable ASCII control characters like “\0″ (null character). In coding languages such as Python, escape sequences can be used with both single (‘ ‘) and double (” “) quotes to prevent them from being interpreted as the end of a string.

23. How would you find the first non-repeating character in a string?

To find the first non-repeating character in a string, we can use a hash map. The keys of this map are characters from the input string and values are their counts. We iterate through the string, for each character, if it’s not already in the map, add it with count 1; if it is, increment its count. After that, iterate again over the string, checking each character’s count in the map. The first character with a count of 1 is our answer.

Here’s an example in Python:

24. How do you split a string into a list of words in Python?

In Python, the split() method is used to divide a string into a list of words. This function splits the string at each instance of white space by default. Here’s an example:

This code will output: [‘Hello’, ‘World’]

If you want to split on something other than whitespace, you can pass that as an argument to the split() function. For example:

This code will output: [‘apple’, ‘banana’, ‘cherry’]

25. Can you describe the difference in memory allocation between a string and a string builder in .NET?

In .NET, strings are immutable objects. This means once a string is created, it cannot be changed. Any operation that appears to modify the string actually creates a new one in memory. This can lead to inefficient use of resources when performing multiple modifications on a string.

On the other hand, StringBuilder is mutable. It allows for efficient manipulation of large or complex strings as it doesn’t create a new object in memory with each modification. Instead, it modifies the existing object, reducing memory usage and improving performance.

Top 25 knitr (R package) Interview Questions and Answers

Top 25 spring data jpa interview questions and answers, you may also be interested in..., top 25 test-driven development (tdd) interview questions and answers, top 25 agile testing interview questions and answers, top 25 abstract class interview questions and answers, top 25 css overflow interview questions and answers.

DEV Community

DEV Community

Posted on Jun 1, 2019 • Updated on Jan 10, 2021

Top 20 String Coding Problems from Programming Job Interviews

Disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.

string problem solving questions

This is very obvious because I have also never written a program where I have not used a single String variable. You will always find String as one of the most used data type or data structure in any program.

In this article, I am going to share some of the most common String based coding problems I have come across from many Programming interviews I have been part of. I also have experience from both sides of the table as a candidate as well as an Interviewer so I know how important these questions are.

Btw, there is no point in solving these questions if you don't have basic knowledge of data structure or you have not to refresh them in recent times. In that case, I suggest you first go through a good data structure and algorithm course or book to revise the concept.

This will save you a lot of time going back and forth between the book and your IDE for each question.

If you need resources, I suggest following online courses to learn Data structure and Algorithms , even though they are independent of any programming language, I strongly suggest you join the course which explains problems in the programming language you are most comfortable with.

  • Data Structures and Algorithms: Deep Dive Using Java for Java developers
  • Algorithms and Data Structures in Python for those who love Python
  • JavaScript Algorithms and Data Structures Masterclass by Colt Steele for JavaScript programmers
  • Mastering Data Structures & Algorithms using C and C++ for those who are good at C/C++

How to solve String based Coding Problems?

A good thing about the string data structure is that if you know the array data structure, you can easily solve string-based problems because strings are nothing but a character array .

So all the techniques you know by solving array-based coding questions can be used to solve string programming questions as well.

Here is my list of some of the frequently asked string coding questions from programming job interviews:

  • How do you reverse a given string in place? ( solution )
  • How do you print duplicate characters from a string? ( solution )
  • How do you check if two strings are anagrams of each other? ( solution )
  • How do you find all the permutations of a string? ( solution )
  • How can a given string be reversed using recursion? ( solution )
  • How do you check if a string contains only digits? ( solution )
  • How do you find duplicate characters in a given string? ( solution )
  • How do you count the number of vowels and consonants in a given string? ( solution )
  • How do you count the occurrence of a given character in a string? ( solution )
  • How do you print the first non-repeated character from a string? ( solution )
  • How do you convert a given String into int like the atoi() ? ( solution )
  • How do you reverse words in a given sentence without using any library method? ( solution )
  • How do you check if two strings are a rotation of each other? ( solution )
  • How do you check if a given string is a palindrome? ( solution )
  • How do you find the length of the longest substring without repeating characters? (solution)
  • Given string str, How do you find the longest palindromic substring in str? (solution)
  • How to convert a byte array to String? ( solution )
  • how to remove the duplicate character from String? ( solution )
  • How to find the maximum occurring character in a given String? ( solution )
  • How do you remove a given character from String? ( solution )

These questions help improve your knowledge of string as a data structure.

If you can solve all these String questions without any help then you are in good shape.

For more advanced questions, I suggest you solve problems given in the Algorithm Design Manual by Steven Skiena , a book with the toughest algorithm questions.

string problem solving questions

If you need to revise your Data Structure and Algorithms concepts then you can also see these resources:

1. Data Structures and Algorithms: Deep Dive Using Java for Java developers

2. Algorithms and Data Structures in Python for those who love Python

3. JavaScript Algorithms and Data Structures Masterclass by Colt Steele for JavaScript programmers

4. Mastering Data Structures & Algorithms using C and C++ for those who are good at C/C++

These are some of the best courses on data structures and algorithms and you can choose the one which is most suitable for you. Btw, I will receive payments if you buy these courses

Now You're Ready for the Coding Interview

These are some of the most common questions outside of data structure and algorithms that help you to do really well in your interview.

I have also shared a lot of these questions on my javarevisited and java67 , so if you are really interested, you can always go there and search for them.

These common String based questions are the ones you need to know to successfully interview with any company, big or small, for any level of programming job.

If you are looking for a programming or software development job in 2018, you can start your preparation with this list of coding questions but you need to prepare other topics as well.

This list of 50+ data structure and algorithms problems provides good topics to prepare and also helps assess your preparation to find out your areas of strength and weakness.

Good knowledge of data structure and algorithms is important for success in coding interviews and that's where you should focus most of your attention.

Further Learning 10 Algorithm Books Every Programmer Should Read Top 5 Data Structure and Algorithm Books for Java Developers From 0 to 1: Data Structures & Algorithms in Java Data Structure and Algorithms Analysis --- Job Interview 50+ Data Structure and Coding Problems for Programmers 10 Data Structure, Algorithms and SQL Courses to Crack Coding Interviews 20+ Array Coding Problems for Programmers 20+ Linked List Coding Problems for Programmers 25+ System Design Coding Problems for interviews

Closing Notes

Thanks, You made it to the end of the article ... Good luck with your programming interview! It's certainly not going to be easy, but you are one step closer after practicing these questions.

If you like this article, then please share it with your friends and colleagues, and don't forget to follow javinpaul on Twitter!

P.S. --- If you need some FREE resources for Programming Job Interviews, you can check out this list of free data structure and algorithm courses to start your preparation.

Top comments (18)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

beachbc profile image

  • Location Portland, OR
  • Work Senior Fullstack Developer at Oregon Public Broadcasting
  • Joined Jun 2, 2019

"Thank you for selecting me as a candidate to interview, if you honestly think I've worked my way up to being a senior developer without knowing how to actually perform the job, then this isn't an organization I want to work for. I'm sure we both have more important things to do with our time, so why don't we go ahead and end this now."

  • Joined Sep 16, 2018

Well @Bradley, I do understand that after a certain level of experience you may find it offending solving these questions but that's not the goal. If you are hands-on with coding, you can easily solve these problems but if you struggle with solving these, it means you are a bit rusty and not really doing coding everyday.

It doesn't matter to me how easy the questions are to answer. To me:

The question is trying to verify that I know how to do trivial and/or esoteric operations off the top of my head, which lets be honest, who has ever had to reverse the words of a sentence? Likewise, who hasn't had to strip bad characters out of a string?

The interviewers care about my rote memorization, which has nothing to do with being a good developer.

The company put someone in charge of interviewing that isn't a developer and they pulled questions off the internet thinking this is what makes a great developer.

The person in charge of hiring is too busy or too lazy to put the time into determining if a long list of candidates are a good fit for their organization, so they use this as a quick way to weed out candidates in round one. Mission successful; if they're not going to put the time into selecting quality candidates then right off the bat I'm not too excited about my prospective coworkers, nor the support I can expect from the organization.

What I'm saying is that a company asking this type of question tells me all I need to know about that company.

About the most I'll do is some sort of take home project and discuss at the interview: at least then I can either use a language or library I haven't used in a long time or learn a new one while I'm doing the project so that I'm not wasting my time.

philrod1 profile image

  • Joined Jun 1, 2019

Exactly! Job interviews are a two-way thing. Or at least they should be.

mt3o profile image

  • Joined Aug 15, 2018

Horrible idea for a job interview. Perhaps for a junior position, or even for an internship, but not for a senior, or at least for minimally independent position. All of those problems are easily solvable with Google. On the other hand, as a senior, you have to work with multiple different languages, technologies, paradigms and be able to to figure out best way to solve the problem, having multiple proposed solutions. Problems you referred are trivial, well known and deeply exploited.

From my experience, I had people who excelled at this kind of questions but failed at "as a java developer i won't touch js/html" kind of test. As a scrum master and main developer on the team I cannot accept situation where one of the members can't (don't want to) handle tasks other people do.

As interviewer I like this question: which features of java8+ are most important to you? It gives the interviewee chance to gather thoughts, check if he is up to date and on which parts of the language he focuses. And there is no "bad" answer. All answers reflect how they think, what they focus on, and, honestly, if you rate people's creativity by number of algorithms they memorized, you'll assemble a team of losers who can't solve any problem unless it's already solved by a business analyst.

I don't want to work for you. Sorry.

mia26mba08 profile image

Possibly the worst way to hire someone. They give zero indication of a devs ability.

I don't know why you think so because this is not the only interview anyone will give to get the job. It's not that easy. this is just a part of a big hiring process.

The java example of reversing a string in-place is wrong. Strings are immutable in Java. The example given will involve two array copies.

Well, while you are correct, it's about logic. In reality, it's better to use StringBuilder.reverse() but yes, mentioning that fact can impress some interviewers too.

humbertobeltrao profile image

I think that trying to let things clear during the interview helps the candidate to understand the importance behind these kind of questions. In one of the process I participated the interviewer explained that solving the string problems I was facing was not the point. He explained the time constraints the projects used to demand in the company and for that reason code performance and complexity concerns would be also evaluated. String problems themselves probably do not represent the scenario a candidate will be working on, but perhaps telling about the skills required to not hit the iceberg helps to care about its top.

For comparison, look here: businessinsider.com/how-tech-compa...

If paywalled, disable javascript.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

furkangozukara profile image

IDM-VTON: The Most Amazing Virtual Try Anything On Application - Windows, Massed Compute, RunPod & Kaggle

Furkan Gözükara - May 3

henrylehd profile image

Understanding the Difference Between Websites and Web Apps

Henry Dioniz - Apr 30

ankur0904 profile image

Hosting a Flask web server on Railway [FREE]

Ankur Singh - Apr 30

mdarifulhaque profile image

79. Word Search

MD ARIFUL HAQUE - May 1

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Java Strings Introduction Easy Java (Basic) Max Score: 5 Success Rate: 93.75%

Java substring easy java (basic) max score: 5 success rate: 99.00%, java substring comparisons easy java (basic) max score: 10 success rate: 91.89%, java string reverse easy java (basic) max score: 10 success rate: 97.80%, java anagrams easy java (basic) max score: 10 success rate: 93.23%, java string tokens easy java (basic) max score: 15 success rate: 82.22%, pattern syntax checker easy java (basic) max score: 20 success rate: 97.49%, java regex medium java (intermediate) max score: 25 success rate: 93.03%, java regex 2 - duplicate words medium java (basic) max score: 25 success rate: 91.91%, valid username regular expression easy max score: 20 success rate: 95.74%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

Ensure that you are logged in and have the required permissions to access the test.

A server error has occurred. Please refresh the page or try after some time.

An error has occurred. Please refresh the page or try after some time.

Signup and get free access to 100+ Tutorials and Practice Problems Start Now

Algorithms

  • Linear Search
  • Binary Search
  • Ternary Search
  • Bubble Sort
  • Selection Sort
  • Insertion Sort
  • Counting Sort
  • Bucket Sort
  • Basics of Greedy Algorithms
  • Graph Representation
  • Breadth First Search
  • Depth First Search
  • Minimum Spanning Tree
  • Shortest Path Algorithms
  • Flood-fill Algorithm
  • Articulation Points and Bridges
  • Biconnected Components
  • Strongly Connected Components
  • Topological Sort
  • Hamiltonian Path
  • Maximum flow
  • Minimum Cost Maximum Flow

Basics of String Manipulation

  • String Searching
  • Z Algorithm
  • Manachar’s Algorithm
  • Introduction to Dynamic Programming 1
  • 2 Dimensional
  • State space reduction
  • Dynamic Programming and Bit Masking

Solve Problems

Make palindrome.

ATTEMPTED BY: 856 SUCCESS RATE: 52% LEVEL: Easy

  • Participate

Edge Letters

ATTEMPTED BY: 460 SUCCESS RATE: 77% LEVEL: Medium

Palindrome Swapping

ATTEMPTED BY: 1028 SUCCESS RATE: 91% LEVEL: Medium

Unique substrings

ATTEMPTED BY: 559 SUCCESS RATE: 84% LEVEL: Easy

ATTEMPTED BY: 142 SUCCESS RATE: 83% LEVEL: Easy

Alice and messages

ATTEMPTED BY: 734 SUCCESS RATE: 69% LEVEL: Easy

Unique subsequences

ATTEMPTED BY: 4081 SUCCESS RATE: 58% LEVEL: Easy

ATTEMPTED BY: 6513 SUCCESS RATE: 43% LEVEL: Easy

Good Subsequences

ATTEMPTED BY: 2552 SUCCESS RATE: 76% LEVEL: Easy

Alice and Strings

ATTEMPTED BY: 6651 SUCCESS RATE: 90% LEVEL: Easy

Google

  • An alphabet
  • A special character
  • Minimum 8 characters

A password reset link will be sent to the following email id

Top 72 Swift Interview Questions

25+ JavaScript Coding Interview Questions (SOLVED with CODE)

Having a JavaScript Coding Interview Session on this week? Fear not, we got your covered! Check that ultimate list of 25 advanced and tricky JavaScript Coding Interview Questions and Challenges to crack on your next senior web developer interview and got your next six-figure job offer in no time!

Q1 :   Explain what a callback function is and provide a simple example

A callback function is a function that is passed to another function as an argument and is executed after some operation has been completed. Below is an example of a simple callback function that logs to the console after some operations have been completed.

Q2 :   Given a string, reverse each word in the sentence

For example Welcome to this Javascript Guide! should be become emocleW ot siht tpircsavaJ !ediuG

Q3 :   How to check if an object is an array or not? Provide some code.

The best way to find whether an object is instance of a particular class or not using toString method from Object.prototype

One of the best use cases of type checking of an object is when we do method overloading in JavaScript. For understanding this let say we have a method called greet which take one single string and also a list of string, so making our greet method workable in both situation we need to know what kind of parameter is being passed, is it single value or list of value?

However, in above implementation it might not necessary to check type for array, we can check for single value string and put array logic code in else block, let see below code for the same.

Now it's fine we can go with above two implementations, but when we have a situation like a parameter can be single value , array , and object type then we will be in trouble.

Coming back to checking type of object, As we mentioned that we can use Object.prototype.toString

If you are using jQuery then you can also used jQuery isArray method:

FYI jQuery uses Object.prototype.toString.call internally to check whether an object is an array or not.

In modern browser, you can also use:

Array.isArray is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5

Q4 :   How to empty an array in JavaScript?

How could we empty the array above?

Above code will set the variable arrayList to a new empty array. This is recommended if you don't have references to the original array arrayList anywhere else because It will actually create a new empty array. You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged, Only use this way if you have only referenced the array by its original variable arrayList .

For Instance:

Above code will clear the existing array by setting its length to 0. This way of empty the array also update all the reference variable which pointing to the original array. This way of empty the array is useful when you want to update all the another reference variable which pointing to arrayList .

Above implementation will also work perfectly. This way of empty the array will also update all the references of the original array.

Above implementation can also empty the array. But not recommended to use often.

Q5 :   How would you check if a number is an integer?

A very simply way to check if a number is a decimal or integer is to see if there is a remainder left when you divide by 1.

Q6 :   Implement enqueue and dequeue using only two stacks

Enqueue means to add an element, dequeue to remove an element.

Q7 :   Make this work

Q8 :   write a "mul" function which will properly when invoked as below syntax.

Here mul function accept the first argument and return anonymous function which take the second parameter and return anonymous function which take the third parameter and return multiplication of arguments which is being passed in successive

In JavaScript function defined inside has access to outer function variable and function is the first class object so it can be returned by function as well and passed as argument in another function.

  • A function is an instance of the Object type
  • A function can have properties and has a link back to its constructor method
  • Function can be stored as variable
  • Function can be pass as a parameter to another function
  • Function can be returned from function

Q9 :   Write a function that would allow you to do this?

You can create a closure to keep the value passed to the function createBase even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a closure, and it has access to the variables within the outer function, in this case the variable baseNumber .

Q10 :   FizzBuzz Challenge

Create a for loop that iterates up to 100 while outputting "fizz" at multiples of 3 , "buzz" at multiples of 5 and "fizzbuzz" at multiples of 3 and 5 .

Check out this version of FizzBuzz:

Q11 :   Given two strings, return true if they are anagrams of one another

For example: Mary is an anagram of Army

Q12 :   How would you use a closure to create a private counter?

You can create a function within an outer function (a closure) that allows you to update a private variable but the variable wouldn't be accessible from outside the function without the use of a helper function.

Q13 :   Provide some examples of non-bulean value coercion to a boolean one

The question is when a non-boolean value is coerced to a boolean, does it become true or false , respectively?

The specific list of "falsy" values in JavaScript is as follows:

  • "" (empty string)
  • 0 , -0 , NaN (invalid number)
  • null , undefined

Any value that's not on this "falsy" list is "truthy." Here are some examples of those:

  • [ ] , [ 1, "2", 3 ] (arrays)
  • { } , { a: 42 } (objects)
  • function foo() { .. } (functions)

Q14 :   What will be the output of the following code?

Above code would give output 1undefined . If condition statement evaluate using eval so eval(function f() {}) which return function f() {} which is true so inside if statement code execute. typeof f return undefined because if statement code execute at run time, so statement inside if condition evaluated at run time.

Above code will also output 1undefined .

Q15 :   What will the following code output?

The code above will output 5 even though it seems as if the variable was declared within a function and can't be accessed outside of it. This is because

is interpreted the following way:

But b is not declared anywhere in the function with var so it is set equal to 5 in the global scope .

Q16 :   Write a function that would allow you to do this

You can create a closure to keep the value of a even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a closure, and it has access to the variables within the outer function, in this case the variable a .

Q17 :   How does the this keyword work? Provide some code examples

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of.

Q18 :   How would you create a private variable in JavaScript?

To create a private variable in JavaScript that cannot be changed you need to create it as a local variable within a function. Even if the function is executed the variable cannot be accessed outside of the function. For example:

To access the variable, a helper function would need to be created that returns the private variable.

Q19 :   What is Closure in JavaScript? Provide an example

A closure is a function defined inside another function (called parent function) and has access to the variable which is declared and defined in parent function scope.

The closure has access to variable in three scopes:

  • Variable declared in his own scope
  • Variable declared in parent function scope
  • Variable declared in global namespace

innerFunction is closure which is defined inside outerFunction and has access to all variable which is declared and defined in outerFunction scope. In addition to this function defined inside function as closure has access to variable which is declared in global namespace .

Output of above code would be:

Q20 :   What will be the output of the following code?

Above code will output 0 as output. delete operator is used to delete a property from an object. Here x is not an object it's local variable . delete operator doesn't affect local variable.

Q21 :   What will be the output of the following code?

Above code will output xyz as output. Here emp1 object got company as prototype property. delete operator doesn't delete prototype property.

emp1 object doesn't have company as its own property. You can test it like:

However, we can delete company property directly from Employee object using delete Employee.company or we can also delete from emp1 object using __proto__ property delete emp1.__proto__.company .

Q22 :   What will the following code output?

This will surprisingly output false because of floating point errors in internally representing certain numbers. 0.1 + 0.2 does not nicely come out to 0.3 but instead the result is actually 0.30000000000000004 because the computer cannot internally represent the correct number. One solution to get around this problem is to round the results when doing arithmetic with decimal numbers.

Q23 :   When would you use the bind function?

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

A good use of the bind function is when you have a particular function that you want to call with a specific this value. You can then use bind to pass a specific object to a function that uses a this reference.

Q24 :   Write a recursive function that performs a binary search

Q25 :   describe the revealing module pattern design pattern.

A variation of the module pattern is called the Revealing Module Pattern . The purpose is to maintain encapsulation and reveal certain variables and methods returned in an object literal. The direct implementation looks like this:

An obvious disadvantage of it is unable to reference the private methods

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

FullStack.Cafe is a biggest hand-picked collection of top Full-Stack, Coding, Data Structures & System Design Interview Questions to land 6-figure job offer in no time.

Coded with 🧡 using React in Australia 🇦🇺

by @aershov24 , Full Stack Cafe Pty Ltd 🤙, 2018-2023

Privacy • Terms of Service • Guest Posts • Contacts • MLStack.Cafe

string problem solving questions

  • Data Structures
  • Linked List
  • Binary Tree
  • Binary Search Tree
  • Segment Tree
  • Disjoint Set Union
  • Fenwick Tree
  • Red-Black Tree
  • Advanced Data Structures
  • Array Data Structure
  • What is Array?
  • Introduction to Getting Started with Array Data Structure
  • Applications, Advantages and Disadvantages of Array
  • Subarrays, Subsequences, and Subsets in Array

Basic operations in Array

  • Array | Searching
  • Array Reverse in C/C++/Java/Python/JavaScript
  • Program for array left rotation by d positions.
  • Print array after it is right rotated K times
  • Search, Insert, and Delete in an Unsorted Array | Array Operations
  • Search, Insert, and Delete in an Sorted Array | Array Operations
  • Array | Sorting
  • Generating subarrays using recursion

Easy problems on Array

  • Find the largest three distinct elements in an array
  • Find Second largest element in an array
  • Move all zeroes to end of array
  • Rearrange array such that even positioned are greater than odd
  • Rearrange an array in maximum minimum form using Two Pointer Technique
  • Segregate even and odd numbers using Lomuto’s Partition Scheme
  • Reversal algorithm for Array rotation
  • Print left rotation of array in O(n) time and O(1) space
  • Sort an array which contain 1 to n values
  • Count the number of possible triangles
  • Print all Distinct ( Unique ) Elements in given Array
  • Find the element that appears once in an array where every other element appears twice
  • Leaders in an array
  • Find Subarray with given sum | Set 1 (Non-negative Numbers)

Intermediate problems on Array

  • Rearrange an array such that arr[i] = i
  • Rearrange positive and negative numbers in O(n) time and O(1) extra space
  • Reorder an array according to given indexes
  • Find the smallest missing number
  • Difference Array | Range update query in O(1)
  • Maximum profit by buying and selling a share at most twice
  • Smallest subarray with sum greater than a given value
  • Inversion count in Array using Merge Sort
  • Merge two sorted arrays with O(1) extra space
  • Majority Element
  • Two Pointers Technique
  • Triplet Sum in Array (3sum)
  • Equilibrium index of an array

Hard problems on Array

  • MO's Algorithm (Query Square Root Decomposition) | Set 1 (Introduction)
  • Square Root (Sqrt) Decomposition Algorithm
  • Sparse Table
  • Range sum query using Sparse Table
  • Range LCM Queries
  • Minimum number of jumps to reach end (Jump Game)
  • Space optimization using bit manipulations
  • Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
  • Construct an array from its pair-sum array
  • Maximum equilibrium sum in an array
  • Smallest Difference Triplet from Three arrays

Top 50 Array Coding Problems for Interviews

Here is the collection of the Top 50 list of frequently asked interview questions on arrays. Problems in this Article are divided into three Levels so that readers can practice according to the difficulty level step by step. 

Top-50-Array-Coding-Problems-for-Interviews

  Related Articles:

  • Top 50 String Coding Problems for Interviews
  • Top 50 Tree Coding Problems for Interviews
  • Top 50 Graph Coding Problems for Interviews
  • Top 50 Dynamic Programming Coding Problems for Interviews
  • Top 50 Sorting Coding Problems for Interviews
  • Top 50 Searching Coding Problems for Interviews
  • Top 50 Binary Search Tree Coding Problems for Interviews

Some other important Tutorials:

  • DSA Tutorial
  • System Design Tutorial
  • Software Development Roadmap
  • Roadmap to become a Product Manager
  • Learn SAP interview questions

Track your progress and attempt this list on GfG Practice.

Please Login to comment...

Similar reads.

author

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Strings (Solved Problem 5)

    string problem solving questions

  2. What is the difference between a Problem Talk and a Problem String?

    string problem solving questions

  3. Free Problem Solving for Kids School Counseling Printable

    string problem solving questions

  4. Strings (Solved Problem 2)

    string problem solving questions

  5. Strings (Solved Problem 3)

    string problem solving questions

  6. Chapter 10 Problem Solving

    string problem solving questions

VIDEO

  1. (PDE) Lecture 13: Vibrating string problem

  2. Part of a String (TCS NQT Problem Solving Series)

  3. Java String 4/7

  4. Remove vowels from a string (TCS NQT Problem Solving Series)

  5. First and last occurance in a string (TCS NQT Problem Solving Series)

  6. U-Intermediate level of string puzzle OUT(2011-12-17)

COMMENTS

  1. Top 50 String Coding Problems for Interviews

    Solve. Encrypt the String - II. Solve. Equal point in a string of brackets. Solve. Isomorphic Strings. Solve. Check if two strings are k-anagrams or not. Solve.

  2. 51 string interview questions (coding problems with solutions)

    Here's a quick list of string interview questions to get started with: String interview questions (5 typical examples): Given a string, create a new string without vowels and print that string. Given a string, create a new string with the same characters in a random order. Given a string containing some words in (possibly nested) parentheses ...

  3. Top 21 String Programming Interview Questions for Beginners and

    How to solve String-based Coding Problems. A good thing about the string data structure is that if you know the array data structure, you can easily solve string-based problems because strings are ...

  4. Top 21 String Programming and Coding Interview Questions With ...

    18) How do you count the number of words in String? ( solution) Write a program to count a number of words in a given String. The words are separated by the following characters: space (' ') or newline ('\n') or tab ('\t') or a combination of these. For example, if input "Java is great" your program should print 3.

  5. String programming exercises and solutions in C

    List of string programming exercises. Write a C program to find length of a string. Write a C program to copy one string to another string. Write a C program to concatenate two strings. Write a C program to compare two strings. Write a C program to convert lowercase string to uppercase. Write a C program to convert uppercase string to lowercase ...

  6. Top 25 String Manipulation Interview Questions and Answers

    The first method is to use a for loop. Initialize a counter variable at zero, then iterate over each character in the string, incrementing the counter by one each time. At the end of the loop, the counter will hold the length of the string. The second method involves using the reduce function from the functools module.

  7. String Manipulation Interview Questions

    Easy Problem Solving (Basic) Max Score: 20 Success Rate: 97.45%. Solve Challenge. Sherlock and the Valid String. Medium Problem Solving (Basic) Max Score: 35 Success Rate: 66.06%. Solve Challenge. Special String Again. Medium Problem Solving (Intermediate) Max Score: 40 Success Rate: 62.58%.

  8. Top 20 String Coding Problems from Programming Job Interviews

    3. JavaScript Algorithms and Data Structures Masterclass by Colt Steele for JavaScript programmers. 4. Mastering Data Structures & Algorithms using C and C++ for those who are good at C/C++. These are some of the best courses on data structures and algorithms and you can choose the one which is most suitable for you.

  9. Python String Exercise with Solutions

    This String Exercise includes the following: - It contains 18 Python string programs, questions, problems, and challenges to practice.; The solution is provided for all questions. All string programs are tested on Python 3; Use Online Code Editor to solve exercise questions.Let us know if you have any alternative solutions in the comment section below.

  10. How I Master String Coding Problems for Interviews

    I have listed the 15 most asked coding interview string questions. Palindromic Substring. Decode String. Reverse Words in a string. Valid Parentheses. Find all Anagrams in a string. Roman Numeral ...

  11. Java String Exercise: Beginner to Pro Exercises

    This section offers beginner-friendly exercises. Practice creating, modifying, and working with strings to build a solid foundation for your Java programming journey. 1. Java String Program to Print Even-Length Words. Input: s = "This is a java language". Output: This is java language. Explanation: All the elements with the length even are printed.

  12. String Cheatsheet for Coding Interview Prep

    Most string problems use the same problem-solving patterns that we talked about for arrays. Here are the question types you may encounter: In a lot of questions, you need to count the number of ...

  13. C++ String

    3. Write a C++ program to capitalize the first letter of each word in a given string. Words must be separated by only one space. Example: Sample Input: cpp string exercises. Sample Output: Cpp String Exercises. Click me to see the sample solution. 4. Write a C++ program to find the largest word in a given string.

  14. Java Exercises: String exercises

    5. Write a Java program to compare two strings lexicographically. Two strings are lexicographically equal if they are the same length and contain the same characters in the same positions. Sample Output: String 1: This is Exercise 1 String 2: This is Exercise 2 "This is Exercise 1" is less than "This is Exercise 2".

  15. Solve Java

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  16. Basics of String Manipulation Practice Problems

    ATTEMPTED BY: 6650 SUCCESS RATE: 90% LEVEL: Easy. SOLVE NOW. 1 2 3. Solve practice problems for Basics of String Manipulation to test your programming skills. Also go through detailed tutorials to improve your understanding to the topic. | page 1.

  17. 50 String Coding Questions Using Python

    First, the code assigns the string '50 String Coding Questions Using Python' to the variable string1. Next, the startswith() method is used to determine if string1 starts with the substring ...

  18. Python String Exercise

    Basic String Programs. Python program to check whether the string is Symmetrical or Palindrome. Reverse words in a given String in Python. Ways to remove i'th character from string in Python. Find length of a string in python (4 ways) Python - Avoid Spaces in string length. Python program to print even length words in a string.

  19. 25+ JavaScript Coding Interview Questions (SOLVED with CODE)

    FullStack.Cafe is a biggest hand-picked collection of top Full-Stack, Coding, Data Structures & System Design Interview Questions to land 6-figure job offer in no time. Check 25+ JavaScript Coding Interview Questions (SOLVED with CODE) and Land Your Next Six-Figure Job Offer! 100% Tech Interview Success!

  20. JavaScript String

    3. Write a JavaScript function to split a string and convert it into an array of words. Test Data : console.log (string_to_array ("Robin Singh")); ["Robin", "Singh"] Click me to see the solution. 4. Write a JavaScript function to extract a specified number of characters from a string. Test Data :

  21. Java Exercises

    We hope these exercises have helped you understand Java better and you can solve beginner to advanced-level questions on Java programming. Solving these Java programming exercise questions will not only help you master theory concepts but also grasp their practical applications, which is very useful in job interviews. More Java Practice Exercises

  22. Top 50 Array Coding Problems for Interviews

    Find the first repeating element in an array of integers. Solve. Find the first non-repeating element in a given array of integers. Solve. Subarrays with equal 1s and 0s. Solve. Rearrange the array in alternating positive and negative items. Solve. Find if there is any subarray with a sum equal to zero.