Unable to Find Time Complexity - time-complexity

Below I am attaching my code(complete) , pls help me get an idea of how to find time_complexity and space_complexity of my code , especially for adding , updating and copying the set.
Thanks in Advance !!!
class Solution {
public List<List<Integer>> getAncestors(int n, int[][] edges) {
Set<Integer> [] ancestors = new Set[n] ;
int [] in_degree = new int[n] ;
List<Integer>[] li = new List[n] ;
for (int i = 0; i < n; i++) { // T.C. = O(n)
ancestors[i] = new HashSet<> ();
li[i] = new ArrayList<>() ;
}
// creating adj_list
for(int []edge : edges){ // T.C. = O(E)
li[edge[0]].add(edge[1]) ;
in_degree[edge[1]] ++ ;
}
helper(n , li , in_degree , ancestors) ;
// filling from (set) to List<Integer> in (lineage)
List<List<Integer>> lineage = new ArrayList<>() ;
for (int i = 0; i < n; i++) {
List<Integer> list = new ArrayList<>() ;
for(int j : ancestors[i]){
list.add(j) ; // copying set to list
}
Collections.sort(list);
lineage.add(list) ;
}
return lineage ;
}
//_____________________________________________________________________________________________________
private void helper(int n, List<Integer>[]li, int [] in_degree , Set<Integer> [] ancestors) {
Queue<Integer> q = new LinkedList<>() ;
for (int i = 0; i < n; i++) if(in_degree[i] == 0) q.add(i) ; // T.C. = O(n)
while(!q.isEmpty()){
int node = q.remove() ;
Set<Integer> grand_ancestors = ancestors[node] ;
for(int u : li[node]){
ancestors[u].add(node) ;
ancestors[u].addAll(grand_ancestors) ;
if(--in_degree[u] == 0) q.add(u) ;
}
}
}
}

Related

What is the Time Complexity and Space complexity of the following codes?

Here are the codes attached below. I have done these problems in one of the FAANG companies. I am open to have a discussion on time complexity and space complexity of these codes.
Code1:
public static void main(String[] args) {
int[] arr = {4,5,6,7};
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < arr.length; i++) {
queue.add(arr[i]);
}
System.out.println(queue);
while (queue.size() > 2) {
int first = queue.poll();
for (int i = 0; i < queue.size(); i++) {
int second = queue.poll();
queue.add(first % 10 + second % 10);
first = second;
}
}
int first = queue.poll() % 10;
int second = queue.poll() % 10;
int res = first + second;
System.out.println(res);
}
Time Complexity: ?
Space Complexity: ?
and Code 2:
public static void main(String[] args) {
String input = "aabbcaac";
HashMap<Character, Integer> map1 = new HashMap<>();
HashMap<Character, Integer> map2 = new HashMap<>();
char[] ip = input.toCharArray();
for (int i = 0; i < ip.length; i++) {
map2.put(ip[i], map2.getOrDefault(ip[i] , 0)+1);
}
System.out.println (map2);
int currVal = 0;
int result = 0;
int k = 1;
for (char str : ip) {
map2.put(str, map2.get(str) - 1);
if (map2.get(str) > 0) {
currVal += 1;
}
if(map1.get(str) == null) {
map1.put(str, 0);
}
if (map1.get(str) > 0) {
currVal -= 1;
}
map1.put(str, map1.get(str) + 1);
if (currVal > k) {
result += 1;
}
System.out.println(currVal);
}
System.out.println(result);
}
Time Complexity: ?
Space Complexity: ?

How to access the values of a dictionary property in a grid using Ocean for Petrel?

I'm tring to access the values of a dictionary property in a grid,such as Fluvial facies or lithologies etc.I have read the coursebook and help docs, but didn't find anything relevant.The coursebook only has examples of creating properties, but not accessing properties.Below is the code I tried:
Grid grid = arguments.Input_Grid;
if (grid == null)
{
PetrelLogger.ErrorStatus("HelloGrid: Arguments cannot be empty.");
return;
}
Index3 currentCell = new Index3();
int maxI = grid.NumCellsIJK.I;
int maxJ = grid.NumCellsIJK.J;
int maxK = grid.NumCellsIJK.K;
for (int i = 0; i < maxI; i++)
{
for (int j = 0; j < maxJ; j++)
{
for (int k = 0; k < maxK; k++)
{
currentCell.I = i; currentCell.J = j; currentCell.K = k;
if (grid.IsCellDefined(currentCell) && grid.HasCellVolume(currentCell))
{
//DictionaryProperty p = ???
//int val = p[currentCell] ???
}
}
}
}
You need to use the "FastDictionaryPropertyIndexer" or "FastPropertyIndexer" for regular properties.
foreach (var dictProp in grid.DictionaryProperties)
{
int numCellsI = dictProp.NumCellsIJK[0];
int numCellsJ = dictProp.NumCellsIJK[1];
int numCellsK = dictProp.NumCellsIJK[2];
float[] values = new float[dictProp.NumCells];
var dpsa = dictProp.SpecializedAccess;
using (var fdpi = dpsa.OpenFastDictionaryPropertyIndexer())
{
int index = 0;
for (int k = 0; k < numCellsK; k++)
{
for (int j = 0; j < numCellsJ; j++)
{
for (int i = 0; i < numCellsI; i++)
{
values[index] = fdpi[i, j, k];
index++;
}
}
}
}
}
You also need to be careful about the indexing since it varies by project. For instance, you may need to reverse the order of traversal in the J direction or you could end up with some strange results.

