1. Meandering Array
public static List<Integer> meanderingArray(List<Integer> list) {
Collections.sort(list);
List<Integer> res = new ArrayList<>();
int i = list.size() - 1, j = 0;
while (j <= i) {
res.add(list.get(i--));
if (j <= i) res.add(list.get(j++));
}
return res;
}
2. Project Estimates
public static int countPairs(List<Integer> costs, int target) {
Set<Integer> set = new HashSet<>(costs);
int count = 0;
for (int x : costs)
if (set.contains(x + target)) count++;
return count;
}
3. Ensemble Model Selection
public static int countValidEnsembles(
List<Integer> a, int minModels, int minAccuracy, int maxAccuracy) {
int n = 0;
for (int x : a)
if (x >= minAccuracy && x <= maxAccuracy) n++;
int count = 0;
for (int mask = 1; mask < (1 << n); mask++)
if (Integer.bitCount(mask) >= minModels) count++;
return count;
}
4. Rover Control
public static int roverControl(int n, List<String> commands) {
int r = 0, c = 0;
for (String s : commands) {
switch (s) {
case "UP": if (r > 0) r--; break;
case "DOWN": if (r < n - 1) r++; break;
case "LEFT": if (c > 0) c--; break;
case "RIGHT": if (c < n - 1) c++; break;
}
}
return r * n + c;
}
5. Transaction Sequence Optimization
public static int maxTransactions(List<Integer> transactions) {
transactions.sort(Collections.reverseOrder());
long sum = 0;
int count = 0;
for (int x : transactions) {
if (sum + x <= 0) break;
sum += x;
count++;
}
return count;}
1. Election Exit Poll Distribution Report
SELECT state,GROUP_CONCAT(CONCAT(name,' x ',c) ORDER BY c DESC,name) votes
FROM (SELECT state,CONCAT(first_name,' ',last_name) name,COUNT(*) c
FROM results JOIN candidates ON candidate_id=id
GROUP BY state,id,name) t
GROUP BY state ORDER BY state;
2. Long-term vs Short-term Investment Analysis
SELECT name client_name,
(SELECT FORMAT(SUM(invested_amount),2) FROM bonds_investments WHERE client_id=clients.id) total_invested_in_bonds,
(SELECT FORMAT(SUM(invested_amount),2) FROM stocks_investments WHERE client_id=clients.id) total_invested_in_stocks
FROM clients
HAVING total_invested_in_bonds>5000
ORDER BY total_invested_in_bonds DESC;
3. Advertising Product Engagement Metrics Report
WITH s AS (
SELECT SUM(is_confirmed=1) v FROM views
), c AS (
SELECT SUM(is_confirmed=1) c FROM clicks
)
SELECT 'Total Views' metric_name,CAST(v AS CHAR) metric_value FROM s
UNION ALL
SELECT 'Total Clicks',CAST(c AS CHAR) FROM c
UNION ALL
SELECT 'Click Through Rate',CAST(ROUND(c*100/v,2) AS DECIMAL(10,2))
FROM s CROSS JOIN c;
4. Cryptocurrency Portfolio Analysis
SELECT crypto_type,crypto_name,
CONCAT('$',CAST(ROUND(total_value,2) AS DECIMAL(15,2))) total_value
FROM (
(SELECT 'Coin' crypto_type,name crypto_name,
quantity*REPLACE(unit_value,'$','') total_value
FROM coins ORDER BY total_value DESC LIMIT 5)
UNION ALL
(SELECT 'Token',name,quantity*REPLACE(unit_value,'$','')
FROM tokens ORDER BY total_value DESC LIMIT 5)
) t
ORDER BY crypto_type,total_value DESC;
1.Maximum Transfer
import java.net.URI;
import java.net.http.*;
import java.io.IOException;
import java.util.*;
import com.google.gson.*;
class Solution {
public static String[] transferAmount(String name, String city) {
double credit = 0, debit = 0;
long page = 1, totalPages = 1;
HttpClient client = HttpClient.newHttpClient();
while (page <= totalPages) {
String url = "https://jsonmock.hackerrank.com/api/transactions?page=" + page;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Accept", "application/json")
.GET().build();
try {
HttpResponse<String> res = client.send(
req, HttpResponse.BodyHandlers.ofString());
JsonObject json = JsonParser.parseString(res.body()).getAsJsonObject();
totalPages = json.get("total_pages").getAsLong();
for (JsonElement e : json.getAsJsonArray("data")) {
JsonObject t = e.getAsJsonObject();
if (t.get("userName").getAsString().equals(name)
&& t.getAsJsonObject("location").get("city")
.getAsString().equals(city)) {
double amount = Double.parseDouble(
t.get("amount").getAsString()
.replace("$", "").replace(",", ""));
String type = t.get("txnType").getAsString();
if (type.equals("credit"))
credit = Math.max(credit, amount);
else if (type.equals("debit"))
debit = Math.max(debit, amount);
}
}
} catch (IOException | InterruptedException e) {
Thread.currentThread().interrupt();
return new String[]{"0.00","0.00"};
}
page++;
}
return new String[]{
String.format("$%,.2f", credit),
String.format("$%,.2f", debit)
};
}
}
2.Future Events
import java.net.URI;
import java.net.http.*;
import java.time.Instant;
import java.io.IOException;
import java.util.*;
import com.google.gson.*;
class Solution {
public static List<String> futureEvents(String country, long plannedDate) {
List<String> result = new ArrayList<>();
HttpClient client = HttpClient.newHttpClient();
long page = 1, totalPages = 1, firstDate = Long.MAX_VALUE, lastDate = Long.MIN_VALUE;
String first = "", last = "";
while (page <= totalPages) {
String url = "https://jsonmock.hackerrank.com/api/events?country="
+ country + "&page=" + page;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(url)).GET().build();
try {
HttpResponse<String> res = client.send(
req, HttpResponse.BodyHandlers.ofString());
JsonObject json = JsonParser.parseString(res.body()).getAsJsonObject();
totalPages = json.get("total_pages").getAsLong();
for (JsonElement e : json.getAsJsonArray("data")) {
JsonObject event = e.getAsJsonObject();
long date = Instant.parse(
event.get("date").getAsString()).toEpochMilli();
if (date > plannedDate) {
String name = event.get("name").getAsString();
if (date < firstDate) {
firstDate = date;
first = name;
}
if (date > lastDate) {
lastDate = date;
last = name;
}
}
}
} catch (IOException | InterruptedException e) {
Thread.currentThread().interrupt();
return Arrays.asList("", "");
}
page++;
}
result.add(first);
result.add(last);
return result;
}
}
3.City Weather
import java.net.URI;
import java.net.http.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
import java.util.*;
import com.google.gson.*;
class Solution {
public static String[] weatherStation(String keyword) {
List<String> result = new ArrayList<>();
HttpClient client = HttpClient.newHttpClient();
long page = 1, totalPages = 1;
while (page <= totalPages) {
String url = "https://jsonmock.hackerrank.com/api/weather/search?name="
+ URLEncoder.encode(keyword, StandardCharsets.UTF_8)
+ "&page=" + page;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(url)).GET().build();
try {
HttpResponse<String> res = client.send(
req, HttpResponse.BodyHandlers.ofString());
JsonObject json = JsonParser.parseString(res.body()).getAsJsonObject();
totalPages = json.get("total_pages").getAsLong();
for (JsonElement e : json.getAsJsonArray("data")) {
JsonObject city = e.getAsJsonObject();
String name = city.get("name").getAsString();
String temp = city.get("weather").getAsString()
.replaceAll("[^0-9.-]", "");
JsonArray status = city.getAsJsonArray("status");
String wind = status.get(0).getAsString()
.replaceAll("[^0-9.-]", "");
String humidity = status.get(1).getAsString()
.replaceAll("[^0-9.-]", "");
result.add(name + "," + temp + "," + wind + "," + humidity);
}
} catch (IOException e) {
return new String[0];
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return new String[0];
}
page++;
}
Collections.sort(result);
return result.toArray(new String[0]);
}
}
4.Pulse Rate
import java.net.URI;
import java.net.http.*;
import java.io.IOException;
import com.google.gson.*;
class Solution {
public static int pulseRate(String diagnosisName, int doctorId) {
HttpClient client = HttpClient.newHttpClient();
long page = 1, totalPages = 1, sum = 0, count = 0;
while (page <= totalPages) {
String url = "https://jsonmock.hackerrank.com/api/medical_records?page=" + page;
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(url)).GET().build();
try {
HttpResponse<String> res = client.send(
req, HttpResponse.BodyHandlers.ofString());
JsonObject json = JsonParser.parseString(res.body()).getAsJsonObject();
totalPages = json.get("total_pages").getAsLong();
for (JsonElement e : json.getAsJsonArray("data")) {
JsonObject record = e.getAsJsonObject();
JsonObject diagnosis = record.getAsJsonObject("diagnosis");
JsonObject doctor = record.getAsJsonObject("doctor");
if (diagnosis.get("name").getAsString().equals(diagnosisName)
&& doctor.get("id").getAsInt() == doctorId) {
sum += record.getAsJsonObject("vitals").get("pulse").getAsInt();
count++;
}
}
} catch (IOException e) {
return 0;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return 0;
}
page++;
}
return count == 0 ? 0 : (int) (sum / count);
}
}
5. TV Show
import java.net.URI;
import java.net.http.*;
import java.util.*;
import com.google.gson.*;
class Result {
public static List<String> showsInProduction(int startYear, int endYear)
throws Exception {
List<String> result = new ArrayList<>();
HttpClient client = HttpClient.newHttpClient();
int page = 1, totalPages = 1;
while (page <= totalPages) {
String url = "https://jsonmock.hackerrank.com/api/tvseries?page=" + page;
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString());
JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject();
totalPages = json.get("total_pages").getAsInt();
JsonArray data = json.getAsJsonArray("data");
for (JsonElement item : data) {
JsonObject show = item.getAsJsonObject();
String name = show.get("name").getAsString();
String runtime = show.get("runtime_of_series").getAsString();
if (runtime.matches("^\\([IVXLCDM]+\\) .*")) {
runtime = runtime.substring(runtime.indexOf(") ") + 2);
}
String years = runtime.replaceAll(
".*\\((\\d{4})(?:-(\\d{4}))?\\).*", "$1 $2");
String[] y = years.trim().split("\\s+");
int start = Integer.parseInt(y[0]);
int end = y.length > 1 ? Integer.parseInt(y[1]) : start;
if (start >= startYear &&
(endYear == -1 ? end == -1 : end != -1 && end <= endYear)) {
result.add(name);
}
}
page++;
}
Collections.sort(result);
return result;
}
}3 views