Code Review Stack Exchange is a question and answer site for peer programmer code reviews.
Subscribe to RSS
It only takes a minute to sign up. I'm curious if my solution could be more efficient than it currently is. If you are intended to measure the frequency of bytes, as the name of your input string seems to suggest, rather than just lowercase ASCII letters, then your holder array should be elements long.
This also saves you from all the additions and subtractions of the 'magic' number Seriously, you could have used 'a'. Also, your holder array should consist of int s not char s, because if a certain byte appears more than times in your input string the char will wrap around to zero.
Also an array of int s will probably perform more efficiently due to memory alignment. How to initialize an array in C. Apart from everything that's been said already, you could improve the code by making it more const -correct. In addition to this, if you know you're going to be working with strings, you might as well have it use null-termination, as you can expect it to be present anyway.
It also allows for more elegant in my opinion expression of the intent, especially if you use 'a' instead of As has been said, you should probably pull the last loop into a different function; I'd say you should pull the array into another function, too.
Something that you haven't shown us are the tests you're running on this code. Assuming you've factored some things out, so that your function looks like this:. You probably want some kind of testing framework to run these tests in, although just using assert. Your function may be fairly short, but 12 lines is non-trivial, and you'll spend less time debugging if you split your code up and write tests for it. I think your solution is optimal in terms of efficiency.
Subscribe to RSS
One alternative would be to eliminate the last loop which iterates through the holder array to find the maximum by keeping a running max, like this:. But because the last loop has a fixed, extremely small number of iterations, I think your code will probably end up being faster, especially with larger input strings by using fewer comparisons.
Sign up to join this community. The best answers are voted up and rise to the top.
Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Here's my answer without using maps, lists, etc. Assuming your array is sorted like the one you posted you could simply iterate over the array and count the longest segment of elements, it's something like narek.
We convert the int data array to boxed Integer Stream. Then we collect by groupingBy on the element and use a secondary counting collector for counting after the groupBy. And this algorithm is useful when your array items are not big numbers.
Time complexity of this will be O N and space complexity will be O 1. Seems like you are looking for the Mode value Statistical Modehave a look at Apache's Docs for Statistical functions. Best approach will be using map where key will be element and value will be the count of each element.
Along with that keep an array of size that will contain the index of most popular element. Populate this array while map construction itself so that we don't have to iterate through map again. If someone want to go with two loop, here is the improvisation from accepted answer where we don't have to start second loop from one every time. Using map to save all the differents elements found in the array and saving the number of times ocurred, then just getting the max from the map.
First, take the first element and check how many times it is repeated and increase the counter count as to see how many times it occurs. Check if this maximum number of times that a number has so far occurred if yes, then change the largest variable to store the maximum number of repetitions and if you would like to store the variable as well, you can do so in another variable here k. I hope this helps. You can count the occurrences of the different numbers, then look for the highest one.
The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Here I have written a generic implementation that will given you the n most common character. In your case you could specify 2 as shown in the example main. The answer is accomplished through sorting the set of map entries in descending order by the number of occurrences value of the entry and then picking n-1 since base zero indexes from the start of the list.
Learn more. Find the second most frequent character in string using HashMap Ask Question. Asked 10 months ago. Active 10 months ago. Viewed times. I am trying to find the second most frequent character in a string.
Find the second most frequent character
How can I fix and optimize this code? EDIT I have use two character variables to get the job done. Naman Ayzaz M. Ayzaz 3 5 5 bronze badges.
I have started to try and work out the TopCoder problems. The "StringDup" problem asks us to:. Create a class called StringDup. Given a string made up of ONLY letters and digits, determine which character is repeated the most in the string 'A' is different than 'a'.
If there is a tie, the character which appears first in the string from left to right should be returned. Is there any way I can make my solution better or more efficient? Is there something that I have missed? I'm new to Java and I thought this would be a good way to learn. This question is looking for a special 'trick' to be done Currently it returns. It's not in the specification, so I think it shouldn't do that. Crash early. It is rather a bug in the client code when it calls the method with invalid input.
Clients might produce bigger side-effect on a non-expected. I'd throw an IllegalStateException here. If you're allowed to use external libraries you could write it in a higher level of abstraction with Guava's Multiset s and Iterables :. Sign up to join this community. The best answers are voted up and rise to the top. Home Questions Tags Users Unanswered.
Finding the most common character in a string Ask Question.
Asked 6 years, 2 months ago. Active 5 years, 9 months ago. Viewed 33k times. Active Oldest Votes. Some additional notes Putting the brace on a new line is a C thing to do, and is frowned upon. In your use case, you should use the variable j because that is the one that by convention is used inside the i loop. If you're allowed to use external libraries you could write it in a higher level of abstraction with Guava's Multiset s and Iterables : import static com.Given an array, find the most frequent element in it.
If there are multiple elements that appear maximum number of times, print any one of them. A simple solution is to run two loops. The outer loop picks all elements one by one. The inner loop finds frequency of the picked element and compares with the maximum so far.
Time complexity of this solution is O n 2. A better solution is to do sorting. We first sort the array, then linearly traverse the array. An efficient solution is to use hashing. We create a hash table and store elements and their frequency counts as key value pairs.
Finally we traverse the hash table and print the key with maximum value. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below. Writing code in comment? Please use ide.
Python3 program to find the most. Sort the array. If last element is most frequent. This code is contributed by Smitha Dinesh Semwal. Sort arr. WriteLine mostFrequent arr,n. Insert all elements in Hash. This code is contributed. ContainsKey key. Add key, 1. Write mostFrequent arr, n .Given n strings, find the common characters in all the strings. In simple words, find characters that appear in all the strings and display them in alphabetical order or lexicographical order.
This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Writing code in comment? Please use ide. XOR two binary strings of unequal lengths.
Examples :. Python3 Program to find all the. Initially marked false.Java Program to Find the Count of Occurrences of Each Character in a String
This code is contributed by Niwesh Gupta. Write " ". Recommended Posts: Remove characters from the first string which are present in the second string A Program to check if strings are rotations of each other or not Print list items containing all characters of a given word Find the smallest window in a string containing all characters of another string Longest Common Subsequence DP-4 Length of the longest substring without repeating characters Check whether two strings are anagram of each other Print all permutations with repetition of characters Print all interleavings of given two strings Interleaving of two given strings with no common characters String matching where one string contains wildcard characters Longest Common Substring DP Find if a string is interleaved of two other strings DP Find the first non-repeating character from a stream of characters Rearrange a string so that all same characters become d distance away.
Load Comments.In Java interviews, finding character frequencies is a popular question. Here we are discussing and implementing a program to find the second most frequent. Finding second highest frequency character in a text is last weeks Thursdays Dzone Code Puzzle. Intention of this post is to try and work out this interview oriented problem in Java with you by explaining the way I am approaching this task. In return, both you and myself can learn through a discussion.
The requirement is to return the character that is the second most frequent. Before writing any code, it is important to break down this requirement into a simple set of test cases.
Most frequent k chars distance
The most correct way would be to start with one test case and proceed with the implementation code, but for the easiness in explanation, I will show four initial test cases and production code to support that requirement. Part 2: will cover additional scenarios which this program does not support. Initial Test Cases 1. All test cases check the equality of expected values against actual. Before; import org. Newer Post Older Post Home.
We appreciate your opinions, suggestions and criticism. Read More While trying to install Nginx server using the source di With Java, putting contents of an Array into a new List object or adding into an existing List object can be achieved easily using a for Web Services with Apache Axis 1. Web services are a handy method of integrating independent systems. Apache Axis is one of the best free tools available for implementing a Java Sorting: Comparator vs Comparable Tutorial.
Java Comparators and Comparables? What are they? How do we use them? This is a question we received from one of our readers. This article With default configurations, JBoss listens on port for web connections.
But this can be changed easily as this port is defined in an In this tutorial we will implement a full data encryption decryption cycle with Java only data, not file encryption ; encrypt some data us Are your Jenkins builds failing due to unavoidable reasons like unavailability of external databases, file systems etc? The only solution yo Test cases for Binary search might not be something you have already written, but the implementation must be an old exercise you may have do Firefox: Dramatic change in release version patterns.