polynomial operator+ function is causing the wrong output or is it print function

this is the output showing :
+2x^0 +0x^1 +0x^2 +0x^3 -5x^4
+0x^0 +0x^1 +0x^2 +0x^3 +6x^4 +0x^5 +0x^6 +0x^7 -9x^8
+2x^0 +0x^1 +0x^2 +0x^3 +1x^4 +0x^5 +0x^6 +0x^7 +1584935467x^8 // output of p1+p2
why is is showing 158.... in x power 8 term .
it should show simply -9x^8 only .
i am trying to learn to implement operator overloading in it .
i think the problem is in loop of overloading function .
#include <iostream>
using namespace std ;
class polynomial {
int* degree ;
int capacity ;
public:
polynomial () {
degree = new int[5];
for ( int i = 0 ; i < 5 ; i ++){
degree[i] = 0 ;
}
capacity = 5 ;
}
// copy constructor
polynomial (const polynomial& p){
this -> degree = new int[p.capacity];
for( int i = 0 ; i < p.capacity ; i++){
this -> degree[i] = degree[i];
}
this -> capacity = p.capacity;
}
// assignment operator overload
void operator=(polynomial const &p){
this -> degree = new int[p.capacity];
for( int i = 0 ; i < p.capacity ; i++){
this -> degree[i] = p.degree[i];
}
this -> capacity = p.capacity;
}
void print(){
for ( int i = 0 ; i < capacity ; i ++ ){
if( degree[i] >= 0)
cout << "+"<< degree[i] <<"x^" <<i<<" ";
else cout<< degree[i] <<"x^" <<i << " ";
}
cout << endl;
}
void setCoefficient( int de , int num ){
if( de < capacity ){
degree[de] = num ;
}
else {
int ic = capacity ;
capacity = capacity+(de-capacity+1) ;
int* ne = new int[capacity];
for( int i = 0 ; i < capacity ; i ++){
ne[i] = 0 ;
}
for( int i = 0 ; i < ic; i ++){
ne[i] = degree[i];
}
delete [] degree;
degree = ne;
degree[de] = num ;
}
}
polynomial operator+( polynomial const &p){
polynomial tp ;
tp.capacity = max(capacity, p.capacity) ;
int i = 0 ;
for(; i < max(this->capacity, p.capacity) ; i ++){
if(i <= capacity && i <= p.capacity)
{tp.degree[i] = degree[i] + p.degree[i];}
else if ( i < p.capacity) tp.degree[i] = p.degree[i] ;
else tp.degree[i] = degree[i];
}
return tp;
}
polynomial operator-( polynomial const &p){
polynomial tp ;
tp.capacity = max(capacity, p.capacity) ;
for( int i = 0 ; i < max(this->capacity, p.capacity) ; i ++){
tp.degree[i] = degree[i] - p.degree[i];
}
return tp;
}
};
#include <bits/stdc++.h>
#include "polynomialClass.cpp"
using namespace std;
int main (){
polynomial p1 , p2 ;
p1.setCoefficient(4, -5);
p1.setCoefficient(0,+2);
p1.print();
p2.setCoefficient(8,-9);
p2.setCoefficient(4,+6);
p2.print();
polynomial p3 = p1 + p2;
p3.print();
}

How I can sort an ArrayList of int arrays?

