Count non white space in the character array:
This algorithm will find out if any location in the array matches a single white space ‘ ‘. It is a very popular interview question during phone interviews. It helps to gauge if the candidate is well versed with the basics and has basic coding skills.
Algorithm:
- Initialize count to 0.
- Run a for loop from 0 to length of array.
- Compare each array location’s character with the space ‘ ‘
- If it matches then increment the count.
- Print the count of spaces in the array.
Implementation:
public class Test { static char a[] = {'a',' ', 'b',' ','c',' ', ' ', ' ', 'd'}; public static void displayNonWhiteSpaces() { for(int i=0; i<a.length; i++) { if(a[i] != ' ') { System.out.println(a[i]); } } } public static void removeWhiteSpaces() { int k=0; for(int i=0; i<a.length; i++) { if(a[i] != ' ') { a[k++] = a[i]; if(k<i) { a[i] = ' '; } } } System.out.println("Length " + a.length); for(int i=0; i<a.length; i++) { System.out.print("\n" + a[i]); } } public static void main(String args[]) { displayNonWhiteSpaces(); removeWhiteSpaces(); } }
Complexity:
Time complexity is O(n), where n is the number of elements in the array since we have to iterate the array once.
You might also like:
Find White Spaces in Character Array
Find a character in the String
Number is prime or not
Finding Absolute Value
Notes on Sorting and Searching Algorithms
Common String Functions
Reverse a String
Product of all array location expect its own
Find a cycle in the Linked List
Find a binomial co-efficient
Remove duplicates from the array
Telephonic phone technical interview questions - Part 2
Counting sort algorithm
B-Tree
You might also like:
Find White Spaces in Character Array
Find a character in the String
Number is prime or not
Finding Absolute Value
Notes on Sorting and Searching Algorithms
Common String Functions
Reverse a String
Product of all array location expect its own
Find a cycle in the Linked List
Find a binomial co-efficient
Remove duplicates from the array
Telephonic phone technical interview questions - Part 2
Counting sort algorithm
B-Tree
No comments:
Post a Comment