Karim Aya

Karim Aya

1566145526

How to solve the Sherlock and Anagrams coding challenge in JavaScript

This post is going to get you through my solution of a coding challenge called “Sherlock and Anagrams”. You may take a look at it in HackerRank. I spent a lot of time trying to solve it, with JavaScript. When I tried to google it, I could not find a decent JS solution. I found just one and it was not working correctly. Also any explanations were completely out of the question. That’s why I decided to write an article about it and try to put some nice and easy to digest explanations along the way. Keep reading now!

⚠ CAUTION: I will roll out my solution below with short explanations about each of the steps. If you want to give a try yourself, please stop here and go to HackerRank site.

Problem

Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.

For example s = mom, the list of all anagrammatic pairs is [m, m], [mo, om] at positions [[0], [2]], [[0, 1], [1, 2]] respectively.

Constraints

Length of the input string: 2 ≤ |s| ≤ 100

String s contains only lowercase letters from the range ascii[a-z].

Analysis

First thing first - we need to get a better understanding of the whole problem. What is an anagram? What is an anagrammatic pair? Can I see one? Also, what exactly does it mean substrings?

In other words, we need to have a clear picture of what are we trying to solve, before solving it.
From the description of the problem we can deduct all we need. Keep walking! 🚶

I think here is a good moment to mention that the challenge in question is under “Dictionaries and Hashmaps” section in HackerRank website, so it’s very likely for one to think, that probably he has to use this kind of data structures when solving it. 😇

Anagrams

Since we are going to look for anagrams, let’s start with them. As it is described above, an anagram of one word is another word, that has the same length and is created with the same characters from the former one.

So we will have to look for words and compare them with other words, in order to see if they are anagrammatic pairs. Once found, we will just count them.

Anagrammatic pairs

After we saw what an anagram is, it should be relatively easy to conclude, that anagrammatic pair is just two strings that are anagrams. Such as “mo” and “om”, or “listen” and “silent”. We will have to count how many pairs like this could be found in a given string. In order to do that, we need to split this original string to substrings.

Substrings

Substrings, as the name infer, are parts of a string. These parts could be just a letter or a pair of letters, such as what have we seen in the example above - “m” or “mo”. In our solution we will split the original string to such substrings and then we will go over them and do the comparison, which will tell us whether we have anagrammatic pairs among them.

Solution

Now, when we did our analysis, it’s showtime! 🎆

Let’s summarize:

  1. We need to find all substrings of the given string - create a method for that.
  2. We need to be able to check if two strings are anagrams - create a method for that.
  3. We need to count all anagrammatic pairs in the given string - create a method for that.
  4. Combine everything from above and spit the result - create a method for that.

Get all substrings

This would be our helper method for finding all substring of a given string:

function getAllSubstrings(str) {
  let i, j, result = [];

  for (i = 0; i < str.length; i++) {
    for (j = i + 1; j < str.length + 1; j++) {
      result.push(str.slice(i, j))
    }
  }
  return result
}

As you can see, it has O(n^2) time complexity, but for our case it does the job, because we have limited length of the input string (up to 100 characters).

Check for anagrams

This would be our helper method for checking if two strings are anagrammatic pair:

function isAnagram(str1, str2) {
  const hist = {}

  for (let i = 0; i < str1.length; i++) {
    const char = str1[i]
    if (hist[char]) {
      hist[char]++
    } else {
      hist[char] = 1
    }
  }

  for (let j = 0; j < str2.length; j++) {
    const char = str2[j]
    if (hist[char]) {
      hist[char]--
    } else {
      return false
    }
  }

  return true
}

❕ You remember, judging by the section where this challenge belongs, we assumed that most probably we will have to use data structures such as hashmaps or dictionaries. Here is the moment to notice that. We use a simple JavaScript object to play the role of a hashmap. We do two iterations - one per string. When we iterate over the first one, we add its characters as keys to the hashmap and count their appearances, which are going to be stored as their values. Then we do another iteration over the second string. Check if its characters are stored in our hashmap. If yes - decrement their value. If there are missing characters, which means the two strings are not anagrammatic pair, we simply return false. If both loops complete, we return true, signifying that the strings being analysed are anagrammatic pair.

Do the counting

This is the method, where we will use the helper for checking if a pair is anagrammatic and count it. We do that with the help of JavaScript arrays and the methods they provide. We iterate over an array containing all the substrings of the original string. Then we get the currect element and remove it from the array. And then we do another loop through that array and return 1 if we find that there is an anagram of the current element. If nothing is found, we return 0.