I have this code. I'm dealing with the N-Queen problem.
The problem is when I wanna show results by screen, the arrays are not ordered. But in this code I can't order them using Comparator. It's very strange because in other Class it works perfectly using Comparator, but here it doesn't work. Hope anyone could help me. Thanks in advance.
import java.util.*;
public class NReinas {
public static void resolverReinas(int n){
String[][] tablero;
tablero = generarTablero(n);
ubicarReina(tablero, 0, n);
}
public static void ubicarReina(String[][] tablero, int etapa, int n){
ArrayList <int[]> resultados = new ArrayList<>();
for(int i = 0; i < tablero.length; i++){
if(isValido(tablero, i, etapa)){
tablero[i][etapa] = "R";
if(etapa < tablero.length - 1){
ubicarReina(tablero, etapa + 1, n); //Recursividad
}else {
resultados.add(devolverSolucion(tablero, n));
}
tablero[i][etapa] = " "; //Backtracking: vaciamos el tablero
}
}
//The ArrayList I want to order by int arrays
for (int[] r : resultados) {
System.out.println(Arrays.toString(r));
}
}
public static boolean isValido(String[][] tablero, int i, int etapa){
for(int x = 0; x < etapa; x++){
if(tablero[i][x].equals("R")){
return false;
}
}
for(int j = 0; j < tablero.length && (i-j) >= 0 && (etapa-j) >=0; j++){
if(tablero[i - j][etapa - j].equals("R")){
return false;
}
}
for(int j = 0; j < tablero.length && (i + j) < tablero.length && etapa - j >= 0; j++){
if(tablero[i + j][etapa - j].equals("R")){
return false;
}
}
return true;
}
public static String[][] generarTablero(int length){
String[][]res = new String[length][length];
for (int i = 0; i < res.length; i++) {
for (int j = 0; j < res.length; j++) {
res[i][j] = " ";
}
}
return res;
}
public static int[] devolverSolucion(String[][] tablero, int n){
int[] solucion = new int[n];
for (int i = 0; i < tablero.length; i++) {
for (int j = 0; j < tablero.length; j++) {
if(tablero[i][j] == "R"){
solucion[i] = j;
}
}
}
return solucion;
}
}
Try Using Integer instead of int and save array values on List instead, so you can use sort them
List<Integer> list = Arrays.asList(solucion);
Collections.sort(list);
If you insist in using and array you can reconverti the list to an array
(Integer[]) list.toArray();

ArrayList Method Returns a null ArrayList, main program cannot access

I'm trying to create a basic function that calls on a method that creates the 2D ArrayList that will be used further in the main program to do things like calculate the row and column sums as well as print out the triangle.
However, after it runs the ArrayList returns null. What's going on?
Thanks,
public class Trib
{
private ArrayList<ArrayList<Integer>> triangle;
private int Asize;
public Trib (int size)
{
// convert the argument to type 'int' to be used in the program
Asize = size;
// create an ArrayList of ArrayLists, it will have 'size' number ArrayLists contained within
ArrayList<ArrayList<Integer>> triangle = new ArrayList<ArrayList<Integer>>(size);
// create the inner ArrayLists
for (int i = 0; i < size; i++)
{
// add to index 'i' of our ArrayList a new ArrayList of size (i+1)
triangle.add(new ArrayList<Integer>(i+1));
for (int j = 0; j <= i; j++)
{
if (j==0 || j == i)
{
triangle.get(i).add(1);
}
else
triangle.get(i).add(triangle.get(i-1).get(j-1)+triangle.get(i-1).get(j));
System.out.print(triangle.get(i).get(j) + " ");
}
System.out.println();
}
triangle.clone();
}
public void printTriangle()
{
System.out.print(triangle.get(1).get(1));
/*for (int i = 0; i < Asize; i++)
{
for (int j = 0; j <= i; j++)
{
System.out.print(triangle.get(1).get(1) + " ");
}
System.out.println();
}*/
}
/*public Trib()
{
this(5);
}*/
/*public int Psize()
{
return triangle.size();
}
public ArrayList<Integer> sumRows()
{
ArrayList<Integer> row_sum = new ArrayList<Integer>(Asize);
for (int i = 0; i < Asize; i++)
{
for (int j = 0; j < i; j++)
{
row_sum.add(triangle.get(i).get(j));
}
}
return row_sum;
}
public ArrayList<Integer> sumCols()
{
ArrayList<Integer> col_sum = new ArrayList<Integer>(Asize);
for (int i = 0; i < Asize; i++)
{
for (int j = 0; j < i; j++)
{
col_sum.add(triangle.get(i).get(i));
}
}
return col_sum;
}*/
public static void main(String[] args)
{
if(args.length < 1)
{
System.err.println("Sorry, this program needs an integer argument.");
System.exit(1);
}
Trib pt = new Trib(Integer.parseInt(args[0]));
pt.printTriangle();
//ArrayList<Object> sum_rows = new ArrayList<Object>(pt.Psize());
// sum_rows.add;
System.out.println("\nHere are the sum of rows:");
//for (int i = 0; i < pt.Psize(); i++)
//System.out.println(sum_rows.get(i));
//ArrayList<Integer> sum_cols = new ArrayList<Integer>(pt.Psize());
System.out.println("\nHere are the sum of columns:");
//for (int i = 0; i < pt.Psize(); i++)
//System.out.printf("%-5d", sum_cols.get(i));
}
}
Watch out what's what you are doing: Notice that you have TWO variables named "triangle": The first one is an instance variable and the second is a local variable, which is the only one you have initialized.
My suggestion to avoid this common mistake is to pre-pend "this." to any use of what you intend must be an instance variable. And, if in doubt, if you use a development environment as Eclipse, press CTRL and click on your variable to navigate to the point where it is declared.