Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

import java.util.ArrayList; import java.util.Comparator; class Train { int trainId; String arrivalTime; String departureTime; public Train ( int trainId, String arrivalTime, String departureTime ) { this.trainId

import java.util.ArrayList;
import java.util.Comparator;
class Train {
int trainId;
String arrivalTime;
String departureTime;
public Train(int trainId, String arrivalTime, String departureTime){
this.trainId = trainId;
this.arrivalTime = arrivalTime;
this.departureTime = departureTime;
}
}
class TrainScheduleManager {
ArrayList trains;
public TrainScheduleManager(){
this.trains = new ArrayList<>();
}
public void addTrain(int trainId, String arrivalTime, String departureTime){
Train newTrain = new Train(trainId, arrivalTime, departureTime);
int index = binarySearchInsertPosition(arrivalTime);
trains.add(index, newTrain);
}
private int binarySearchInsertPosition(String targetArrivalTime){
int low =0;
int high = trains.size()-1;
while (low <= high){
int mid = low +(high - low)/2;
String midArrivalTime = trains.get(mid).arrivalTime;
if (midArrivalTime.compareTo(targetArrivalTime)<0){
low = mid +1;
} else if (midArrivalTime.compareTo(targetArrivalTime)>0){
high = mid -1;
} else {
// Handle cases where arrival times are the same (unlikely for this problem)
low = mid +1; // Insert after duplicates (if any)
}
}
return low; // Insert position
}
public void removeTrain(int trainId){
for (int i =0; i < trains.size(); i++){
if (trains.get(i).trainId == trainId){
trains.remove(i);
break;
}
}
}
public void displaySchedule(){
for (Train train : trains){
System.out.println("Train ID: "+ train.trainId +
"| Arrival: "+ train.arrivalTime +
"| Departure: "+ train.departureTime);
}
}
}
public class Main {
public static void main(String[] args){
TrainScheduleManager manager = new TrainScheduleManager();
manager.addTrain(1,"08:00","08:30");
manager.addTrain(2,"09:00","09:30");
manager.addTrain(3,"09:30","10:00");
manager.addTrain(4,"10:00","10:30");
System.out.println("Initial Train Schedule:");
manager.displaySchedule();
manager.removeTrain(2);
System.out.println("Updated Train Schedule after removing Train 2:");
manager.displaySchedule();
}
}
what is the time complexity and space complexity of this code

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Driven Web Sites

Authors: Mike Morrison, Joline Morrison

1st Edition

061901556X, 978-0619015565

More Books

Students also viewed these Databases questions