Contact Form

Name

Email *

Message *

Cari Blog Ini

Image

Funny String Hackerrank Solution


Funny String Hackerrank Solution

Funny String Hackerrank Solution

Introduction

The Funny String Hackerrank problem asks to find the count of funny strings in a given array of strings. A string is funny if the absolute difference between the ASCII values of its characters is the same for all adjacent characters.

The Solution

Here is the solution to the problem:

  1. Iterate over each string in the array.
  2. For each string, check if it is funny.
  3. If the string is funny, increment the count of funny strings.
  4. Return the count of funny strings.

Here is the Python code for the solution:

```python def funny_string(s): """ Check if the given string is funny. Args: s (str): The string to check. Returns: bool: True if the string is funny, False otherwise. """ # Check if the string is empty. if not s: return True # Iterate over the string. for i in range(1, len(s)): # Get the absolute difference between the ASCII values of the adjacent characters. diff = abs(ord(s[i]) - ord(s[i - 1])) # Check if the absolute difference is not the same as the previous absolute difference. if i > 1 and diff != prev_diff: return False # Update the previous absolute difference. prev_diff = diff # The string is funny. return True def count_funny_strings(arr): """ Count the number of funny strings in the given array. Args: arr (list): The array of strings. Returns: int: The number of funny strings in the array. """ # Initialize the count of funny strings. count = 0 # Iterate over the array. for s in arr: # Check if the string is funny. if funny_string(s): # Increment the count of funny strings. count += 1 # Return the count of funny strings. return count ```

Example

Here is an example of how to use the solution:

```python arr = ["acxz", "bcde", "fghi"] result = count_funny_strings(arr) print(result) # Output: 2 ```

In this example, the array contains three strings. The first string, "acxz", is funny because the absolute difference between the ASCII values of its adjacent characters is the same for all adjacent characters. The second string, "bcde", is not funny because the absolute difference between the ASCII values of the characters "c" and "d" is not the same as the absolute difference between the ASCII values of the characters "b" and "c". The third string, "fghi", is funny because the absolute difference between the ASCII values of its adjacent characters is the same for all adjacent characters. Therefore, the total count of funny strings in the array is 2.

Conclusion

The Funny String Hackerrank problem is a simple problem that can be solved in a straightforward manner. The solution presented in this article is efficient and easy to understand. I hope this article has been helpful. Thanks for reading!


Comments