function countAnagrams(currentIndex, arr) {
  const currentElement = arr[currentIndex]
  const arrRest = arr.slice(currentIndex + 1)
  let counter = 0

  for (let i = 0; i < arrRest.length; i++) {
    if (currentElement.length === arrRest[i].length && isAnagram(currentElement, arrRest[i])) {
      counter++
    }
  }

 return counter
}

And in the end

The only thing left to be done now is to combine all of the above and spit the desired result. Here is how the final method looks like:

function sherlockAndAnagrams(s) {
  const duplicatesCount = s.split('').filter((v, i) => s.indexOf(v) !== i).length

  if (!duplicatesCount) return 0
  let anagramsCount = 0

  const arr = getAllSubstrings(s)

  for (let i = 0; i < arr.length; i++) {
    anagramsCount += countAnagrams(i, arr)
  }

  return anagramsCount
}

Maybe you have noticed, here I am checking first for duplicates, in order to know if I should continue further. As if there are no duplicated letters, then it’s not possible to have an anagram.

And finally, we get all substrings into an array, iterate over it, count the anagrammatic pairs that are found and return this number. You can find the full code here.

Conclusion

This kind of exercises are very good for making you think algorithmically, but also they change your way of working in your day to day job. My recommendation would be to do the same I am trying to do - train your brain now and then with one of those. And if you can - share. I know sometimes you don’t have time for such challenges, but when you do - go for it.

My personal feeling after finishing this was a total satisfaction, which is completely understandable, considering the the time it took me to do it. But at the end, dear reader, I am even happier I can share this experience with you 😌!

#javascript

What is GEEK

Buddha Community

How to solve the Sherlock and Anagrams coding challenge in JavaScript

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Giles  Goodwin

Giles Goodwin

1603857900

4 Ways You Can Get Rid of Dirty Side Effects for Cleaner Code in JavaScript

According to an analysis, a developer creates 70 bugs per 1000 lines of code on average. As a result, he spends 75% of his time on debugging. So sad!

Bugs are born in many ways. Creating side effects is one of them.

Some people say side effects are evil, some say they’re not.

I’m in the first group. Side effects should be considered evil. And we should aim for side effects free code.

Here are 4ways you can use to achieve the goal.

1. use strict;

Just add use strict; to the beginning of your files. This special string will turn your code validation on and prevent you from using variables without declaring them first.

#functional-programming #javascript-tips #clean-code #coding #javascript-development #javascript

Samanta  Moore

Samanta Moore

1621137960

Guidelines for Java Code Reviews

Get a jump-start on your next code review session with this list.

Having another pair of eyes scan your code is always useful and helps you spot mistakes before you break production. You need not be an expert to review someone’s code. Some experience with the programming language and a review checklist should help you get started. We’ve put together a list of things you should keep in mind when you’re reviewing Java code. Read on!

1. Follow Java Code Conventions

2. Replace Imperative Code With Lambdas and Streams

3. Beware of the NullPointerException

4. Directly Assigning References From Client Code to a Field

5. Handle Exceptions With Care

#java #code quality #java tutorial #code analysis #code reviews #code review tips #code analysis tools #java tutorial for beginners #java code review

Houston  Sipes

Houston Sipes

1604088000

How to Find the Stinky Parts of Your Code (Part II)

There are more code smells. Let’s keep changing the aromas. We see several symptoms and situations that make us doubt the quality of our development. Let’s look at some possible solutions.

Most of these smells are just hints of something that might be wrong. They are not rigid rules.

This is part II. Part I can be found here.

Code Smell 06 - Too Clever Programmer

The code is difficult to read, there are tricky with names without semantics. Sometimes using language’s accidental complexity.

_Image Source: NeONBRAND on _Unsplash

Problems

  • Readability
  • Maintainability
  • Code Quality
  • Premature Optimization

Solutions

  1. Refactor the code
  2. Use better names

Examples

  • Optimized loops

Exceptions

  • Optimized code for low-level operations.

Sample Code

Wrong

function primeFactors(n){
	  var f = [],  i = 0, d = 2;  

	  for (i = 0; n >= 2; ) {
	     if(n % d == 0){
	       f[i++]=(d); 
	       n /= d;
	    }
	    else{
	      d++;
	    }     
	  }
	  return f;
	}

Right

function primeFactors(numberToFactor){
	  var factors = [], 
	      divisor = 2,
	      remainder = numberToFactor;

	  while(remainder>=2){
	    if(remainder % divisor === 0){
	       factors.push(divisor); 
	       remainder = remainder/ divisor;
	    }
	    else{
	      divisor++;
	    }     
	  }
	  return factors;
	}

Detection

Automatic detection is possible in some languages. Watch some warnings related to complexity, bad names, post increment variables, etc.

#pixel-face #code-smells #clean-code #stinky-code-parts #refactor-legacy-code #refactoring #stinky-code #common-code-smells