Home Strings [Hackerrank] – Camel Case Solution

[Hackerrank] – Camel Case Solution

by nikoo28
0 comment 4 mins read

Let us try to understand this problem statement first. We have a string in camel case and we have to find the total number of words in this string. A camel case representation is a special representation of string where the first word starts with a small letter, and all the subsequent words start with a capital letter.

Let us look at some sample test cases:

Input: oneTwoThree
Output: 3
We have 3 words
one, two, and three.

Input: jackAndJillWentUpTheHill
Output: 7
We have a total of 7 words
jack, and, jill, went, up, the, hill

image showing sample strings in camel case
Fig: Sample test cases


In the English language we separate each word by a blank space, but when it comes to programming we want to save as much space as possible. This problem introduces you to a new concept of string representation known as camel case. One must also know about a few more string representations:

  • Kebab Case: We separate each word by a hyphen and all characters are lowercase.
  • Snake Case: Same as kebab case, but we separate each word by an underscore.
  • Mixed Case: Does not follow any pattern, any character can be in any case. This is the most difficult to understand.
  • Pascal Case: Same as camel case, but the first character is also written in uppercase.
different string representation styles
Fig: Different string representations

Each of these string representations is used in different programming languages as per the conventions and best practices. They help to make your code easy to read and understand.


The problem has a very straight forward solution. You do not need any special data structures.

  • Start iterating the string from the beginning and initialize a counter variable to 1.
  • Move on the next character, and increment the counter if you see a capital letter.
  • Keep repeating the process till you reach the end of the string.
  • The counter represents the number of words.
image showing number of words in camel case representation
Fig: Number of words in camel case representation


  public int camelcase(String s) {
    int numberOfWords = 0;

    for (int i = 0; i < s.length(); i++) {
      // Get the character
      char c = s.charAt(i);

      // Check if the character is a capital letter
      if (c >= 'A' && c <= 'Z') {
        // This is a start of new word

    // Since the first word starts with a small letter
    numberOfWords = numberOfWords + 1;

    return numberOfWords;
Code language: Java (java)

Time Complexity: O(n)
Space Complexity: O(1)

You can also find the code and test cases on GitHub.

Video Explanation:

YouTube player

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More