DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Java UDFs and Stored Procedures for Data Engineers: A Hands-On Guide
  • Using Java Class Extension Library for Data-Oriented Programming - Part 2
  • Using Java Class Extension Library for Data-Oriented Programming
  • Practical Generators in Go 1.23 for Database Pagination

Trending

  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • System Coexistence: Bridging Legacy and Modern Architecture
  • After 9 Years, Microsoft Fulfills This Windows Feature Request
  • Introduction to Retrieval Augmented Generation (RAG)
  1. DZone
  2. Data Engineering
  3. Data
  4. SKP's Algorithms and Data Structures #6: Java Problem: Active Traders

SKP's Algorithms and Data Structures #6: Java Problem: Active Traders

This Article Series Focuses on Algorithms, Data Structures, or Applying them to Problem Solving. In this Article, We Discuss the Solution to [Active Traders] Problem from Hacker Rank.

By 
Sumith Puri user avatar
Sumith Puri
·
Feb. 28, 21 · Code Snippet
Likes (3)
Comment
Save
Tweet
Share
8.1K Views

Join the DZone community and get the full member experience.

Join For Free

[Question/Problem Statement is the Property of HackerRank]

Algorithms/Data Structures — [Problem Solving] 
An Institutional Broker wants to Review their Book of Customers to see which are Most Active. Given a List of Trades By "Customer Name, Determine which Customers Account for At Least 5% of the Total Number of Trades. Order the List Alphabetically Ascending By Name."


Example
n = 23
"customers = {"Bigcorp", "Bigcorp", "Acme", "Bigcorp", "Zork", "Zork", "Abe", "Bigcorp", "Acme", "Bigcorp", "Bigcorp", "Zork", "Bigcorp", "Zork", "Zork", "Bigcorp", "Acme", "Bigcorp", "Acme", "Bigcorp", "Acme", "Littlecorp", "Nadircorp"}."

"Bigcorp had 10 Trades out of 23, which is 43.48% of the Total Trades."
"Both Acme and Zork had 5 trades, which is 21.74% of the Total Trades."
"The Littlecorp, Nadircorp, and Abe had 1 Trade Each, which is 4.35%..."

"So the Answer is ["Acme","Bigcorp","Zork"] (In Alphabetical Order) Because only These Three Companies Placed at least 5% of the Trades.


Function Description

Complete the Function mostActive in the Editor Below.

mostActive
has the following parameter:
String customers[n]: An Array Customer Names
(Actual Question Says String Array, But Signature is List of Strings)

Returns String[]: An Alphabetically Ascending Array


Constraints

• 1 < n < 10^5
• 1 < Length of customers[] < 20
• The First Character of customers[i] is a Capital English letter.
• All Characters of customers[i] except for the First One are Lowercase.
• Guaranteed that At least One Customer makes at least 5% of Trades.


Input Format

"The First Line contains an integer, n, The Number of Elements in customers."
"Each Line i of the n Subsequent Lines (where 0 s i< n) contains a string, customers[i]."


Sample Case 0 Input For Custom Testing
20
Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Beta


Function mostActive       
customers[] size n = 20
customers[] = [As Provided Above]


Sample Output

Alpha
Beta
Omega


Explanation

"Alpha made 10 Trades out of 20 (50% of the Total), Omega made 9 Trades (45% of the Total). and Beta made 1 Trade (5% of the Total). All of them have met the 5% Threshold, so all the Strings are Returned in an Alphabetically Ordered Array."

 

[Explanation of the Solution]
This is Good Practice for the Brain for Problem Solving — Involves Simple Arithmetic and Mathematical Application. Ideally, A Programmer would want to Optimize the Solution in Space and Time (Which I Did Not :-)
 


[Source Code, Sumith Puri (c) 2021 — Free to Use and Distribute]
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.IntStream;

/*
 * HackerRank Problem Solving - Ain't a Horse that Can't be Rode
 * Sumith Kumar Puri (c) 2021 - ~ Bengaluru, Karnataka, India ~
 * 
 */
class ActiveTradersLogic {
    
    public static List<String> mostActive(List<String> customers) {

        // How About Arrays or Custom LinkedList for a 'Very Fast' Traversal?
        Map<String, Integer> customerMap = new TreeMap<String, Integer>();
        List<String> solutionStr = new ArrayList<String>();
        int customerMapSize = customers.size();

        for (int i = 0; i < customerMapSize; i++) {

            String customerKey = customers.get(i);

            if (customerMap.containsKey(customerKey)) {

                Integer customerCount = customerMap.get(customerKey);
                customerMap.put(customerKey, ++customerCount);
            } else {
                customerMap.put(customerKey, 1);
            }
        }

        Set<String> customerMapKeys = customerMap.keySet();
        for (String customerKey : customerMapKeys) {

            Integer customerCount = customerMap.get(customerKey);
            double currentCustomerPercent = (double) (customerCount) / (double) customerMapSize;

            if (currentCustomerPercent * 100 >= 5.0) {

                solutionStr.add(customerKey);
            }
        }

        return solutionStr;
    }
}

public class ActiveTraders {
    
    public static final String OUTPUT_PATH = "PROVIDE_ABSOLUTE_INPUT_FILE_NAME";
    
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv(OUTPUT_PATH)));

        int customersCount = Integer.parseInt(bufferedReader.readLine().trim());

        List<String> customers = IntStream.range(0, customersCount).mapToObj(i -> {
            try {
                return bufferedReader.readLine();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }).collect(toList());

        List<String> result = ActiveTradersLogic.mostActive(customers);

        bufferedWriter.write(result.stream().collect(joining("\n")) + "\n");

        bufferedReader.close();
        bufferedWriter.close();
    }
}


Happy Problem Solving using Java! 6

Alpha (finance) Java (programming language) Data (computing)

Published at DZone with permission of Sumith Puri. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java UDFs and Stored Procedures for Data Engineers: A Hands-On Guide
  • Using Java Class Extension Library for Data-Oriented Programming - Part 2
  • Using Java Class Extension Library for Data-Oriented Programming
  • Practical Generators in Go 1.23 for Database Pagination

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!