HackerRank Funny String Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Funny String Solution. This problem is a part of the HackerRank Algorithms Series.

HackerRank Funny String Solution
HackerRank Funny String Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Funny String Solution

Task

In this challenge, you will determine whether a string is funny or not. To determine whether a string is funny, create a copy of the string in reverse e.g. abc -> cba. Iterating through each string, compare the absolute difference in the ascii values of the characters at positions 0 and 1, 1 and 2 and so on to the end. If the list of absolute differences is the same for both strings, they are funny.

Determine whether a give string is funny. If it is, return Funny, otherwise return Not Funny.

Example

s = ‘lmnop’

The ordinal values of the charcters are [108, 109, 110, 111, 112]sreverse = ‘ponml’ and the ordinals are [112, 111, 110, 109, 108]. The absolute differences of the adjacent elements for both strings are [1, 1, 1, 1], so the answer is Funny.

Function Description

Complete the funnyString function in the editor below.

funnyString has the following parameter(s):

  • string s: a string to test

Returns

  • string: either Funny or Not Funny

Input Format

The first line contains an integer q, the number of queries.
The next q lines each contain a string, s.

Constraints

  • 1 <= q <= 10
  • 2 <= length of s <= 10000

Sample Input

STDIN Function
—– ——–
2 q = 2
acxz s = ‘acxz’
bcxz s = ‘bcxz’

Sample Output

Funny
Not Funny

Explanation

Let r be the reverse of s.

Test Case 0:
s = acxz, r = zxca
Corresponding ASCII values of characters of the strings:
s = [97. 99, 120, 122] and r = [122, 120, 99, 97]
For both the strings the adjacent difference list is [2, 21, 2].

Test Case 1:
s = bcxzr = zxcb
Corresponding ASCII values of characters of the strings:
s = [98, 99, 120, 122] and r = [122, 120, 99, 98]
The difference list for string s is [1, 21, 2] and for string r is [2, 21, 1].

HackerRank Funny String Solution

Funny String Solution in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX(_n, _m) ((_n > _m)?_n:_m)
#define MIN(_n, _m) ((_n < _m)?_n:_m)
int main() {
    
    int  testcnt    = 0;
    char str[10001] = {0};
    int  len        = 0;
    
    scanf("%d", &testcnt);
    
    for (int test = 0; test < testcnt; test++){
        scanf("%s", str);
        len = strlen(str);
        
        int funny = 1;
        for (int i = 1, j = len - 1; i < len; i++, j--){
            if (MAX(str[i], str[i-1]) - MIN(str[i], str[i-1]) != 
                MAX(str[j], str[j-1]) - MIN(str[j], str[j-1])){
                funny = 0;
                break;
            }
        }
        
        if (funny){
            printf("Funny\n");
        }
        else{
            printf("Not Funny\n");
        }
    }
    
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    return 0;
}

Funny String Solution in Cpp

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cctype>
#include<cstdlib>
#include<algorithm>
#include<bitset>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<cmath>
#include<sstream>
#include<fstream>
#include<iomanip>
#include<ctime>
#include<complex>
#include<functional>
#include<climits>
#include<cassert>
#include<iterator>
using namespace std;
string s;
int t;
char ss[1000001];
int main(){
	scanf("%d", &t);
	while (t--){
		scanf("%s", ss);
		s = ss;
		//cin >> s;
		string r = s;
		bool ok = false;
		reverse(r.begin(), r.end());
		for (int i = 0; i < s.size() - 1; i++){
			if (abs(s[i] - s[i + 1]) != abs(r[i] - r[i + 1])){
				ok = true;
				break;
			}
		}
		if (ok){
			puts("Not Funny");
		}
		else{
			puts("Funny");
		}
 }
	return 0;
}

Funny String Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        for (int t = 0; t < T; t++){
            String s = in.next();
            int n = s.length();
            boolean funny = true;
            for (int i = 1; i < n; i++){
                if (Math.abs(s.charAt(i) - s.charAt(i - 1)) != Math.abs(s.charAt(n - i - 1) - s.charAt(n - (i - 1) - 1))) {funny = false; break;}
            }
            if (funny) System.out.println("Funny"); else System.out.println("Not Funny");
        }
    }
}
Ezoicreport this ad

Funny String Solution in Python

# Enter your code here. Read input from STDIN. Print output to STDOUT
import fileinput
line = fileinput.input()
n = int(line[0])
for i in range(n):
    s = line[i+1].strip()
    lst = [ord(c) for c in s]
    nlst = lst[:]
    nlst.reverse()
    
    ln = len(s)
    funny = True
    for k in range(1, ln):
        if abs(lst[k]-lst[k-1]) != abs(nlst[k]-nlst[k-1]):
            funny = False
            break
            
    if funny: print "Funny"
    else: print "Not Funny"
    

Funny String Solution using JavaScript

function processData(input) {
    var l;
    var s_i, s_i_1, r_i, r_i_1;
    //Enter your code here
    var lines = input.split("\n");
    var number_of_lines = lines[0];
    
    a:    for (var i = 1; i <= number_of_lines; i++) {
        l = lines[i];
        for (var j = 1; j < l.length / 2; j++) {
            s_i = l.charCodeAt(j);
            s_i_1 = l.charCodeAt(j-1);
            r_i_1 = l.charCodeAt(l.length - j -1);
            r_i = l.charCodeAt(l.length - j);
            
            //console.log(s_i, s_i_1, r_i_1, r_i);
            if (Math.abs(s_i - s_i_1) !== Math.abs(r_i - r_i_1)) {
                console.log("Not Funny");
                continue a;
            }
        }
        console.log("Funny")
    }
} 
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});
process.stdin.on("end", function () {
   processData(_input);
});

Funny String Solution in Scala

object Solution {
    def main(args: Array[String]) {
        val t = readInt()
        println(Range(0, t).map{ _ =>
          val s = readLine().toArray
          val r = s.reverse.toArray
          if (Range(1, s.size).forall{ i => Math.abs(s(i) - s(i - 1)) == Math.abs(r(i) - r(i - 1)) }) {
            "Funny"
          } else "Not Funny"
        }.mkString("\n"))
    }
}

Ezoicreport this adFunny String Solution in Pascal

(* Enter your code here. Read input from STDIN. Print output to STDOUT *)
program FunnyString;
function IsFunny(input : ansistring) : ansistring;
var
  indexS, indexR : integer;
  NotFunny : boolean;
begin
  indexS := 2;
  indexR := length(input) - 1;
  repeat
    if abs(ord(input[indexS]) - ord(input[indexS - 1])) <> abs(ord(input[indexR]) - ord(input[indexR + 1])) then
      NotFunny := True;
    inc(indexS);
    dec(indexR);
  until NotFunny or (indexS = length(input));
  if NotFunny then
    IsFunny := 'Not Funny'
  else
    IsFunny := 'Funny';
end;
var
  t, index : integer;
  input, result : ansistring;
begin
  readln(t);
  for index := 1 to t do
  begin
    readln(input);
    result := IsFunny(input);
    writeln(result);
  end;
end.

Disclaimer: This problem (Funny String) is generated by HackerRank but the Solution is Provided by  BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Gemstones Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad