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.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Funny String Solution
HackerRank Funny String Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Funny String

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");
        }
    }
}

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"))
    }
}

Funny 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 Chase2learn. This tutorial is only for Educational and Learning purposes.

FAQ:

1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi


Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment