本段 575 题 | 来源:fullstack + general + design | 知识点:算法与数据结构
1. 是否应该优化算法(algorithm)或代码(code)以提高运行速度?为什么?
- 知识点: 算法与数据结构 (主题: algorithms;标签: optimization, performance, algorithms)
- 类型: technical | 难度: easy | 子类型:
- 分类: general
- id: 695e1a981da5537956393cfd | 官方: 是 | 付费: 否
答案:
TL;DR是的,通常建议优化算法或代码以提升运行速度。原文观点认为:优化后的算法能够更贴合业务问题,优化程度越高,运行速度越快。
原因- 原文认为优化算法能更好理解业务问题
- 优化程度越高,速度越快
2. What is the difference between a stack and a queue?
栈和队列之间有什么区别?
- 知识点: 算法与数据结构
- 类型: technical | 难度: easy | 子类型:
- 分类: general
- 公司: Google
- id: 6964718ba9243c30c87060b3 | 官方: 是 | 付费: 否
答案:
Both a stack and a queue are abstract data types for storing and retrieving information in a certain sequence. The order in which elements are added and removed differs among them.
栈和队列都是用于按特定顺序存储和检索信息的抽象数据类型。它们添加和移除元素的顺序不同。
A stack is a data structure that follows the Last-In, First-Out (LIFO) principle. This indicates that the element introduced last is the first to be removed. Consider a cafeteria plate stack: the last plate placed on the stack is the first to be removed from the top.
栈是遵循后进先出(LIFO)原则的数据结构。这表明最后引入的元素最先被移除。考虑一个自助餐厅的盘子堆:最后放在堆上的盘子最先从顶部被移除。
A queue, on the other hand, is a First-In, First-Out (FIFO) data structure. This means that the first piece added to the queue is the first to be eliminated. Consider a queue of people waiting for a bus: the first person to arrive is the first to board.
另一方面,队列是先进先出(FIFO)数据结构。这意味着最早添加到队列的元素最先被移除。考虑排队等公交车的人群:第一个到达的人第一个上车。
3. Java 中如何将字符串(string)转换为整数(integer)?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, string;标签: Parsing, Integer)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965d432f760bfe7d4f8b704 | 官方: 是 | 付费: 否
答案:
答案使用 Integer.parseInt(str) 或 Integer.valueOf(str)。需要处理异常:无效数字会抛 NumberFormatException。如果有进制可用 Integer.parseInt(str, radix)。
4. 怎么将 byte 转换为 String?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, encoding;标签: byte[], String, charset, encoding)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965dbd6fa809e6d38860d40 | 官方: 是 | 付费: 否
答案:
答案可以使用 String 接收 byte[] 参数的构造器来进行转换,需要注意的点是要使用的正确的编码(encoding),否则会使用平台默认编码(platform default encoding),这个编码可能跟原来的编码相同,也可能不同。
5. List、Set、Map 和 Queue 之间的区别
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, collections;标签: List, Set, Map, Queue)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965dcf6fa809e6d388632fd | 官方: 是 | 付费: 否
答案:
答案List 是一个有序集合(ordered collection),允许元素重复。它的某些实现可以提供基于下标值的常量访问时间(constant-time access),但是这不是 List 接口保证的。Set 是一个无序集合(unordered collection)。
6. poll() 方法和 remove() 方法的区别?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, collections;标签: Queue, poll, remove, exception)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965dcf6fa809e6d38863301 | 官方: 是 | 付费: 否
答案:
答案poll() 和 remove() 都是从队列(Queue)中取出一个元素,但是 poll() 在获取元素失败的时候会返回空(null),但是 remove() 失败的时候会抛出异常(Exception)。
7. ArrayList 与 LinkedList 的区别?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, collections;标签: ArrayList, LinkedList, random access, time complexity)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965dcf6fa809e6d38863309 | 官方: 是 | 付费: 否
答案:
答案最明显的区别是 ArrrayList 底层的数据结构是数组(Array),支持随机访问(Random Access),而 LinkedList 的底层数据结构书链表(Linked List),不支持随机访问。使用下标访问一个元素,ArrayList 的时间复杂度(Time Complexity)是 O(1),而 LinkedList 是 O(n)。更多细节的讨论参见答案。
8. 用哪两种方式来实现集合的排序?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, collections;标签: sorting, TreeSet, TreeMap, Collections.sort)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965dcf7fa809e6d388633dc | 官方: 是 | 付费: 否
答案:
答案你可以使用有序集合(Sorted Collection),如 TreeSet 或 TreeMap,你也可以使用有顺序的的集合,如 list,然后通过 Collections.sort() 来排序。
9. Java 中怎么打印数组?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, arrays;标签: Arrays.toString, Arrays.deepToString, print array)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965dcf7fa809e6d388633e9 | 官方: 是 | 付费: 否
答案:
答案你可以使用 Arrays.toString() 和 Arrays.deepToString() 方法来打印数组。由于数组没有实现 toString() 方法,所以如果将数组传递给 System.out.println() 方法,将无法打印出数组的内容,但是 Arrays.toString() 可以打印每个元素。
10. Java 中的 LinkedList 是单向链表还是双向链表?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, collections;标签: LinkedList, doubly linked list)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965dcf7fa809e6d388633ed | 官方: 是 | 付费: 否
答案:
答案是双向链表(Doubly Linked List),你可以检查 JDK 的源码。在 Eclipse,你可以使用快捷键 Ctrl + T,直接在编辑器中打开该类。
11. Java 中的 TreeMap 是采用什么树实现的?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, collections, data-structures;标签: TreeMap, Red-Black tree)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965dcf7fa809e6d388633f1 | 官方: 是 | 付费: 否
答案:
答案Java 中的 TreeMap 是使用红黑树(Red-Black Tree)实现的。
12. 怎么检查一个字符串只包含数字?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, string;标签: String, Digits, Regex)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965e03dfa809e6d3886840a | 官方: 是 | 付费: 否
答案:
答案可以用正则表达式(Regular Expression):str.matches("\d+")(注意空字符串需单独处理)。也可以遍历字符:对每个字符调用 Character.isDigit(c),只要有一个不是数字就返回 false。
13. 在不使用 StringBuffer 的前提下,怎么反转一个字符串?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, string;标签: Reverse String, Two Pointers)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965e03dfa809e6d38868416 | 官方: 是 | 付费: 否
答案:
答案可以把字符串转为 char[],使用双指针(Two Pointers)首尾交换并构造新字符串;或者用递归(Recursion)/栈(Stack)。示例思路:char[] a = s.toCharArray();,i=0,j=a.length-1 循环交换,最后 new String(a)。
14. 如何检查出两个给定的字符串(String)是反序的?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, string;标签: Reverse Check, Two Pointers)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965e03efa809e6d388684fc | 官方: 是 | 付费: 否
答案:
答案先判断长度(length)是否相等;然后用双指针(two pointers):一个从 s1 开头走,一个从 s2 末尾走,逐字符比较,全部相等则互为反序。也可以反转(reverse)其中一个字符串再做 equals(equals)比较(但会额外创建对象(object))。
15. 你能写出一个正则表达式(regular expression)来判断一个字符串(String)是否是一个数字(number)吗?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, regex, string;标签: Regex, Number Validation)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965e1d2fa809e6d3886aaab | 官方: 是 | 付费: 否
答案:
答案一个数字字符串(numeric string),只能包含数字(digit),如 0 到 9 以及 +、- 开头,通过这个信息,你可以下一个如下的正则表达式(regular expression)来判断给定的字符串(String)是不是数字(number)。
示例:^[+-]?\d+$
16. String s = new String("xyz");创建了几个字符串对象(String object)?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, string, jvm;标签: String Pool, new, Object Creation)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965e5a2fa809e6d38872acf | 官方: 是 | 付费: 否
答案:
答案两个对象(object),一个是静态区(static area)的"xyz",一个是用new创建在堆(heap)上的对象(object)。
17. 是否可以继承(inherit)String类(class)?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: String, final, Inheritance)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965e772fa809e6d388763ed | 官方: 是 | 付费: 否
答案:
答案String类是final类(final class)故不可以继承(inherit)
18. String(字符串) 属于基础的数据类型吗?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: String, Primitive Types)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965e90cfa809e6d38877f8b | 官方: 是 | 付费: 否
答案:
答案String 不属于基础类型(primitive type),基础类型(primitive type)有 8 种:byte、boolean、char、short、int、float、long、double,而 String 属于对象(object)。
19. String str="i"与 String str=new String("i")一样吗?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, jvm;标签: String Pool, Heap, new String)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965e90cfa809e6d38877faa | 官方: 是 | 付费: 否
答案:
答案不一样,因为内存(memory)的分配方式不一样。String str="i"的方式,java 虚拟机会将其分配到常量池(constant pool)中;而 String str=new String("i") 则会被分到堆内存(heap memory)中。
20. 如何将字符串(String)反转(reverse)?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: Reverse String, StringBuilder, StringBuffer)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965e90dfa809e6d38878089 | 官方: 是 | 付费: 否
答案:
答案使用 StringBuilder 或者 stringBuffer 的 reverse() 方法(method)。
示例代码(example code):
// StringBuffer reverse
// StringBuffer 反转
StringBuffer stringBuffer = new StringBuffer();
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("abcdefg");
stringBuffer.append("abcdefg");
System.out.println(stringBuffer.reverse()); // gfedcba
System.out.println(stringBuffer.reverse()); // gfedcba
// StringBuilder reverse
// StringBuilder 反转
StringBuilder stringBuilder = new StringBuilder();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("abcdefg");
stringBuilder.append("abcdefg");
System.out.println(stringBuilder.reverse()); // gfedcba
System.out.println(stringBuilder.reverse()); // gfedcba
21. String(字符串)在 Java(爪哇)中是数据类型(data type)吗?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: String, Primitive vs Object)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965f3d9fa809e6d3888babf | 官方: 是 | 付费: 否
答案:
答案String(字符串)不是 Java(爪哇)的原始(primitive)数据类型(data type)。Java(爪哇)中创建字符串(String)时,实际上创建的是 java.lang.String(爪哇语言字符串类)类的对象(object)。创建了 String(字符串)对象后,可以使用 String(字符串)类的所有内置方法(built-in method)。
22. Stack(栈)和 Queue(队列)的区别是什么?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: Stack, Queue, LIFO, FIFO)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965f594fa809e6d3888f873 | 官方: 是 | 付费: 否
答案:
答案Stack(栈)和 Queue(队列)都用于存放数据集合(data collection)。主要区别是:Stack(栈)基于后进先出(LIFO,Last-In-First-Out)原则,而 Queue(队列)基于先进先出(FIFO,First-In-First-Out)原则。
23. 对象(object)被垃圾回收(garbage collection)后还能重新引用(reference)并使用吗?如何实现?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: Garbage Collection, Heap, Object Lifecycle)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965f597fa809e6d3888fd33 | 官方: 是 | 付费: 否
答案:
答案不可能。一旦对象(object)被垃圾回收器(garbage collector)销毁,它就不再存在于堆内存(heap memory)中,无法再次访问,也没有办法重新引用(reference)它。
24. Java(爪哇)中对象(object)是如何存储的?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: Heap, Object Storage)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965f736fa809e6d388920ed | 官方: 是 | 付费: 否
答案:
答案在 Java(爪哇)中,对象(object)创建时会在堆(heap)内存中分配空间。当对象(object)被垃圾回收器(garbage collector)销毁后,该内存空间会重新回到堆(heap)中,供新的对象(object)使用。
25. 以下两个类(class),哪个会分配更多内存(memory)?为什么?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: Heap, Class Loading)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965f737fa809e6d388922de | 官方: 是 | 付费: 否
答案:
答案在未创建对象(object)之前,不会在堆(heap)上为类(class)分配内存(memory)。由于两个类(class)都没有创建对象(object),因此堆内存(heap memory)中不会为任何一个类(class)分配内存(memory)。
26. 数组(array)声明后还能改变大小吗?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: Array, Vector)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965f73afa809e6d388925d7 | 官方: 是 | 付费: 否
答案:
答案数组(array)是静态的(static),一旦指定大小就无法改变。如果需要可变大小的集合(collection),应优先使用 Vector(向量类)等集合类(collection class)。
27. String(字符串)和 StringBuffer(字符串缓冲区类)可以直接比较吗?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: String, StringBuffer)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6965f73bfa809e6d388926e2 | 官方: 是 | 付费: 否
答案:
答案虽然 String(字符串)和 StringBuffer(字符串缓冲区类)都表示字符串(string)对象(object),但不能直接将它们进行比较,否则会报错。
28. 数组(Array)和数组列表(ArrayList)有什么区别?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: Array, ArrayList, Generics)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 69660512fa809e6d388b2e75 | 官方: 是 | 付费: 否
答案:
答案Array(数组)ArrayList(数组列表)声明数组时必须指定大小。
String[] name = new String[2]不一定需要指定大小,会动态改变大小。
ArrayList name = new ArrayList向数组放入对象时需要指定索引。
name[1] = “book”无需索引。
name.add(“book”)Array(数组) 不是类型参数化的Java 5.0 以后 ArrayList(数组列表) 支持参数化(泛型(Generics))。
例如:尖括号表示 String(字符串) 列表
29. 集合框架(Collection Framework)中有哪些接口(Interfaces)和类(Classes)?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: Interfaces, Classes, List, Set, Map, Queue)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 69660513fa809e6d388b2fc9 | 官方: 是 | 付费: 否
答案:
答案集合中的接口(Interfaces):
- Collection
- List
- Set
- Map
- Sorted Set
- Sorted Map
- Queue
集合中的类(Classes): - Lists:Array List、Vector、Linked List
- Sets:Hash set、Linked Hash Set、Tree Set
- Maps:Hash Map、Hash Table、Tree Map、Linked Hashed Map
- Queue:Priority Queue
30. 请解释 Priority Queue(优先队列)。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: Queue, PriorityQueue)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 69660860fa809e6d388bce7b | 官方: 是 | 付费: 否
答案:
答案Queue Interface(队列接口)
Priority Queue(优先队列):LinkedList(链表) 类被增强以实现 Queue(队列) 接口。队列可以用 LinkedList 来处理。队列的目的就是“Priority-in, Priority-out”。
因此,元素要么按自然顺序排序,要么根据 comparator(比较器)排序。元素的排序代表它们的相对优先级。
31. String(字符串) 属于基础的数据类型吗?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: String, 基本类型)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 69672608fa809e6d38a208fb | 官方: 是 | 付费: 否
答案:
答案
String(字符串) 不是基本数据类型,它是一个类(引用类型(Reference Type))。
Java 的基本数据类型(Primitive Data Types)只有 8 种:byte、short、int、long、float、double、char、boolean。
32. Java 中操作字符串都有哪些类?它们之间有什么区别?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: String, StringBuffer, StringBuilder)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 69672609fa809e6d38a20928 | 官方: 是 | 付费: 否
答案:
答案
- String:字符串常量,创建之后不可变(immutable)。String 类被 final 修饰,不可被继承。
- StringBuffer:字符串变量(mutable),线程安全(方法通常带有 synchronized)。
- StringBuilder:字符串变量(mutable),线程不安全,但性能通常比 StringBuffer 更高。
33. String str = "i"; 与 String str = new String("i"); 一样吗?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: String, 常量池)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 69672609fa809e6d38a2092c | 官方: 是 | 付费: 否
答案:
答案
不一样。
- String str = "i";:会先去字符串常量池中查找是否已经存在 "i",如果存在则直接返回常量池中的引用;如果不存在则在常量池中创建。
- String str = new String("i");:会在堆中创建一个新的 String 对象;同时字面量 "i" 仍会出现在常量池中(若之前不存在则创建)。
因此两者在引用地址(Reference Equality,==)上可能不同,但在内容比较(Content Equality,equals)上可以相同。
34. HashMap 和 Hashtable 的区别?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, collections;标签: HashMap, Hashtable)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6967260efa809e6d38a20ee4 | 官方: 是 | 付费: 否
答案:
答案
- HashMap 可以接受 null 作为 key 和 value;Hashtable 不允许。
- HashMap 是非 synchronized 的;Hashtable 是 synchronized 的。
- Hashtable 默认的初始大小为 11,之后每次扩充为原来的 2n+1;HashMap 默认的初始大小为 16,之后每次扩充为原来的 2 倍。
35. 如何将数组(Array)和 List 相互转换?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, collections;标签: Arrays.asList, toArray)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6967260efa809e6d38a20f00 | 官方: 是 | 付费: 否
答案:
答案
- 数组转 List:使用 Arrays.asList()。
- List 转数组:使用 toArray()。
注意:Arrays.asList() 返回的 List 是一个定长 List,不能进行 add/remove 等改变长度的操作。
36. 栈(Stack)和队列(Queue)有什么区别?分别适合什么场景?
- 知识点: 算法与数据结构 (主题: data-structures;标签: stack, queue, data-structures)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f113f120fcc159115928d | 官方: 是 | 付费: 否
答案:
答案栈是 LIFO(Last-In-First-Out),适合调用栈(Call Stack)、撤销(Undo)、解析(Parsing)与 DFS(Depth-First Search);队列是 FIFO(First-In-First-Out),适合任务排队(Task Queueing)、缓冲(Buffering)、消息队列(Message Queue)与 BFS(Breadth-First Search)。常规实现下 push/pop、enqueue/dequeue 都可 O(1)。
37. 材料里建议的备考时间分配是什么?为什么要这样分配?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 (主题: prep, interview;标签: prep-split, star-method, system-design)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f1220120fcc159115a5c2 | 官方: 是 | 付费: 否
答案:
答案材料建议把备考重心放在:编码/算法(Coding/Algorithms)约 60%(覆盖常见数据结构与算法套路)、系统设计(System Design)约 25%(特别是 L4/L5+ 的可扩展与可靠性权衡)、行为面(Behavioral Interview)约 25%(用 STAR 讲清影响与 Googleyness)。这样分配是因为流程里 coding 轮数最多、淘汰最强;系统设计决定中高职级上限;行为面决定是否能协作与长期交付。
38. 示例:输入 nums=[1] 时如何确定 N 与输出?为什么输出是 [2,3]?
- 知识点: 算法与数据结构 (主题: algorithms;标签: example, edge case)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f19cc120fcc15911672cf | 官方: 是 | 付费: 否
答案:
答案nums 长度为 1,表示 N-2 = 1,因此 N = 3。
完整集合应为 {1,2,3},数组里只有 1,所以缺失的是 2 和 3。
三种方法都会得到同样结果:数学法(Mathematical Method)A=5-1=4,B=14-1=13 -> 解得 2、3;异或法(XOR) (1^2^3)^(1)=2^3;原地哈希(In-place Hashing)最终发现索引 1、2 不匹配。
39. Amazon SDE coding interview 最常见的题型分类和大致占比是什么?
- 知识点: 算法与数据结构 (主题: amazon, interview, coding, data-structures;标签: Question Frequency, Prep Strategy)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f228f120fcc159117dd3d | 官方: 是 | 付费: 否
答案:
答案根据数据统计,题型最常见的是 Graphs/Trees (约46%),其次是 Arrays/Strings (约38%),然后是 Linked Lists (约10%);Search/Sort、Stacks & Queues 各约2%,Hash tables 约2%。准备时先把高频题型刷透,再补低频题型更高效。
40. 为什么要按题型频率做准备,而不是随机刷题?
- 知识点: 算法与数据结构 (主题: amazon, interview, prep, patterns;标签: Prioritization, Leetcode Strategy)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f2293120fcc159117e012 | 官方: 是 | 付费: 否
答案:
答案Amazon 的 coding 面试覆盖面广,但高频题型重复出现的概率更大。按频率准备能更快建立稳定的解题模板(如DFS(Depth-First Search)/BFS(Breadth-First Search)、二分(Binary Search)、双指针(Two Pointers)、滑窗(Sliding Window)、链表操作(Linked List Operations)),并在有限时间里最大化命中率。低频题型不必忽略,但建议放在高频题型熟练之后系统补齐。
41. Amazon coding 面试中你需要展示的核心能力是什么?
- 知识点: 算法与数据结构 / 行为与软技能 (主题: amazon, interview, coding, problem-solving;标签: Structured Thinking, Complexity)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f2293120fcc159117e015 | 官方: 是 | 付费: 否
答案:
答案重点不是背答案,而是展示结构化思考与工程化实现:先澄清边界与复杂度目标,再选合适的数据结构(Data Structure)/算法(Algorithm),写出正确、可读、少 bug 的代码,并能解释时间复杂度(Time Complexity)与空间复杂度(Space Complexity)。必要时给出优化(剪枝(Pruning)、缓存(Caching)、迭代替代递归(Iteration over Recursion)等)以及测试用例覆盖(Test Case Coverage)。
42. 什么是数据结构?有哪些类型?
- 知识点: 算法与数据结构 (主题: data-structures;标签: basics)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f24f3120fcc1591184265 | 官方: 是 | 付费: 否
答案:
答案数据结构是组织与存储数据的方式,目标是让访问、插入、删除、查找等操作更高效、更可维护。
- 线性结构:元素按顺序排列,如数组、链表、栈、队列。
- 非线性结构:元素不是单线顺序,如树、图、堆等。
43. 什么是链表?有哪些类型?
- 知识点: 算法与数据结构 (主题: linked-list;标签: basics)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f24f7120fcc15911844bb | 官方: 是 | 付费: 否
答案:
答案链表(Linked List)是由节点组成的线性结构,每个节点包含数据与指向下一节点的引用,插入/删除通常比数组更灵活。
- 单向链表:每个节点只指向 next,尾节点 next 为 null。
- 双向链表:同时有 prev 与 next,便于双向遍历与删除。
- 循环链表:尾节点指回头节点(可单向/双向),没有 null 结尾。
44. 什么是栈?常见应用场景有哪些?
- 知识点: 算法与数据结构 (主题: stack;标签: basics, applications)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f24fa120fcc159118474f | 官方: 是 | 付费: 否
答案:
答案栈(Stack)是一种遵循 LIFO(后进先出,Last In First Out) 的线性结构,只在栈顶进行入栈 push 与出栈 pop。
常见用途:函数调用栈(Function Call Stack)、括号匹配与表达式求值、回溯/DFS、撤销/重做、浏览器前进后退等。
45. 什么是队列?常见应用场景有哪些?
- 知识点: 算法与数据结构 (主题: queue;标签: basics, applications)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f24fd120fcc15911849c0 | 官方: 是 | 付费: 否
答案:
答案队列(Queue)是一种遵循 FIFO(先进先出,First In First Out) 的线性结构,从队尾入队 enqueue、从队头出队 dequeue。
常见用途:任务调度与消息队列(Message Queue)、打印/IO 缓冲、事件循环、BFS 图遍历、生产者-消费者模型(Producer-Consumer Model)等。
46. 什么是二分查找?它的时间复杂度是多少?
- 知识点: 算法与数据结构 (主题: binary-search;标签: basics)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f24ff120fcc1591184c18 | 官方: 是 | 付费: 否
答案:
答案二分查找(Binary Search)用于在有序数组/序列中定位目标值:每次取中点比较,若目标更小则缩到左半区,否则缩到右半区,直到找到或区间为空。
每轮区间减半,因此时间复杂度为 O(log n),空间复杂度通常为 O(1)(迭代实现)。
47. 用 Java 判断字符串是否为回文(Palindrome)。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, string;标签: palindrome)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f2500120fcc1591184cd5 | 官方: 是 | 付费: 否
答案:
答案回文从左右读相同。可用双指针(Two Pointers)比较两端字符,时间 O(n)、空间 O(1)。若需忽略大小写/非字母数字,可先清洗字符串。
static boolean isPalindrome(String s){
static boolean isPalindrome(String s){
int l = 0, r = s.length() - 1;
int l = 0, r = s.length() - 1;
while (l < r) {
while (l < r) {
if (s.charAt(l) != s.charAt(r)) return false;
if (s.charAt(l) != s.charAt(r)) return false;
l++; r--;
l++; r--;
}
return true;
返回 true;
}
48. 编写程序:在包含 N 个数字的有序数组上执行二分搜索(Binary Search)。
- 知识点: 算法与数据结构 (主题: binary-search, algorithms, array;标签: binary search, iteration)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f2cc0120fcc1591199a50 | 官方: 是 | 付费: 否
答案:
答案二分搜索要求数组已排序。用两个指针 l/r 维护搜索区间,每次取中点 mid 比较目标值:相等返回索引;目标更小则收缩右边界,否则收缩左边界,直到区间为空。时间复杂度(Time Complexity)O(log N),空间复杂度(Space Complexity)迭代版为 O(1)。
// Java (iterative)
// Java (迭代)
int binarySearch(int[] a, int target){
int binarySearch(int[] a, int target){
int l=0, r=a.length-1;
int l=0, r=a.length-1;
while(l<=r){
while(l<=r){
int mid = l + (r-l)/2;
int mid = l + (r-l)/2;
if(a[mid]==target) return mid;
if(a[mid]==target) return mid;
if(a[mid]>target) r = mid-1; else l = mid+1;
if(a[mid]>target) r = mid-1; else l = mid+1;
}
return -1;
return -1;
}
49. 线性数据结构(Linear Data Structure)和非线性数据结构(Non-linear Data Structure)有什么区别?分别举例。
- 知识点: 算法与数据结构 (主题: data-structures;标签: DSA, Basics)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f345a120fcc15911a6e26 | 官方: 是 | 付费: 否
答案:
答案线性数据结构的数据元素按顺序排列,通常有唯一的前驱/后继关系,遍历更像“一条线”;典型例子:数组(Array)、链表(Linked List)、栈(Stack)、队列(Queue)。非线性数据结构的元素关系是层级或网状,一个节点可能连接多个节点;典型例子:树(Tree)、堆(Heap)、图(Graph)。实际选择取决于访问/插入/删除复杂度与业务关系建模方式。
50. 面试出现“颜色代码问题”时,可能在考什么?你会怎么处理?
- 知识点: 算法与数据结构 / 行为与软技能 (主题: problem-solving;标签: Clarification, Color Code)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 696f3462120fcc15911a7a11 | 官方: 是 | 付费: 否
答案:
答案“颜色代码”常见两类:电子/电阻色环(颜色对应数字、倍率与误差)或Web 颜色值(如 #RRGGBB / RGB / HSL)。最稳的做法是先澄清语境:请面试官确认是电阻色环还是网页颜色编码;再给出对应解释与例子。面试官通常更看重你“先问清问题再解题”的思维习惯。
51. 什么是数组(Array)?数组在现实中的应用有哪些?
- 知识点: 算法与数据结构 (主题: data-structures;标签: Array)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- id: 696f4e76120fcc15911fbaf1 | 官方: 是 | 付费: 否
答案:
An array is a collection of items stored in contiguous memory locations, typically of the same type, enabling O(1) index access via base address + offset.
数组是存储在连续内存位置中的项目集合,通常具有相同类型,通过基地址加偏移量实现O(1)索引访问。
Real-life applications include: tabular data (e.g., contacts list), game leaderboards, numbered question papers with marks, 2D arrays in image processing, and representing signals in speech recognition.
实际应用包括:表格数据(如联系人列表)、游戏排行榜、带分数的编号试卷、图像处理中的二维数组,以及语音识别中表示信号。
52. 编写程序将字符串中字符大小写互换(小写转大写,大写转小写)。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: cpp;标签: String)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- id: 696f4e82120fcc15911fcb7e | 官方: 是 | 付费: 否
答案:
Method:
方法:
Traverse the string. If a character is lowercase, subtract 32 to convert to uppercase; if uppercase, add 32 to convert to lowercase.
遍历字符串。如果字符是小写,减去 32 转换为大写;如果是大写,加上 32 转换为小写。
Example: "siMPlilEArn" => "SImpLILeaRN"
示例:"siMPlilEArn" => "SImpLILeaRN"
Code:
代码:
include
using namespace std;
using namespace std;
void caseChange(string& str){
void caseChange(string& str){
int len=str.length();
int len=str.length();
for(int i=0;i='a' && str[i]='A' && str[i]<='Z') str[i]=str[i]+32;
for(int i=0;i='a' && str[i]='A' && str[i]<='Z') str[i]=str[i]+32;
}
}
int main(){ string str="siMPlilEArn"; cout<<"The Original String is : "<<str<<"
int main(){ string str="siMPlilEArn"; cout<<"The Original String is : "<<str<<"
"; caseChange(str); cout<<"The Changed String is : "<<str<<"
"; caseChange(str); cout<<"The Changed String is : "<<str<<"
"; return 0; }
"; return 0; }
53. 请写伪代码:遍历一个序列,能被 3 整除输出一个单词,能被 5 整除输出另一个单词,同时满足则输出两个单词。
- 知识点: 算法与数据结构 (主题: algorithms;标签: Pseudocode, FizzBuzz)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- 公司: Carsales
- id: 6970454b120fcc1591309332 | 官方: 是 | 付费: 否
答案:
答案这是典型的 FizzBuzz。关键点是先判断同时满足(15),避免重复打印。时间复杂度(Time Complexity)O(N),空间复杂度(Space Complexity)O(1)。
伪代码(FizzBuzz)for i from 1 to N:
if i % 15 == 0:
if i % 15 == 0:
print("FizzBuzz")
print("FizzBuzz")
else if i % 3 == 0:
else if i % 3 == 0:
print("Fizz")
print("Fizz")
else if i % 5 == 0:
否则如果 i % 5 == 0:
print("Buzz")
print("Buzz")
else:
否则:
print(i)
print(i)
54. 编写一个函数来判断一个字符串是否是回文字符串。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: python, algorithms;标签: palindrome, two-pointers)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- 公司: Telstra
- id: 69709b51120fcc15913a53e9 | 官方: 是 | 付费: 否
答案:
思路- 双指针(Two Pointers)从两端向中间移动,遇到不相等立即返回False
- 如果题目要求忽略大小写/非字母数字,先做规范化处理
时间复杂度O(n),空间复杂度O(1)(双指针)
示例代码(Python)def is_palindrome(s: str) -> bool:Normalize if needed: s = ''.join(ch.lower() for ch in s if ch.isalnum())
return s == s[::-1]
return s == s[::-1]
55. 实现一个函数来合并两个排序数组(Sorted Array)。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: python, algorithms;标签: merge, two-pointers)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- 公司: Telstra
- id: 69709b55120fcc15913a5724 | 官方: 是 | 付费: 否
答案:
思路- 使用双指针(two pointers)分别遍历两个数组
- 每次取较小元素放入结果并移动指针
时间复杂度O(n+m),空间复杂度O(n+m)(输出数组)
示例代码(Python)def merge_sorted_arrays(a, b):
i = j = 0i = j = 0
out = []
out = []
while i < len(a) and j < len(b):
当 i < len(a) 且 j < len(b) 时:
if a[i] <= b[j]:
如果 a[i] <= b[j]:
out.append(a[i]); i += 1
out.append(a[i]); i += 1
else:
否则:
out.append(b[j]); j += 1
out.append(b[j]); j += 1
out.extend(a[i:])
out.extend(a[i:])
out.extend(b[j:])
out.extend(b[j:])
return out
return out
56. Confirm skill stacks(技术栈)and experience related to Resume(简历)(确认简历技术栈与经验)。
- 知识点: 算法与数据结构 / 行为与软技能 (标签: resume, skill-stack)
- 类型: behavioral | 难度: easy | 子类型:
- 分类: general
- id: 6970a2d4120fcc15913b16ed | 官方: 是 | 付费: 否
答案:
答案对照 JD(Job Description)与简历关键词,挑 2-3 个最核心技术栈(Tech Stack)(如 React/Redux/Testing),用项目证据回答:我如何用它解决了什么问题、产出什么结果,证明“确实做过”,不要只背概念。
57. 什么是递归(Recursion)?为什么它在算法中很有用?
- 知识点: 算法与数据结构 (主题: algorithms, recursion;标签: Recursion, Base Case, Divide and Conquer)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 69772669a39c9c5c3a8a064c | 官方: 是 | 付费: 否
答案:
答案递归(Recursion)是函数在解决问题时调用自身,把大问题拆成更小的同类子问题,并通过“基线条件”(base case)终止递归。它在分治类算法(归并排序(merge sort)、快速排序(quick sort))、树/图遍历(tree/graph traversal)、回溯搜索(backtracking)等场景很有用,能让代码更直观。但递归也可能带来栈深限制(stack depth limit)与额外开销,需要注意基线条件、重复计算(可用记忆化(memoization)/DP(dynamic programming))与尾递归优化(tail recursion optimization)(部分语言支持)。
58. 解释算法的时间复杂度(time complexity),并给出常见时间复杂度的示例。
- 知识点: 算法与数据结构 (主题: algorithms, complexity;标签: Big-O, Time Complexity, Performance)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 69772678a39c9c5c3a8a0af7 | 官方: 是 | 付费: 否
答案:
答案时间复杂度用大 O(Big O notation)表示算法运行时间随输入规模 n 增长的趋势,用于评估性能上界并对比算法。常见示例:O(1) 常数时间(constant time)(数组按下标访问);O(log n) 对数时间(logarithmic time)(二分查找(binary search));O(n) 线性时间(linear time)(遍历数组);O(n log n)(归并/堆排序(heap sort));O(n^2)(双重循环、冒泡排序(bubble sort));O(2^n)/O(n!)(指数/阶乘(exponential/factorial),常见于暴力枚举(brute-force enumeration))。实际分析通常关注最坏/平均情况与主导项。
59. 解释链表(linked list)的概念,并比较单链表(singly linked list)和双链表(doubly linked list)。
- 知识点: 算法与数据结构 (主题: data-structures, linked-list;标签: Linked List, Singly, Doubly)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6977267ca39c9c5c3a8a0e5a | 官方: 是 | 付费: 否
答案:
答案链表(linked list)是一种线性数据结构,由节点(node)组成,每个节点保存数据与指针(pointer)(引用),通过指针把节点串起来。单链表(singly linked list)每个节点只指向下一个节点,结构更省内存、实现更简单,但无法高效反向遍历;双链表(doubly linked list)每个节点同时指向前驱(predecessor)和后继(successor),支持双向遍历与更方便的删除操作(已定位节点时),代价是额外指针带来更多内存开销与维护复杂度。两者随机访问都不是 O(1),通常为 O(n)。
60. 编写一个函数,将两个排序数组合并为一个排序数组。
- 知识点: 算法与数据结构 (主题: algorithms, arrays;标签: Two Pointers, Merge, Sorted Arrays)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 69772fc1a39c9c5c3a8bf1c4 | 官方: 是 | 付费: 否
答案:
答案典型做法是“双指针归并”(merge with two pointers):分别用 i、j 指向两个数组头部,每次把较小元素追加到结果并移动对应指针;当某一数组耗尽后,把另一数组剩余部分直接追加。时间复杂度 O(n+m),空间复杂度 O(n+m)(若允许原地合并(in-place merge)则可进一步优化,取决于语言与输入约束)。
61. 编写一个函数来反转给定字符串中单词的顺序。
- 知识点: 算法与数据结构 (主题: algorithms, strings;标签: String, Reverse, Words)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 69772fc6a39c9c5c3a8bf8de | 官方: 是 | 付费: 否
答案:
答案思路是按空白分割成单词数组(注意处理多空格与标点),再将数组反转并用单个空格连接。若要求原地(in-place)或 O(1) 额外空间,可先整体反转字符串,再逐个反转每个单词以恢复单词内部顺序。面试中建议先确认输入规则:是否保留多空格、是否含换行与标点。
62. 解释冒泡排序(bubble sort)和插入排序(insertion sort)。
- 知识点: 算法与数据结构 (主题: algorithms, sorting;标签: Bubble Sort, Insertion Sort, Complexity)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 6977327aa39c9c5c3a8d618a | 官方: 是 | 付费: 否
答案:
答案冒泡排序(bubble sort)通过不断比较相邻元素并交换,让最大(或最小)元素逐轮“冒泡”到正确位置,平均/最坏时间复杂度 O(n²),实现简单但效率低;插入排序(insertion sort)像整理扑克牌,把当前元素插入到前面已排序序列的合适位置,最坏 O(n²),但在数据基本有序或数据量小的情况下表现很好,且是稳定排序(stable sort)、空间开销小。
63. 定义:列表(List)与元组(Tuple)。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: python, data-structures;标签: List, Tuple, Mutability)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 69773802a39c9c5c3a8e14ba | 官方: 是 | 付费: 否
答案:
答案列表(List)是可变(mutable)、有序的元素集合,用 [] 表示,支持增删改、切片与排序,适合需要频繁更新的数据;元组(Tuple)是不可变(immutable)、有序集合,用 () 表示(或省略括号),创建后元素不可修改,适合表示固定结构数据或作为字典键(dictionary key)。两者都可包含混合类型与嵌套结构,但在语义上 list 更“可编辑”,tuple 更“定型”。
64. 编写一个 Java(Java)程序来生成阶乘数。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, algorithms;标签: Factorial, Loop, BigInteger)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 69773804a39c9c5c3a8e15d6 | 官方: 是 | 付费: 否
答案:
答案阶乘 n! 可用循环或递归计算。面试中建议说明边界(0! = 1)与溢出风险(int(int)很快溢出,使用 long(long)或 BigInteger(BigInteger))。实现思路:读取 n,初始化结果为 1,从 2 循环乘到 n 输出结果。若 n 较大可改用 BigInteger(BigInteger)并在循环中 multiply(multiply),以保证正确性与鲁棒性。
65. 什么是栈(Stack)?
- 知识点: 算法与数据结构 (主题: data-structures;标签: stack, lifo)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 697825c0a39c9c5c3ab58c53 | 官方: 是 | 付费: 否
答案:
答案栈(Stack)是一种遵循 LIFO(后进先出)的线性数据结构(linear data structure),插入与删除都发生在同一端(栈顶 top)。常见操作是 push/pop/peek(push/pop/peek)。栈常用于函数调用栈、表达式求值、括号匹配、DFS(DFS)等场景。
66. 什么是树(Tree)数据结构(data structure)?
- 知识点: 算法与数据结构 (主题: data-structures, trees;标签: tree)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 697825c0a39c9c5c3ab58c9a | 官方: 是 | 付费: 否
答案:
答案树(Tree)是一种分层的非线性数据结构(non-linear data structure),由节点与边组成,有一个根节点(root),其余节点是根的子节点(children),并可继续形成子树。树常用于表示层级关系(文件系统、组织结构)、索引结构(B-Tree(B-Tree))、以及解析语法结构等。
67. 什么是选择排序(Selection Sort)?
- 知识点: 算法与数据结构 (主题: algorithms, sorting;标签: selection-sort)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 697825c7a39c9c5c3ab593a1 | 官方: 是 | 付费: 否
答案:
答案选择排序(Selection Sort)每一轮从未排序区间中选出最小(或最大)元素,放到已排序区间的末尾(或开头),重复直到排序完成。它的比较次数较固定,时间复杂度(time complexity)通常为 O(n²),空间复杂度(space complexity)O(1),但稳定性通常不保证(取决于实现)。
68. 选择排序(Selection Sort)有哪些优点?
- 知识点: 算法与数据结构 (主题: algorithms, sorting;标签: selection-sort)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 697825cca39c9c5c3ab59924 | 官方: 是 | 付费: 否
答案:
答案选择排序(Selection Sort)的优点主要体现在实现与交换次数方面:逻辑简单、实现容易;每轮最多一次交换,总交换次数为 O(n),在交换代价很高的场景可能有优势;同时它原地排序,额外空间 O(1)。但总体时间复杂度(time complexity)O(n²),更适合小规模数据。
- 实现简单,易于理解
- 交换次数少(每轮至多一次)
- 原地排序,额外空间 O(1)
- 适合小数据集或交换代价高的场景
69. 树(Tree)数据结构(data structure)有哪些应用场景?
- 知识点: 算法与数据结构 (主题: data-structures, trees;标签: tree, applications)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 697825d1a39c9c5c3ab59e05 | 官方: 是 | 付费: 否
答案:
答案树结构常用于表达层级关系与高效检索。典型应用包括:符号表/索引结构(如 BST(BST)、B-Tree(B-Tree)/Trie(Trie))、算术表达式树与编译器语法分析(AST(AST)/Parse Tree(Parse Tree))、文件系统目录树、组织结构与权限层级、UI 组件树等。
- 符号表/索引(BST、B-Tree、Trie)
- 算术表达式与语法树(AST)
- 层级数据模型(目录、组织架构)
- 解析与编译(Syntax analysis)
70. BFS(Breadth-First Search)和 DFS(Depth-First Search)分别使用哪些数据结构(data structure)?
- 知识点: 算法与数据结构 (主题: algorithms, graphs;标签: bfs, dfs)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 697825d1a39c9c5c3ab59e08 | 官方: 是 | 付费: 否
答案:
答案BFS(广度优先搜索)按层访问节点,典型实现使用队列(Queue(Queue))维护待访问节点;DFS(深度优先搜索)尽可能深入探索,典型实现使用栈(Stack(Stack))或递归调用栈。
- BFS:Queue(队列)
- DFS:Stack(栈)或递归
71. 什么是线性数据结构(Linear Data Structure)?
- 知识点: 算法与数据结构 (主题: data-structures;标签: linear-data-structure)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 697825d1a39c9c5c3ab59e12 | 官方: 是 | 付费: 否
答案:
答案线性数据结构(linear data structure)指数据元素按顺序排列,每个元素(除首尾)都有唯一前驱与后继,逻辑结构呈“一条线”。常见例子有数组(array)、链表(linked list)、栈(stack)、队列(queue)、线性表等。它们实现与遍历相对简单,但在插入删除与随机访问上的性能各有差异。
- 例子:Array、Linked List、Stack、Queue
72. Java 中如何 Split(分割)字符串?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: string, split)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 697825d1a39c9c5c3ab59e18 | 官方: 是 | 付费: 否
答案:
答案Java 中可用 String.split(regex, limit) 按正则(Regular Expression)切分字符串。示例把 "Simplilearn" 按字母 'e' 切分,并限制最多切成 2 段。注意 split 的第一个参数是正则表达式(Regular Expression),特殊字符(Special Character)需要转义(Escape)。
public class Simpli {
public class Simpli {
public static void main(String args[]) {
public static void main(String args[]) {
// Define a string to split
// 定义一个要拆分的字符串
String str = "Simplilearn";
String str = "Simplilearn";
// Split the string at the letter 'e', and limit the split to 2 parts
// 在字母 'e' 处拆分字符串,并将拆分限制为 2 部分
String[] arrOfStr = str.split("e", 2);
String[] arrOfStr = str.split("e", 2);
// Print the resulting substrings after split
// 分割后打印生成的子字符串
for (String a : arrOfStr)
for (String a : arrOfStr)
System.out.println(a);
System.out.println(a);
}
}
73. Python 中的 docstring(文档字符串)是什么?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: python;标签: docstring)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 697825d6a39c9c5c3ab5a2dd | 官方: 是 | 付费: 否
答案:
答案docstring(文档字符串)是放在模块(Module)、类(Class)、函数(Function)或方法(Method)定义体开头的字符串字面量(String Literal),用于描述其用途、参数、返回值与用法。它会被保存到 doc 属性中,便于 help()、Sphinx 等工具生成文档。推荐使用三引号(Triple Quotes),并遵循 Google/NumPy 风格注释规范。
74. TikTok 对 SWE(软件工程师)的典型岗位要求有哪些(教育背景、经验年限、能力侧重点)?
- 知识点: 算法与数据结构 / UI/UX 设计 / 行为与软技能 (主题: data-structures, algorithms, software-design, agile;标签: tiktok, requirements, resume)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 697887f9a39c9c5c3ad694fb | 官方: 是 | 付费: 否
答案:
答案TikTok 通常更看重“经验与技能”而非学历门槛:多数岗位接受本科或更灵活的教育背景,但偏好计算机或相关技术背景。经验方面多为 2–5 年以上(资深岗位更高),并鼓励展示团队协作与领导经历;新毕业生也可用社团/项目中的协作与负责人经历加分。能力上强调计算机基础(Computer Science Fundamentals)(算法、数据结构、设计)、工程落地能力(编码、调试、优化)、以及在敏捷环境(Agile Environment)中与跨团队协作推进项目的能力。
75. 申请 TikTok SWE 前,通常有哪些高性价比的准备建议(了解公司、技术练习、全球协作等)?
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms, communication;标签: tiktok, prep, interview)
- 类型: technical | 难度: easy | 子类型:
- 分类: fullstack
- id: 697887f9a39c9c5c3ad69508 | 官方: 是 | 付费: 否
答案:
答案准备建议通常分三块:第一,了解 TikTok——熟悉使命“inspire creativity and bring joy”、关注官方新闻动态,并了解 TikTok for Good、TikTok for Developers 等项目,面试时能用具体例子表达兴趣;第二,强化技术面——TikTok 编程考核重速度与准确,建议刷 LeetCode 风格 DS&A(数据结构与算法)题并训练讲解过程;第三,培养全球协作意识——团队跨时区协作普遍,愿意适应非传统工作时间、尊重多文化沟通会加分。
76. Merge the overlapping intervals of an array and return a new output array.
合并数组中重叠的区间,并返回一个新的输出数组。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: algorithms, sorting;标签: Intervals, Sorting, Apple SWE)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979dba7c8f1f94b64623de3 | 官方: 是 | 付费: 否
答案:
先按区间起点排序。维护当前区间 current(当前区间):若下一个区间起点 <= current 终点,则合并(合并区间)(更新终点为 max)。否则把 current 放入结果并切换到下一个。遍历结束补上最后一个 current 即可。
77. Merge two sorted linked lists so that the resulting linked list is also sorted.
合并两个已排序的链表,使结果链表也是有序的。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: linked-list, algorithms;标签: Linked List, Two Pointers, Apple SWE)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979dba7c8f1f94b64623deb | 官方: 是 | 付费: 否
答案:
双指针(Two Pointers)合并:用 dummy 头结点和 tail 指针;比较两条链表(Linked List)当前节点值,把较小者接到 tail 后并移动对应指针;其中一条结束后直接接上另一条剩余部分。时间 O(n+m)(时间复杂度),额外空间 O(1)(空间复杂度)。
78. Determine whether two binary trees are identical when you are given the roots of both.
给定两个二叉树的根节点,判断它们是否相同。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: trees, algorithms;标签: Binary Tree, DFS, Apple SWE)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979dba7c8f1f94b64623dee | 官方: 是 | 付费: 否
答案:
递归(Recursion)对比:两节点都为空则相同;一空一非空则不同;值不同则不同;否则继续比较左右子树(Subtree)是否都相同。这能同时保证结构一致与节点值一致。
79. How should you prepare for a software engineer role at Atlassian?
你应该如何准备 Atlassian 的软件工程师职位面试?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 行为与软技能 (主题: data-structures, algorithms, system-design;标签: Preparation, System Design, STAR)
- 类型: behavioral | 难度: easy | 子类型: scenario
- 分类: general
- 公司: Atlassian
- id: 6979de50c8f1f94b6462c77c | 官方: 是 | 付费: 否
答案:
按“技术+表达”两条线准备:DSA(Data Structures and Algorithms)重点练树(Tree)/堆(Heap)/图(Graph)等高频题型,写清晰可测试的代码;系统设计(System Design)模拟真实面试节奏,练通知服务(Notification Service)、限流器(Rate Limiter)等,能讲清规模、容错、一致性与监控取舍。行为面用 STAR(Situation, Task, Action, Result)准备价值观案例,特别体现“别坑客户”。面试中多问澄清问题,表达要结构化。
80. 反转一个链表(Linked List)。
- 知识点: 算法与数据结构 (主题: linked-list, algorithms;标签: google, real-question, prepfully)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872b89 | 官方: 是 | 付费: 是
答案:
题目来源Prepfully 报告,Google SWE Technical Phone Screen 真题。对应 LeetCode 206(Easy)。
思路分析经典链表操作题,考察指针操作基本功。
解题方法方法一:迭代(Iteration)使用三个指针 prev、curr、next,逐个反转指针方向。
- 时间复杂度:O(n)
- 空间复杂度:O(1)
方法二:递归(Recursion)递归到链表末尾,回溯时反转指针。 - 时间复杂度:O(n)
- 空间复杂度:O(n)(递归栈)
评分要点- 能否写出 bug-free 的迭代解法(iterative solution) - 能否讨论两种方法的优劣
- 边界情况:空链表、单节点链表
81. 给定两个字符串(string),判断其中一个是否是另一个的子序列(subsequence)。
- 知识点: 算法与数据结构 (主题: string, algorithms;标签: google, real-question, interviewquery)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872b8f | 官方: 是 | 付费: 是
答案:
题目来源InterviewQuery 报告,Google SWE Technical Phone Screen。对应 LeetCode 392。
思路分析双指针法(two-pointer technique):一个指针(pointer)遍历长字符串,一个指针遍历短字符串,匹配时短字符串指针前进。
解题方法双指针i 指向 s(子序列候选),j 指向 t(目标字符串)。遍历 t,每当 s[i] == t[j] 时 i++。最终 i == len(s) 则为子序列。
- 时间复杂度:O(n),n = len(t)
- 空间复杂度:O(1)
评分要点- 能否快速想到双指针 - Follow-up:如果有大量 s 需要判断,如何优化?(预处理 t 的字符位置 + 二分查找)
82. 打印给定字符串中第一个不重复的字符。
- 知识点: 算法与数据结构 (主题: string, hash-table;标签: google, real-question, prepfully)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872b92 | 官方: 是 | 付费: 是
答案:
题目来源Prepfully 报告,Google SWE Onsite Coding Round 真题。对应 LeetCode 387。
思路分析使用哈希表(hash table)记录每个字符出现次数,然后再遍历一次找第一个计数为1的字符。
解题方法哈希表 + 两次遍历(two-pass traversal)第一次遍历建立频率表(frequency table),第二次遍历找第一个频率为1的字符。
- 时间复杂度:O(n)
- 空间复杂度:O(1)(最多26个字母)
评分要点- 能否想到最优的 O(n) 解法 - 是否考虑字符集大小(ASCII vs Unicode)
- 代码是否简洁清晰
83. Logger Rate Limiter:设计一个日志速率限制器(rate limiter),同一条日志在10秒内不重复打印。
- 知识点: 算法与数据结构 (主题: hash-table, data-structures;标签: google, real-question, cnblogs)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872b9e | 官方: 是 | 付费: 是
答案:
题目来源cnblogs (博客园) 2025 Google 面经报告。对应 LeetCode 359,Easy。
思路分析使用 HashMap 存储每条消息的最后打印时间。
解题方法HashMapshouldPrintMessage(timestamp, message):如果 message 不在 map 中或 timestamp - map[message] >= 10,则打印并更新时间戳,返回 true。否则返回 false。
- 时间复杂度:O(1)
- 空间复杂度:O(消息数量)
评分要点- 解法是否简洁 - Follow-up:内存不足怎么办?(淘汰策略、滑动窗口)
84. Given a linked list, check whether the linked list has a loop in it or not.
给定一个链表,检查链表中是否存在环。
- 知识点: 算法与数据结构 (标签: interviewbit, accolite, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Accolite Digital
- id: 69b3791b58d557c902b973c8 | 官方: 否 | 付费: 否
答案:
Example:
示例:
Input:
输入:
1 -> 2 -> 3 -> 4 -> 5
Output:
输出:
No loop present.
不存在环。
Input:
输入:
1-> 2 -> 3 -> 4 A | | V 6 Output:
1-> 2 -> 3 -> 4 A | | V 6 输出:
Loop present. - Approach 1: Traverse the list one by one, adding node addresses to a Hash Table as you go. If NULL is reached at any time, return false; otherwise, return true if the next of the current nodes points to any of the previously recorded nodes in Hash.
存在环。 - 方法1:逐个遍历链表,将节点地址存入哈希表。如果任何时候到达NULL,则返回false;否则,如果当前节点的下一个指针指向哈希表中任何先前记录的节点,则返回true。
Solution Code:
// Node structure// 节点结构体
struct Node {
struct Node {
int data;
int data;
struct Node* next;
struct Node* next;
};
bool findLoop(struct Node* head)
bool findLoop(struct Node* head)
{
// Hashmap for flagging if a node has been visited
// 用于标记节点是否已被访问的哈希表
unordered_set<Node*> hash_map;
unordered_set<Node*> hash_map;
while (head != NULL) {
while (head != NULL) {
// If this node is already present in hashmap it means there is a cycle and so we return true
// 如果该节点已经存在于哈希表中,则说明存在环,因此我们返回true
if (hash_map.find(head) != hash_map.end())
if (hash_map.find(head) != hash_map.end())
return true;
返回 true;
// If we are seeing the node for the first time, we insert it in hash map
// 如果这是第一次看到该节点,我们将其插入哈希表
hash_map.insert(head);
hash_map.insert(head);
head = head->next;
head = head->next;
}
// We return false in case there is no loop in the given linked list
// 如果给定的链表中没有环,我们返回false
return false;
返回 false;
}
Time Complexity: O(n) Space Complexity: O(n)
时间复杂度:O(n) 空间复杂度:O(n)
Here, n is the number of nodes in the given linked list.
这里,n 是给定链表中的节点数量。
Explanation: In the above code, the function findLoop detects if a loop is present in a linked list or not. We maintain a hashmap of nodes and as we traverse through the linked list, we flag a node as visited. If we encounter a visited node again, it implies that a loop is present in the linked list and so we return true. - Approach 2: In this approach, we maintain two pointers: slow_pointer and fast_pointer. We initialize both of them with the head of the linked list. We iterate through the linked list until either the fast_pointer becomes NULL or the fast_pointer->next becomes NULL. In each iteration, we update the slow_pointer by moving it one step ahead in the linked list while we update the fast_pointer by moving it two steps ahead in the linked list. If at any point, the slow_pointer and the fast_pointer become equal, we return true implying that a cycle is indeed present in the linked list. This algorithm is also known as Floyd's Cycle finding algorithm.
解释:在上述代码中,函数findLoop用于检测链表中是否存在环。我们维护一个节点的哈希表,并在遍历链表时将节点标记为已访问。如果我们再次遇到已访问的节点,则意味着链表中存在环,因此我们返回true。 - 方法2:在该方法中,我们维护两个指针:慢指针和快指针。我们使用链表的头节点来初始化它们。我们遍历链表,直到快指针变为NULL或快指针的下一个节点变为NULL。在每次迭代中,我们通过将慢指针在链表中向前移动一步来更新它,同时通过将快指针在链表中向前移动两步来更新它。如果在任何时刻,慢指针和快指针变得相等,我们返回true,这意味着链表中确实存在环。该算法也被称为弗洛伊德环检测算法。
Solution Code:
// Node structure// 节点结构体
struct Node {
struct Node {
int data;
int data;
struct Node* next;
struct Node* next;
};
// Returns true if there is a loop in linked list
// 如果链表中存在环,则返回true
// else returns false.
// 否则返回 false。
bool findLoop(Node* head)
bool findLoop(Node* head)
{
Node slow_pointer = head, fast_pointer = head;
Node slow_pointer = head, fast_pointer = head;
while (fast_pointer && fast_pointer->next) {
while (fast_pointer && fast_pointer->next) {
slow_pointer = slow_pointer->next;
slow_pointer = slow_pointer->next;
fast_pointer = fast_pointer->next->next;
fast_pointer = fast_pointer->next->next;
if (slow_pointer == fast_pointer) {
if (slow_pointer == fast_pointer) {
return true;
返回 true;
}
}
return false;
返回 false;
}
Time Complexity: O(n) Space Complexity: O(1)
时间复杂度:O(n) 空间复杂度:O(1)
Explanation: In the above code, the function findLoop takes in the head of the linked list as an argument and returns true if a loop is present in the linked list else false. We maintain two pointers: slow_pointer and fast_pointer as discussed in the solution approach and keep iterating the linked list until either fast_pointer or fast_pointer->next becomes NULL. At any iteration, if the slow_pointer becomes equal to the fast_pointer, we return true.
解释:在上述代码中,函数 findLoop 以链表的头节点作为参数,如果链表中存在循环则返回 true,否则返回 false。我们维护两个指针:slow_pointer 和 fast_pointer,正如解决方案方法中所讨论的,并持续遍历链表,直到 fast_pointer 或 fast_pointer->next 变为 NULL。在任何一次迭代中,如果 slow_pointer 等于 fast_pointer,我们就返回 true。
85. Given an array of integers as input, find the sum of the contiguous subarray in the array such that its sum is the maximum of all the possible subarrays.
给定一个整数数组作为输入,找出数组中连续子数组的和,使其为所有可能子数组中的最大值。
- 知识点: 算法与数据结构 (标签: interviewbit, accolite, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Accolite Digital
- id: 69b3791b58d557c902b973e1 | 官方: 否 | 付费: 否
答案:
Example:
示例:
Input: Arr = {-2, -3, 4, -1, -2, 1, 5, -3}
输入:Arr = {-2, -3, 4, -1, -2, 1, 5, -3}
Output: 7
输出:7
Explanation: The largest contiguous subarray sum is formed by the subarray [4, -1, -2, 1, 5]
解释:最大的连续子数组和由子数组 [4, -1, -2, 1, 5] 形成
Approach 1: The very basic approach is to traverse through every possible subarray of the given array and to find the sum of each subarray. We then compare the obtained sum with our answer and update our answer if this sum is greater than the answer. The time complexity in this approach would be O(n^3) and the space complexity would be O(1). We will run a nested loop to consider all the subarrays. Now, inside the nested loop, we will run one more nested loop to find the sum of the elements of the subarray in consideration.
方法1:最基础的方法是遍历给定数组的所有可能子数组,并计算每个子数组的和。然后我们将得到的和与答案进行比较,如果该和大于答案,则更新答案。这种方法的时间复杂度为O(n^3),空间复杂度为O(1)。我们将运行嵌套循环来考虑所有子数组。现在,在嵌套循环内部,我们将再运行一个嵌套循环来计算所考虑子数组元素的和。
We can reduce the time complexity in this case to O(n^2) by maintaining a prefix sum array for the given array. This would help us to eliminate the third nested loop. However, doing so increases the space cost to O(n). We leave the implementation of these approaches for the readers since they are pretty straightforward. Let us now look at the most optimal solution.
在这种情况下,我们可以通过为给定数组维护一个前缀和数组来将时间复杂度降低到O(n^2)。这将帮助我们消除第三个嵌套循环。然而,这样做会将空间成本增加到O(n)。由于这些方法相当直接,我们将其实现留给读者。现在让我们看看最优的解决方案。
Approach 2: In this approach, we follow Kadane's algorithm. The basic idea behind Kadane's approach is to search the array for all positive contiguous segments (max_ending_here is utilized for this). Also, among all positive segments, we maintain track of the maximum total contiguous segment (max_so_far is utilized for this). We compare each positive-sum to max_so_far and update max_so_far if it is more than max_so_far.
方法2:在这种方法中,我们遵循卡丹算法。卡丹方法的基本思想是搜索数组中所有正的连续段(为此使用max_ending_here)。此外,在所有正段中,我们跟踪最大总连续段(为此使用max_so_far)。我们将每个正和与max_so_far进行比较,如果大于max_so_far则更新max_so_far。
Solution Code:
解决方案代码:
include
using namespace std;
using namespace std;
// function to find the maximum contiguous subarray sum
// 用于找到最大连续子数组和的函数
int findMaxSubArraySum(int arr[], int size)
int findMaxSubArraySum(int arr[], int size)
{
int max_so_far = arr[0];
int max_so_far = arr[0];
int curr_max = arr[0];
int curr_max = arr[0];
for (int i = 1; i < size; i++)
for (int i = 1; i < size; i++)
{
curr_max = max(arr[i], curr_max+arr[i]);
curr_max = max(arr[i], curr_max+arr[i]);
max_so_far = max(max_so_far, curr_max);
max_so_far = max(max_so_far, curr_max);
}
return max_so_far;
return max_so_far;
}
int main()
int main()
{
int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int n = sizeof(arr)/sizeof(arr[0]);
int n = sizeof(arr)/sizeof(arr[0]);
int max_sum = findMaxSubArraySum(arr, n);
int max_sum = findMaxSubArraySum(arr, n);
cout << "The maximum contiguous sum for the given array is : " << max_sum;
cout << "The maximum contiguous sum for the given array is : " << max_sum;
return 0;
return 0;
}
Output:
输出:
7
Time Complexity: O(n)
时间复杂度:O(n)
Space Complexity: O(1)
空间复杂度:O(1)
Explanation: In the above code, the function findMaxSubArraySum() takes the input of an array and the size of the array as its parameters and returns the maximum sum for a contiguous subarray of the given array. We keep two variables to find our answer. curr_max holds the current maximum subarray sum whose elements are the array elements just before the current index. max_so_far holds the maximum subarray sum seen so far.
解释:在上述代码中,函数 findMaxSubArraySum() 将数组和数组大小作为其参数输入,并返回给定数组的连续子数组的最大和。我们保留两个变量来找到答案。curr_max 保存当前最大子数组和,其元素是当前索引之前的数组元素。max_so_far 保存迄今为止看到的最大子数组和。
86. How can we compare between two algorithms written for the same problem?
如何比较针对同一问题编写的两个算法?
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b979fd | 官方: 否 | 付费: 否
答案:
The complexity of an algorithm is a technique that is used to categorise how efficient it is in comparison to other algorithms. It focuses on how the size of the data set to be processed affects execution time. In computing, the algorithm's computational complexity is critical. It is a good idea to categorise algorithms according to how much time or space they take up and to describe how much time or space they take up as a function of input size. - Complexity of Time: The running time of a program as a function of the size of the input is known as time complexity.
算法的复杂度是一种用于分类其相对于其他算法效率的技术。它关注的是待处理数据集的大小如何影响执行时间。在计算中,算法的计算复杂度至关重要。根据算法占用时间或空间的大小,并以输入大小的函数形式描述它们所占用的时间或空间,是个好主意。- 时间复杂度:程序运行时间作为输入大小的函数,称为时间复杂度。
Complexity of Space: Space complexity examines algorithms based on how much space they require to fulfil their tasks. In the early days of computers, space complexity analysis was crucial (when storage space on the computer was limited).
Note: Nowadays, a lack of space is rarely an issue because computer storage is plentiful. Therefore, it is mostly the Time Complexity that is given more importance while evaluating an Algorithm.注意:如今,空间不足很少成为问题,因为计算机存储非常充足。因此,在评估算法时,主要更多关注的是时间复杂度。
87. What do you understand about the DFS (Depth First Search) algorithm.
你对DFS(深度优先搜索)算法有何理解?
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a00 | 官方: 否 | 付费: 否
答案:
Depth First Search or DFS is a technique for traversing or exploring data structures such as trees and graphs. The algorithm starts at the root node (in the case of a graph, any random node can be used as the root node) and examines each branch as far as feasible before retracing. So the basic idea is to start at the root or any arbitrary node and mark it, then advance to the next unmarked node and repeat until there are no more unmarked nodes. After that, go back and check for any more unmarked nodes to cross. Finally, print the path's nodes. The DFS algorithm is given below: - Step1: Create a recursive function that takes the node's index and a visited array as input.
深度优先搜索(DFS)是一种用于遍历或探索树和图等数据结构的技术。该算法从根节点开始(对于图,可以使用任意随机节点作为根节点),并在回溯前尽可能深入地检查每条分支。因此,基本理念是从根节点或任意节点开始并标记它,然后前进到下一个未标记的节点,并重复此过程,直到没有更多未标记的节点。之后,返回并检查是否有更多未标记的节点需要穿越。最后,打印路径上的节点。DFS算法如下:- 步骤1:创建一个递归函数,接收节点索引和访问数组作为输入。
- Step 2: Make the current node a visited node and print it.
- Step 3: Call the recursive function with the index of the adjacent node after traversing all nearby and unmarked nodes.
88. What do you understand about the BFS (Breadth First Search) algorithm.
你对BFS(广度优先搜索)算法有何理解?
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a03 | 官方: 否 | 付费: 否
答案:
BFS or Breadth-First Search is a graph traversal technique. It begins by traversing the graph from the root node and explores all of the nodes in the immediate vicinity. It chooses the closest node and then visits all of the nodes that have yet to be visited. Until it reaches the objective node, the algorithm repeats the same method for each of the closest nodes.
BFS或广度优先搜索是一种图遍历技术。它从根节点开始遍历图,并探索紧邻区域中的所有节点。它选择最近的节点,然后访问所有尚未访问的节点。直到达到目标节点,算法对每个最近的节点重复相同的方法。
The BFS Algorithm is given below: - Step 1: Set status = 1 as the first step for all the nodes(ready state).
BFS算法如下:- 步骤1:将所有节点的状态设置为1作为第一步(就绪状态)。
- Step 2: Set the status of the initial node A to 2, that is, waiting state.
- Step 3: Repeat steps 4 and 5 until the queue is not empty.
- Step 4: Dequeue and process node N from the queue, setting its status to 3, that is, the processed state.
- Step 5: Put all of N's neighbours in the ready state (status = 1) in the queue and set their status to 2 (waiting state)
- Step 6: Exit.
89. Write down a string reversal algorithm. If the given string is "kitiR," for example, the output should be "Ritik".
写下一个字符串反转算法。例如,如果给定字符串是“kitiR”,则输出应为“Ritik”。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a06 | 官方: 否 | 付费: 否
答案:
An algorithm for string reversal is as follows: - Step 1: Start.
字符串反转的算法如下:- 步骤1:开始。
- Step 2: We take two variables l and r.
- Step 3: We set the values of l as 0 and r as (length of the string - 1).
- Step 4: We interchange the values of the characters at positions l and r in the string.
- Step 5: We increment the value of l by one.
- Step 6: We decrement the value of r by one.
- Step 7: If the value of r is greater than the value of l, we go to step 4
- Step 8: Stop.
90. What do you understand about the Dynamic Programming (DP) Algorithmic Paradigm? List a few problems which can be solved using the same.
你对动态规划(DP)算法范式有何理解?列举几个可以用它解决的问题。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a09 | 官方: 否 | 付费: 否
答案:
Dynamic Programming is primarily a recursion optimization. We can use Dynamic Programming to optimise any recursive solution that involves repeated calls for the same inputs. The goal is to simply save the results of subproblems so that we do not have to recalculate them later. The time complexity of this simple optimization is reduced from exponential to polynomial. For example, if we create a simple recursive solution for Fibonacci Numbers, the time complexity is exponential, but if we optimise it by storing subproblem answers using Dynamic Programming, the time complexity is linear.
动态规划主要是一种递归优化。我们可以使用动态规划来优化任何涉及对相同输入重复调用的递归解决方案。其目标简单来说就是保存子问题的结果,以便我们不必在之后重新计算它们。这种简单优化的时间复杂度从指数级降低到了多项式级。例如,如果我们为斐波那契数列创建一个简单的递归解决方案,时间复杂度是指数级的,但如果我们通过使用动态规划存储子问题的答案来优化它,时间复杂度就是线性的。
The following codes illustrate the same:
以下代码说明了这一点:
With Recursion (no DP): The time complexity of the given code will be exponential.
使用递归(无DP):给定代码的时间复杂度将是指数级的。
/Sample C++ code for finding nth fibonacci number without DP/
/用于查找第n个斐波那契数的C++示例代码(不含DP)/
int nFibonacci(int n){
int nFibonacci(int n){
if(n == 0 || n == 1) return n;
if(n == 0 || n == 1) return n;
else return nFibonacci(n - 1) + nFibonacci(n - 2);
else return nFibonacci(n - 1) + nFibonacci(n - 2);
}
With DP: The time complexity of the given code will be linear because of Dynamic Programming.
使用DP:由于动态规划,给定代码的时间复杂度将是线性的。
/Sample C++ code for finding nth fibonacci number with DP/
/用于查找第n个斐波那契数的C++示例代码(含DP)/
int nFibonacci(int n){
int nFibonacci(int n){
vectorfib(n + 1);
vectorfib(n + 1);
fib[0] = 0;
fib[0] = 0;
fib[1] = 1;
fib[1] = 1;
for(int i = 2;i <= n;i ++){
for(int i = 2;i <= n;i ++){
fib[i] = fib[i - 1] + fib[i - 2];
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
return fib[n];
}
A few problems which can be solved using the Dynamic Programming (DP) Algorithmic Paradigm are as follows: - Finding the nth Fibonacci number
几个可以使用动态规划(DP)算法范式解决的问题如下:- 查找第n个斐波那契数
- Finding the Longest Common Subsequence between two strings.
- Finding the Longest Palindromic Substring in a string.
- The discrete (or 0-1) Knapsack Problem.
- Shortest Path between any two nodes in a graph (Floyd Warshall Algorithm)
- Data Science
- All Events
- My Events
91. Write an algorithm for counting the number of leaf nodes in a binary tree.
编写一个用于统计二叉树中叶节点数量的算法。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a0c | 官方: 否 | 付费: 否
答案:
An algorithm for counting the number of leaf nodes in a binary tree is given below: - Step 1: If the current node is null, return a value 0.
用于统计二叉树中叶节点数量的算法如下:- 步骤 1:如果当前节点为空,则返回值 0。
- Step 2: If a leaf node is encountered, that is, if the current node's left and right nodes are both null, then return 1.
- Step 3: Calculate the number of leaf nodes recursively by adding the number of leaf nodes in the left subtree by the number of leaf nodes in the right subtree.
92. Write down an algorithm for adding a node to a linked list sorted in ascending order(maintaining the sorting property).
写出一个用于向按升序排序的链表添加节点(保持排序属性)的算法。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a0f | 官方: 否 | 付费: 否
答案:
An algorithm for adding a node to a link list sorted in ascending order (maintaining the sorting property) is given below: - Step 1: Check if the linked list has no value (or is empty). If yes, then set the new node as the head and return it.
用于向按升序排序的链表添加节点(保持排序属性)的算法如下:- 步骤 1:检查链表是否没有值(或为空)。如果是,则将新节点设置为头节点并返回它。
- Step 2: Check if the value of the node to be inserted is smaller than the value of the head node. If yes, place it at the beginning and make it the head node.
- Step 3: Find the suitable node after which the input node should be added in a loop. To discover the required node, begin at the head and work your way forward until you reach a node whose value exceeds the input node. The preceding node is the correct node.
- Step 4: After the correct node is found in step 3, insert the node.
93. Describe the Binary Search Algorithm.
描述二分查找算法。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a12 | 官方: 否 | 付费: 否
答案:
To apply binary search on a list of elements, the prerequisite is that the list of elements should be sorted. It is based on the Divide and Conquers Algorithmic paradigm. In the Binary Search Algorithm, we divide the search interval in half periodically to search the sorted list. We begin by creating an interval that spans the entire list. If the search key's value is less than the item in the interval's midpoint, the interval should be narrowed to the lower half. Otherwise, we limit it to the upper half of the page. We check for the value until it is discovered or the interval is empty. Given below is an algorithm describing Binary Search: (Let us assume that the element to be searched is x and the array of elements is sorted in ascending order) - Step 1: x should be firstly compared to the middle element.
要在一组元素列表上应用二分查找,前提是该元素列表必须已排序。它基于分治算法范式。在二分查找算法中,我们定期将搜索区间一分为二来搜索已排序列表。我们首先创建一个覆盖整个列表的区间。如果搜索键的值小于区间中点处的元素,则区间应缩小到下半部分。否则,我们将其限制在页面的上半部分。我们检查该值,直到找到它或区间为空。下面给出一个描述二分查找的算法:(假设要搜索的元素为 x,并且元素数组已按升序排序)- 步骤 1:x 应首先与中间元素进行比较。
- Step 2: We return the middle element's index if x matches the middle element.
- Step 3: Else If x is greater than the middle element, x can only be found after the middle element in the right half subarray since the array is sorted in the ascending order. As a result, we repeat the process for the right half.
- Step 4: Otherwise, we repeat for the left half (x is smaller).
Step 5: If the interval is empty, we terminate the binary search.
The time complexity of the Binary Search Algorithm is O(log(n)) where n is the size of the list of elements and its space complexity is constant, that is, O(1).二分查找算法的时间复杂度为 O(log(n)),其中 n 是元素列表的大小,其空间复杂度为常数,即 O(1)。
94. Describe the Linear Search Algorithm.
描述线性查找算法。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a15 | 官方: 否 | 付费: 否
答案:
To find an element in a group of elements, the linear search can be used. It works by traversing the list of elements from the beginning to the end and inspecting the properties of all the elements encountered along the way. Let us consider the case of an array containing some integer elements. We want to find out and print all of the elements' positions that match a particular value (also known as the "key" for the linear search). The linear search works in a flow here, matching each element with the number from the beginning to the end of the list, and then printing the element's location if the element at that position is equal to the key.
要在元素组中查找一个元素,可使用线性查找。它通过从列表开头遍历到结尾并检查沿途遇到的所有元素的属性来工作。让我们考虑一个包含一些整数元素的数组的情况。我们想找出并打印所有与特定值(也称为线性查找的“键”)匹配的元素位置。线性查找在此按流程工作,将每个元素与从列表开头到结尾的数字进行匹配,然后如果该位置的元素等于键,则打印该元素的位置。
Given below is an algorithm describing Linear Search: - Step 1: Using a loop, traverse the list of elements given.
下面给出一个描述线性查找的算法:- 步骤 1:使用循环,遍历给定的元素列表。
- Step 2: In each iteration, compare the target value (or key-value) to the list's current value.
- Step 3: If the values match, print the array's current index.
- Step 4: Move on to the next array element if the values do not match.
- Step 5: Repeat Steps 1 to 4 till the end of the list of elements is reached.
The time complexity of the Linear Search Algorithm is O(n) where n is the size of the list of elements and its space complexity is constant, that is, O(1).
线性查找算法的时间复杂度为 O(n),其中 n 是元素列表的大小,其空间复杂度为常数,即 O(1)。
95. What do you understand by a searching algorithm? List a few types of searching algorithms.
你对搜索算法有什么理解?列出几种类型的搜索算法。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a18 | 官方: 否 | 付费: 否
答案:
Searching Algorithms are used to look for an element or get it from a data structure (usually a list of elements). These algorithms are divided into two categories based on the type of search operation: - Sequential Search: This method traverses the list of elements consecutively, checking each element and reporting if the element to be searched is found. Linear Search is an example of a Sequential Search Algorithm.
搜索算法用于从数据结构(通常是元素列表)中查找或获取一个元素。这些算法根据搜索操作的类型分为两类:- 顺序搜索:此方法连续遍历元素列表,检查每个元素并报告要搜索的元素是否找到。线性查找是顺序搜索算法的一个示例。
- Interval Search: These algorithms were created specifically for searching sorted data structures. Because they continually target the centre of the search structure and divide the search space in half, these types of search algorithms are far more efficient than Sequential Search algorithms. Binary Search is an example of an Interval Search Algorithm.
96. What do you understand about greedy algorithms? List a few examples of greedy algorithms.
你对贪心算法有什么理解?列出几个贪心算法的示例。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a1b | 官方: 否 | 付费: 否
答案:
A greedy algorithm is an algorithmic method that aims to choose the best optimal decision at each sub-step, eventually leading to a globally optimal solution. This means that the algorithm chooses the best answer available at the time, regardless of the consequences. In other words, when looking for an answer, an algorithm always selects the best immediate, or local, option. Greedy algorithms may identify less than perfect answers for some cases of other problems while finding the overall, ideal solution for some idealistic problems.
贪心算法是一种算法方法,旨在每个子步骤中选择最佳最优决策,最终导致全局最优解。这意味着算法选择当时可用的最佳答案,而不考虑后果。换句话说,在寻找答案时,算法总是选择最直接的、即局部最佳选项。贪心算法对于某些问题的某些情况可能会找到不太完美的答案,而对于某些理想化问题能找到整体的理想解决方案。
The Greedy algorithm is used in the following algorithms to find their solutions: - Prim's Minimal Spanning Tree Algorithm
贪心算法用于以下算法中以找到其解决方案:- Prim 的最小生成树算法
- Kruskal's Minimal Spanning Tree Algorithm
- Travelling Salesman Problem
- Fractional Knapsack Problem
- Dijkstra's Algorithm
- Job Scheduling Problem
- Graph Map Coloring
- Graph Vertex Cover.
97. Explain the Divide and Conquer Algorithmic Paradigm. Also list a few algorithms which use this paradigm.
解释分治算法范式。同时列出几个使用该范式的算法。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a1e | 官方: 否 | 付费: 否
答案:
Divide and Conquer is an algorithm paradigm, not an algorithm itself. It is set up in such a way that it can handle a large amount of data, split it down into smaller chunks, and determine the solution to the problem for each of the smaller chunks. It combines all of the piecewise solutions of the smaller chunks to form a single global solution. This is known as the divide and conquer technique. The Divide and Conquer algorithmic paradigm employ the steps given below: - Divide: The algorithm separates the original problem into a set of subproblems in this step.
分治是一种算法范式,而不是算法本身。它的设置方式使其能够处理大量数据,将其拆分成较小的块,并为每个较小的块确定问题的解决方案。它结合所有较小块的逐段解决方案以形成单一的全局解决方案。这被称为分治技术。分治算法范式采用以下给出的步骤:- 划分:该算法在此步骤中将原始问题分离为一组子问题。
- Conquer: The algorithm solves each subproblem individually in this step.
- Combine: In this step, the algorithm combines the solutions to the subproblems to obtain the overall solution.
Some of the algorithms which use the Divide and Conquer Algorithmic paradigm are as follows: - Binary Search
使用分治算法范式的一些算法如下:- 二分查找
- Merge Sort
- Strassen's Matrix Multiplication
- Quick Sort
- Closest pair of points.
Successful Tech Career for FREE!
免费开启成功的科技职业生涯!
Successful Tech Career!
成功的技术职业生涯!
Interview Process
面试流程
CTC & Designation
CTC与职位级别
Projects on the Job
工作项目
Referral System
推荐系统
Try It Out
试试看
2 Lakh+ Roadmaps Created
已生成20万+职业规划
98. Write an algorithm to swap two given numbers in Java without using a temporary variable.
编写一个算法,在Java中不使用临时变量交换两个给定的数字。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a21 | 官方: 否 | 付费: 否
答案:
It is a trick question that is frequently asked in the interviews of various companies. This problem can be solved in a variety of ways. However, while solving the problem, we must solve it without using a temporary variable, which is an essential condition. For this problem, if we can consider the possibility of integer overflow in our solution while coming up with an approach to solving it, we can make a great impression on interviewers.
这是一个技巧性问题,经常出现在各类公司的面试中。这个问题可以通过多种方式解决。然而,在解决问题时,我们必须在不使用临时变量的情况下解决,这是一个基本条件。对于这个问题,如果我们在提出解决方法时能考虑解决方案中的整数溢出可能性,就能给面试官留下深刻印象。
Let us say that we have two integers a and b, with a's value equal to 5 and b's value equal to 6, and we want to swap them without needing a third variable. We will need to use Java programming constructs to solve this problem. Mathematical procedures such as addition, subtraction, multiplication, and division can be used to swap numbers. However, it is possible that it will cause an integer overflow problem.
假设我们有两个整数a和b,a的值等于5,b的值等于6,我们想在不使用第三个变量的情况下交换它们。我们将需要使用Java编程结构来解决这个问题。数学过程,如加法、减法、乘法和除法,可以用来交换数字。然而,这可能会导致整数溢出问题。
Let us take a look at two approaches to solve this problem:
让我们看看解决这个问题的两种方法:
Using Addition and subtraction:
使用加法和减法:
a = a + b;
a = a + b;
b = a - b; // this will act like (a+b) - b, and now b equals a.
b = a - b; // 这将表现为(a+b) - b,现在b等于a。
a = a - b; // this will act like (a+b) - a, and now an equals b.
a = a - b; // 这将表现为(a+b) - a,现在a等于b。
It is a clever trick. However, if the addition exceeds the maximum value of the int primitive type as defined by Integer.MAX_VALUE in Java, or if the subtraction is less than the minimum value of the int primitive type as defined by Integer.MIN_VALUE in Java, there will be an integer overflow.
这是一个巧妙的技巧。然而,如果加法超过Java中由Integer.MAX_VALUE定义的int原始类型的最大值,或者减法小于Java中由Integer.MIN_VALUE定义的int原始类型的最小值,就会发生整数溢出。
Using the XOR method:
使用XOR方法:
Another way to swap two integers without needing a third variable (temporary variable) is using the XOR method. This is often regarded as the best approach because it works in languages that do not handle integer overflows, such as Java, C, and C++. Java has a number of bitwise operators. XOR (denoted by ^) is one of them.
另一种不需要第三个变量(临时变量)交换两个整数的方法是使用XOR方法。这通常被认为是最好的方法,因为它适用于不处理整数溢出的语言,如Java、C和C++。Java有许多位运算符。XOR(用^表示)就是其中之一。
x = x ^ y;
x = x ^ y;
y = x ^ y;
y = x ^ y;
x = x ^ y;
x = x ^ y;
99. What do you understand by the Asymptotic Notations?
你对渐近符号有何理解?
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3792158d557c902b97a24 | 官方: 否 | 付费: 否
答案:
Asymptotic analysis is a technique that is used for determining the efficiency of an algorithm that does not rely on machine-specific constants and avoids the algorithm from comparing itself to the time-consuming approach. For asymptotic analysis, asymptotic notation is a mathematical technique that is used to indicate the temporal complexity of algorithms.
渐近分析是一种用于确定算法效率的技术,它不依赖于机器特定的常量,并避免算法与耗时方法进行比较。对于渐近分析,渐近符号是一种数学技术,用于表示算法的时间复杂度。
The following are the three most common asymptotic notations. - Big Theta Notation: (θ Notation)The exact asymptotic behaviour is defined using the theta (θ) Notation. It binds functions from above and below to define behaviour. Dropping low order terms and ignoring leading constants is a convenient approach to get Theta notation for an expression.
以下是三种最常见的渐近记号。- 大Theta记号:(θ记号)精确的渐近行为使用theta(θ)记号来定义。它从上方和下方约束函数以定义行为。去掉低阶项并忽略前导常数是获取表达式Theta记号的便捷方法。
- Big O Notation:The Big O notation defines an upper bound for an algorithm by bounding a function from above. Consider the situation of insertion sort: in the best case scenario, it takes linear time, and in the worst case, it takes quadratic time. Insertion sort has a time complexity O(n^2). It is useful when we just have an upper constraint on an algorithm's time complexity.
- Big Omega (Ω) Notation:The Ω Notation provides an asymptotic lower bound on a function, just like Big O notation does. It is useful when we have a lower bound on an algorithm's time complexity.
100. What do you understand by the best case, worst case and average case scenario of an algorithm?
你如何理解算法的最佳情况、最差情况和平均情况场景?
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: interviewbit, algorithm, topic-specific, algorithms, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3792158d557c902b97a27 | 官方: 否 | 付费: 否
答案:
The mathematical foundation/framing of an algorithm's run time performance is defined by asymptotic analysis. We can easily determine the best case, average case, and worst-case scenarios of an algorithm using asymptotic analysis. - Best Case Scenario of an Algorithm: The best-case scenario for an algorithm is defined as the data arrangement in which the algorithm performs the best. Take a binary search, for example, where the best-case scenario is if the target value is in the very centre of the data we are looking for. The best-case scenario for binary search would have a time complexity of O(1) or constant time complexity.
算法运行时间性能的数学基础/框架由渐近分析定义。我们可以使用渐近分析轻松确定算法的最佳情况、平均情况和最差情况场景。- 算法的最佳情况场景:算法的最佳情况场景定义为算法表现最佳的数据排列。以二分搜索为例,最佳情况场景是目标值正好位于我们查找数据的正中心。二分搜索的最佳情况场景的时间复杂度为O(1)或常数时间复杂度。
- Worst Case Scenario of an Algorithm: The worst collection of input for a given algorithm is referred to as the worst-case scenario of an Algorithm. For example, quicksort can perform poorly if the pivot value is set to the largest or smallest element of a sublist. Quicksort will degenerate into an algorithm with a time complexity of O(n^2), where n is the size of the list to be sorted.
- Average Case Scenario of an Algorithm: The average-case complexity of an algorithm is the amount of some computational resource (usually time) used by the process, averaged over all possible inputs, according to computational complexity theory. For example, the average-case complexity of the randomised quicksort algorithm is O(n*log(n)), where n is the size of the list to be sorted.
101. Explain the binary search tree. Write code for insertion in a binary search tree.
解释二叉搜索树。编写在二叉搜索树中进行插入的代码。
- 知识点: 算法与数据结构 (标签: interviewbit, amdocs, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Amdocs
- id: 69b3792d58d557c902b9847c | 官方: 否 | 付费: 否
答案:
A binary Search Tree (BST) is a special kind of binary tree (tree-like structure) where the parent and child nodes are linked. Binary Search trees allow only two child nodes per parent node (the root/top node). In BTS, all nodes to the left of the root node contain lower values than the root node, whereas nodes to the right contain greater values as shown below.
二叉搜索树(BST)是一种特殊的二叉树(树状结构),其中父节点和子节点是相连的。二叉搜索树中,每个父节点(根/顶部节点)只允许有两个子节点。在BST中,根节点左侧的所有节点的值都小于根节点,而右侧的节点的值都大于根节点,如下所示。
Insertion: Insert a node in the BST. New nodes will either be inserted into the left subtree if their value is less than the root node or into the right subtree if their value is greater than the root node.
插入:在BST中插入一个节点。如果新节点的值小于根节点,则将其插入到左子树中;如果其值大于根节点,则将其插入到右子树中。
//Insertion code for BST
//BST的插入代码
struct node insert(struct node root, int val)
struct node insert(struct node root, int val)
{
// It handles two cases,
// 它处理两种情况,
//1. Return new node, if the tree is empty
//1. 如果树为空,则返回新节点
// 2. Return new node, if tree traversal reaches NULL
// 2. 如果树遍历到达NULL,则返回新节点
if(root == NULL)
if(root == NULL)
return getNewNode(val);
return getNewNode(val);
//If given val is greater than root->key,
//如果给定的val大于root->key,
//Insert the new node at the correct place in the right subtree
//在右子树中正确位置插入新节点
if(root->key < val)
if(root->key < val)
root->right = insert(root->right,val);
root->right = insert(root->right,val);
//If given val is smaller than root->key,
//如果给定的val小于root->key,
//Insert the new node at the correct place in the left subtree
//在左子树中正确位置插入新节点
else if(root->key > val)
else if(root->key > val)
root->left = insert(root->left,val);
root->left = insert(root->left,val);
return root;
return root;
}
102. What is a Jagged Array in Java?
Java中的锯齿数组是什么?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b9941c | 官方: 否 | 付费: 否
答案:
Jagged arrays are multidimensional arrays in which the member arrays are of different sizes. As an example, we can make a 2D array where the first array contains three elements, and the second array consists of four elements. Below is an example demonstrating the concept of jagged arrays.
锯齿数组是成员数组具有不同大小的多维数组。例如,我们可以创建一个二维数组,其中第一个数组包含三个元素,第二个数组包含四个元素。以下是一个演示锯齿数组概念的示例。
public class InterviewBit {
public class InterviewBit {
public static void main(String[] args){
public static void main(String[] args){
int[][] 2dArray = new int[2][];
int[][] 2dArray = new int[2][];
2dArray[0] = new int[3];
2dArray[0] = new int[3];
2dArray[1] = new int[4];
2dArray[1] = new int[4];
int counter = 0;
int counter = 0;
for(int row=0; row <2dArray.length; row++){
for(int row=0; row <2dArray.length; row++){
for(int col=0; col < 2dArray[row].length; col++){
for(int col=0; col < 2dArray[row].length; col++){
2dArrayrow = counter++;
2dArrayrow = counter++;
}
}
for(int row=0; row < 2dArray.length; row++){
for(int row=0; row < 2dArray.length; row++){
System.out.println();
System.out.println();
for(int col=0; col < 2dArray[row].length; col++){
for(int col=0; col < 2dArray[row].length; col++){
System.out.print(2dnArrayrow + " ");
System.out.print(2dnArrayrow + " ");
}
}
}
}
Output:
输出:
0 1 2
3 4 5 6
103. Can the sizeof operator be used to tell the size of an array passed to a function?
sizeof运算符能否用于告诉传递给函数的数组的大小?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b3793e58d557c902b9941f | 官方: 否 | 付费: 否
答案:
Passing an array as a parameter in C or C++ does not pass information about how many elements there are in the array. Although sizeof() can tell you the size of the pointer and the size of the type it points to, it cannot tell you how many bytes are occupied by the entire array.
在 C 或 C++ 中将数组作为参数传递时,并不会传递关于数组中有多少个元素的信息。尽管 sizeof() 可以告诉你指针的大小以及它所指向类型的大小,但它无法告诉你整个数组占用了多少字节。
104. Mention some advantages and disadvantages of Arrays.
提及数组的一些优点和缺点。
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99422 | 官方: 否 | 付费: 否
答案:
Advantages: - Multiple elements of Array can be sorted at the same time.
优点:- 数组的多个元素可以同时进行排序。
Using the index, we can access any element in O(1) time.
Disadvantages: - You need to specify how many elements you're going to store in your array ahead of time and We can not increase or decrease the size of the Array after creation.缺点:- 你需要提前指定要在数组中存储多少个元素,并且数组创建后我们无法增加或减小其大小。
- You have to shift the other elements to fill in or close gaps, which takes worst-case O(n) time.
105. What is the difference between length and length () in Java?
在 Java 中,length 和 length() 有什么区别?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99425 | 官方: 否 | 付费: 否
答案:
In Java, the length() is a method of String class whereas length is an instance variable of an array. - length in Java
在 Java 中,length() 是 String 类的一个方法,而 length 是数组的一个实例变量。- Java 中的 length
The length variable returns the length of an array i.e. a number of elements present in an array. After initializing, the length of an array cannot be changed, so the length variable can directly be used to get the length of an array. It is used only for an array. Example:
length 变量返回数组的长度,即数组中存在的元素个数。初始化后,数组的长度不能更改,因此可以直接使用 length 变量来获取数组的长度。它仅用于数组。示例:
public class InterviewBit {
public class InterviewBit {
public static void main(String args[]) {
public static void main(String args[]) {
int array[] = {1, 2, 3, 4, 5};
int array[] = {1, 2, 3, 4, 5};
System.out.println("Length of an array is: " + array.length);
System.out.println("Length of an array is: " + array.length);
}
}
Output
输出
Length of an array is: 5
Length of an array is: 5
length() in Java
It is a static method of String class.它是 String 类的一个静态方法。
The length() returns the number of characters stored in a string object.
length() 返回存储在字符串对象中的字符数。
The string class uses this method as the length of a string can be modified using the various operations performed on a string object.
字符串类使用此方法,因为字符串的长度可以通过对字符串对象执行的各种操作来修改。
The String class uses a char[] array internally.
String 类内部使用一个 char[] 数组。
Example:
示例:
public class InterviewBit {
public class InterviewBit {
public static void main(String args[]) {
public static void main(String args[]) {
String str = "Welcome to InterviewBit";
String str = "Welcome to InterviewBit";
System.out.println("Length of String using length() method is: " + str.length());
System.out.println("Length of String using length() method is: " + str.length());
}
}
Output:
输出:
Length of String using length() method is: 23
使用length()方法获取的字符串长度为:23
106. We know that Arrays are objects so why cannot we write strArray.length()?
我们知道数组是对象,那么为什么不能写strArray.length()呢?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99428 | 官方: 否 | 付费: 否
答案:
We cannot write strArray.length() because length is not a method, it's a data item of an array. We can use the methods of Object like toString() and hashCode() against Array.
我们不能写strArray.length(),因为length不是方法,它是数组的一个数据项。我们可以对数组使用Object类的方法,如toString()和hashCode()。
107. When will we get ArrayIndexOutOfBounds Exception?
什么时候会得到ArrayIndexOutOfBounds异常?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b9942c | 官方: 否 | 付费: 否
答案:
ArrayIndexOutOfBoundsis a runtime exception that occurs when the program tries to access the invalid index of an array such as an Index higher than the size of the array or a negative index.
ArrayIndexOutOfBounds是运行时异常,当程序尝试访问数组的无效索引时发生,例如索引大于数组大小或索引为负数。
108. When will we get ArrayStoreException?
什么时候会得到ArrayStoreException?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99430 | 官方: 否 | 付费: 否
答案:
- ArrayStoreException is a runtime exception.
- For example, you will get this exception at run time if you declare a String Array and then try to insert integer elements in the array.
109. Can a Negative number be passed in Array size?
数组大小可以传递负数吗?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99433 | 官方: 否 | 付费: 否
答案:
No, a negative number cannot be passed as array size. If you pass a negative number in Array size then you will get the NegativeArraySizeException at run time.
不可以,负数不能作为数组大小传递。如果在数组大小中传递负数,则会在运行时得到NegativeArraySizeException。
110. Find the Target Element in an array.
在数组中查找目标元素。
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99436 | 官方: 否 | 付费: 否
答案:
First of all, you will get a number n, which indicates the size of the array. After that, you will get n more inputs corresponding to each index of the array. Then you will be given a target, for which you have to find, at which index of array target is present. Print -1 if target is not present in the array.
首先,你会得到一个数字n,它表示数组的大小。之后,你会得到n个输入,对应数组的每个索引。然后会给你一个目标值,你需要找出该目标值在数组的哪个索引处。如果目标值不在数组中,则打印-1。
Approach:
方法:
We will run a for loop on the input array and check if the value equivalent to target is present in the array or not.
我们将在输入数组上运行一个for循环,检查是否存在与目标值相等的值。
If the target is found then we will print the index of this target value and return else we will return -1.
如果找到目标值,则打印该目标值的索引并返回,否则返回-1。
import java.io.*;
import java.io.*;
import java.util.*;
import java.util.*;
public class InterviewBit {
public class InterviewBit {
public static void main(String[] args) throws Exception {
public static void main(String[] args) throws Exception {
Scanner scn = new Scanner(System.in);
扫描器 scn = 新扫描器(System.in);
int n = scn.nextInt();
整数 n = scn.nextInt();
int[] arr = new int[n];
整数[] arr = 新整数[n];
for (int i = 0; i < n; i++) {
for (int i = 0; i < n; i++) {
arr[i] = scn.nextInt();
arr[i] = scn.nextInt();
}
int target = scn.nextInt();
int target = scn.nextInt();
for (int i = 0; i < arr.length; i++) {
for (int i = 0; i < arr.length; i++) {
if (target == arr[i]) {
if (target == arr[i]) {
System.out.println(i);
System.out.println(i);
return;
return;
}
}
System.out.println(-1);
System.out.println(-1);
}
}
111. Where is an Array stored in JVM memory?
在 JVM 内存中,数组存储在哪里?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99439 | 官方: 否 | 付费: 否
答案:
An Array is an object in java. So, Array is stored in heap memory in Java Virtual Machine.
数组在 Java 中是一个对象。因此,数组存储在 Java 虚拟机中的堆内存里。
112. Difference between Array and Object.
数组和对象之间的区别。
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b9943e | 官方: 否 | 付费: 否
答案:
- An object represents a thing with characteristics (called a property), whereas an array creates a list of data and stores it in a single variable. Using brackets and dots, we can access, alter, and delete items from objects, while a variety of built-in methods and zero-based indexing allow us to access and modify items in arrays. We can iterate over object properties and array items using various different loops (e.g. for, for…in, for…of, forEach()).
- All Java objects are dynamically allocated on the heap. Unlike C++, where objects can be allocated in memory either on Heap or on Stack. When we use the new() method in C++, the object is allocated on the heap, otherwise on Stack if not global or static.
113. Can you declare an array without assigning the size of an array?
你能不指定数组大小来声明一个数组吗?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99441 | 官方: 否 | 付费: 否
答案:
No, we cannot declare an array without assigning size. If we declare an array without size, it will throw compile time error.
不能,我们不能不指定大小来声明一个数组。如果我们不指定大小声明数组,它将抛出编译时错误。
114. What is the time complexity for performing basic operations in an array?
在数组上执行基本操作的时间复杂度是多少?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99444 | 官方: 否 | 付费: 否
答案:
The Time Complexity of different operations in an array is: For analyzing the real-time complexity you also have to consider the time in bringing the block of memory from an external device to RAM which takes O(√N) time.
数组中不同操作的时间复杂度是:为了分析实时复杂度,你还必须考虑将内存块从外部设备读取到 RAM 所需的时间,这需要 O(√N) 的时间。
| ARRAY OPERATION 数组操作 | REAL TIME COMPLEXITY 实时复杂度 | ASSUMED TIME COMPLEXITY 假定时间复杂度 |
|---|---|---|
| Accessing the i-th element. 访问第 i 个元素。 | O(√N) | O(1) |
| Traversing all elements. 遍历所有元素。 | O(N + √N) | O(N) |
| Override element at i-th index. 覆盖第 i 个索引处的元素。 | O(√N) | O(1) |
| Insert an element. 插入一个元素。 | O(N + √N) | O(N) |
| Delete an element. 删除一个元素。 | O(N + √N) | O(N) |
115. What is the default value of Array in Java?
Java 中数组的默认值是什么?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99447 | 官方: 否 | 付费: 否
答案:
If we don't specify the values by ourselves, then Java assigns default values in them which are 0 for byte, short, int, and long, 0.0 for float and double , false for boolean, and null for objects respectively.
如果我们自己不指定值,Java 会为它们分配默认值,分别是:对于 byte、short、int 和 long 为 0,对于 float 和 double 为 0.0,对于 boolean 为 false,对于对象为 null。
116. What will happen if you do not initialize an Array?
如果你没有初始化一个数组,会发生什么?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b9944a | 官方: 否 | 付费: 否
答案:
The array will take default values depending upon the data type.
数组将根据数据类型采用默认值。
117. Difference between Array and ArrayList in Java.
Java 中数组和 ArrayList 的区别。
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b9944d | 官方: 否 | 付费: 否
答案:
| Definition 定义 | An Array is a collection of similar data types stored in contiguous memory locations. 数组是存储在连续内存位置中的相似数据类型的集合。 | An ArrayList is a class of Java Collections framework which contains popular classes like Vector, HashMap, etc. ArrayList 是 Java 集合框架中的一个类,包含 Vector、HashMap 等常用类。 |
|---|---|---|
| Static/ Dynamic 静态/动态 | static in size. 大小是静态的。 | dynamic in size. 大小是动态的。 |
| Resizable 可调整大小 | An array is not resizable as it is a fixed-length data structure. 数组不可调整大小,因为它是固定长度的数据结构。 | An ArrayList is a variable-length data structure that can be resized. As an element is being added to an ArrayList, JVM checks to see if it has enough space by calling the ensureCapacity method. If a space exists, it adds the element to the ArrayList, otherwise, it resizes the ArrayList.In the resizing process, an array of a larger size is created, the old array is copied to the new array using Arrays.copyOf, and the new array is then assigned to the existing array. ArrayList 是一种可变长度的数据结构,可以调整大小。当元素被添加到 ArrayList 时,JVM 通过调用 ensureCapacity 方法检查是否有足够空间。如果空间存在,它会将元素添加到 ArrayList,否则它会调整 ArrayList 的大小。在调整大小过程中,会创建一个更大的数组,使用 Arrays.copyOf 将旧数组复制到新数组,然后将新数组分配给现有数组。 |
| Initialization 初始化 | Size of an array should be declared directly or indirectly while initializing. 数组的大小应在初始化时直接或间接声明。 | An instance of ArrayList can be created without specifying its size. Java creates an ArrayList of default size. 可以在不指定大小的情况下创建 ArrayList 实例。Java 创建一个默认大小的 ArrayList。 |
| Performance 性能 | It is fast in comparison to ArrayList as it has a fixed size. 由于固定大小,它比 ArrayList 快。 | Slow as the resize operation in ArrayList slows down the performance. 较慢,因为 ArrayList 中的调整大小操作会降低性能。 |
| Primitive/ Generic type 原始/泛型类型 | Can store both objects and primitives type. 可以存储对象和原始类型。 | Arraylist automatically converts primitive type to object. ArrayList 自动将原始类型转换为对象。 |
| Iterating Values 迭代值 | A for loop or for each loop is used to iterate over an array. 使用 for 循环或 for-each 循环迭代数组。 | An iterator is used to iterate over ArrayList. 使用迭代器迭代 ArrayList。 |
| Length 长度 | It provides a length variable that denotes the length of an array. 它提供一个 length 变量来表示数组的长度。 | size() method can be used to determine the size of ArrayList. 可以使用 size() 方法确定 ArrayList 的大小。 |
| Single/ Multi-Dimensional 单维/多维 | Can be multi-dimensional. 可以是多维的。 | Single-dimensional. 单维的。 |
118. State difference between stack and queue.
说明栈和队列之间的区别。
- 知识点: 算法与数据结构 (标签: interviewbit, avasoft, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: AVASOFT
- id: 69b3795958d557c902b9a993 | 官方: 否 | 付费: 否
答案:
The difference between stack and queue are as follows:
栈和队列的区别如下:
| Stack 栈 | Queue 队列 |
|---|---|
| It is a linear data structure in which elements can only be added (PUSH) or removed (POP) from the top of the list. 它是一种线性数据结构,其中元素只能从列表顶部添加(PUSH)或移除(POP)。 | It is a linear data structure in which elements can be inserted (Enqueue) only from one side of the list (Rear) and the elements can be deleted (Dequeue) only from the other side (Front). 它是一种线性数据结构,其中元素只能从列表的一侧(Rear)插入(Enqueue),并且元素只能从另一侧(Front)删除(Dequeue)。 |
| The LIFO (Last In First Out) principle is commonly used in stacks. It signifies that the element added last will be the first to be removed from the list. 栈中常用LIFO(后进先出)原则。它表示最后添加的元素将首先从列表中移除。 | The FIFO (First In First Out) principle is commonly used in queues. It is likely that the element added first from the rear will also be the first element eliminated from the front. 队列中常用FIFO(先进先出)原则。很可能从后端首先添加的元素也将是从前端首先消除的元素。 |
| Stacks are utilized in a variety of applications, like addressing recursion problems, expression conversion, memory management, string parsing or string reversal, and so on. 栈用于多种应用,如解决递归问题、表达式转换、内存管理、字符串解析或字符串反转等。 | Queues are utilized in a variety of applications, like addressing sequential processing problems, routing and switching, round-robin scheduling technique, and so on. 队列用于多种应用,如解决顺序处理问题、路由和交换、轮询调度技术等。 |
| Only one pointer, known as top, is used to access the list in stacks, and it always points to the last entry in the list. 只有一个指针(称为top)用于访问栈中的列表,它始终指向列表中的最后一个条目。 | We keep two pointers in queues to access the list. The front pointer points to the first element added to the list, whereas the rear pointer points to the last element added. 我们在队列中保留两个指针来访问列表。front指针指向添加到列表的第一个元素,而rear指针指向添加的最后一个元素。 |
Stack Example:
栈示例:
Queue Example:
队列示例:
119. What pointer type should you use if you are implementing the heterogeneous linked list in C?
如果在C中实现异构链表,应该使用什么指针类型?
- 知识点: 算法与数据结构 (标签: interviewbit, axis-bank, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Axis Bank
- id: 69b3795c58d557c902b9ac4b | 官方: 否 | 付费: 否
答案:
Since the heterogeneous linked list consists of different types of data, it is not feasible for ordinary pointers to be used for this purpose. Hence, you will need to use a generic pointer type such as a void pointer since the void pointer can hold a pointer to any type.
由于异构链表包含不同类型的数据,使用普通指针不适合此目的。因此,您需要使用通用指针类型,如void指针,因为void指针可以持有指向任何类型的指针。
Useful Resources
有用资源
- Software Engineering Interview Questions
- Technical Interview Questions
- Coding Interview Questions
- Interview Resources
- DSA- Programming
- Mock Interview
120. 给定一个整数数组,找出所有和为目标值(target value)的两个数的索引。要求时间复杂度 O(n)。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: canva, generated)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: design
- 公司: 可画
- id: 69b379cc58d557c902b9ff08 | 官方: 是 | 付费: 是
答案:
思路分析使用哈希表(hash table)存储已遍历的数及其索引。对每个元素,检查目标值减去当前值是否在哈希表中。
参考答案def twoSum(nums, target):
seen = {}
seen = {}
for i, num in enumerate(nums):
for i, num in enumerate(nums):
complement = target - num
complement = target - num
if complement in seen:
如果 complement 在 seen 中:
return [seen[complement], i]
返回 [seen[complement], i]
seen[num] = i
seen[num] = i
return []评分要点- 正确使用哈希表实现 O(n) 时间复杂度
- 处理边界情况(空数组、无解)
- 代码简洁可读
- 能解释空间复杂度权衡
常见追问- 如果数组已排序,如何优化? - 如果需要找所有配对而非第一组?
- 如何处理重复元素?
121. 实现一个 LRU 缓存(LRU cache),支持 get 和 put 操作,要求时间复杂度均为 O(1)。
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 (主题: algorithms, data-structures, system-design;标签: canva, generated)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: design
- 公司: 可画
- id: 69b379cc58d557c902b9ff4d | 官方: 是 | 付费: 是
答案:
思路分析使用哈希表(hash table) + 双向链表(doubly linked list)。哈希表提供 O(1) 查找,双向链表维护访问顺序。
参考答案关键数据结构:HashMap + DoublyLinkedList。get 时将节点移到头部;put 时插入头部,容量满时删除尾部。
评分要点- 正确选择数据结构组合
- O(1) 时间复杂度的 get 和 put
- 正确处理缓存驱逐
- 线程安全考虑
常见追问- 如何实现线程安全的 LRU? - LRU vs LFU 的区别和适用场景?
- 在Canva Editor中 LRU 缓存的实际应用?
122. 给定一棵二叉树(binary tree),实现层序遍历(level-order traversal)并返回每层节点值的列表。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: canva, generated)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: design
- 公司: 可画
- id: 69b379cc58d557c902b9ff50 | 官方: 是 | 付费: 是
答案:
思路分析使用 BFS(广度优先搜索,breadth-first search),用队列(queue)逐层处理节点。
参考答案def levelOrder(root):
if not root: return []
如果 root 为空,返回 []
result, queue = [], [root]
result、queue 初始化为 []、[root]
while queue:
while queue:
level, next_q = [], []
level、next_q 初始化为 []
for node in queue:
遍历 queue 中的每个节点:
level.append(node.val)
将 node.val 添加到 level
if node.left: next_q.append(node.left)
如果 node.left 存在,将其添加到 next_q
if node.right: next_q.append(node.right)
如果 node.right 存在,将其添加到 next_q
result.append(level)
将 level 添加到 result
queue = next_q
将 queue 更新为 next_q
return result评分要点- 正确使用 BFS(Breadth-First Search)和队列(Queue)
- 处理空树边界情况
- 时间空间复杂度分析
常见追问- 如何实现锯齿形层序遍历(Zigzag Level Order Traversal)? - 如何找到二叉树的最大宽度?
123. 实现一个函数,判断给定字符串是否是有效的括号序列(Valid Parentheses Sequence)(包含 ()、[]、{})。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: canva, generated)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: design
- 公司: 可画
- id: 69b379cc58d557c902b9ff53 | 官方: 是 | 付费: 是
答案:
思路分析使用栈(Stack)匹配括号。遇到左括号入栈,遇到右括号检查栈顶是否匹配。
参考答案def isValid(s):
stack = []
stack = []
mapping = {')':'(', ']':'[', '}':'{'}
mapping = {')':'(', ']':'[', '}':'{'}
for char in s:
对于 s 中的每个字符 char:
if char in mapping:
如果 char 在 mapping 中:
if not stack or stack[-1] != mapping[char]:
如果 stack 为空或 stack[-1] != mapping[char]:
return False
return False
stack.pop()
stack.pop()
else:
否则:
stack.append(char)
stack.append(char)
return len(stack) == 0评分要点- 正确使用栈数据结构(Stack Data Structure)
- 处理空字符串和不匹配情况
- 代码简洁易读
常见追问- 如何处理嵌套层数限制(Nesting Depth Limit)? - 如果加入通配符 * 如何处理?
124. What are the disadvantages of using an array to implement Queue?
使用数组实现队列有哪些缺点?
- 知识点: 算法与数据结构 (标签: interviewbit, capgemini, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Capgemini
- id: 69b379f058d557c902ba16ec | 官方: 否 | 付费: 否
答案:
The cons of using an array to implement a queue are: - Even if the queue is empty, if it has a significant number of enqueue and dequeue operations, we may not be able to insert entries at some time (as in the case of linear increment of front and rear indices) (this problem is solved by using circular queue).
使用数组实现队列的缺点是:- 即使队列为空,如果它进行了大量的入队和出队操作,我们可能在某些时候无法插入条目(如front和rear索引线性递增的情况)(此问题通过使用循环队列解决)。
- When using an array to construct a queue, there may be occasions where we need to extend the queue to insert additional elements. Because it is nearly impossible to extend the array size when using an array to implement a queue, determining the suitable array size is always an issue.
125. List the advantages of using Tries over Binary Search Trees (BSTs).
列出使用Tries相比二叉搜索树(BST)的优势。
- 知识点: 算法与数据结构 (标签: interviewbit, capgemini, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Capgemini
- id: 69b379f058d557c902ba16f2 | 官方: 否 | 付费: 否
答案:
The advantages of Tries over binary search trees (BSTs) are as follows: - It's quicker to lookup keys. In the worst-case scenario, looking up a key of length m takes O(m) time. Because lockups are dependent on the depth of the tree, which is logarithmic in the number of keys if the tree is balanced, a BST does O(log n) key comparisons, where n is the number of items in the tree. As a result, a BST takes O(m log n) time in the worst scenario. Furthermore, log(n) will approach m in the worst-case scenario. Also, on real processors, the simple actions Tries utilize during lookup, such as array indexing with a character, are quick.
Tries相比二叉搜索树(BST)的优势如下:- 查找键更快。在最坏情况下,查找长度为m的键需要O(m)时间。由于查找依赖于树的深度,如果树是平衡的,深度与键数量成对数关系,BST进行O(log n)次键比较,其中n是树中的项数。因此,在最坏情况下,BST需要O(m log n)时间。此外,在最坏情况下,log(n)将接近m。而且,在实际处理器上,Tries在查找过程中使用的简单操作,如使用字符进行数组索引,非常快速。
- Because nodes are shared between keys with common starting sub-sequences, tries with a large number of short keys are more space-efficient.
- Tries facilitate longest-prefix matching, assisting in the discovery of the key with the longest possible prefix of characters, all of which are unique.
- The length of the key is equal to the number of internal nodes from root to leaf. As a result, balancing the tree isn't an issue.
126. Write a program to create a stack using a linked list in Java.
编写一个程序,在Java中使用链表创建栈。
- 知识点: 算法与数据结构 (标签: interviewbit, cisco, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Cisco
- id: 69b37a1258d557c902ba2c86 | 官方: 否 | 付费: 否
答案:
We can easily implement a stack using the linked list. A stack will have a top pointer which is the “head” of the stack where the item will be pushed and popped at the head of the list. The link field of the first node will be null and the link field of the second field will have the address of the first node and so on and the address of the last node will be stored in the “top” pointer.
我们可以轻松地使用链表实现栈。栈将有一个top指针,它是栈的“头部”,项目将在列表头部进行推入和弹出。第一个节点的链接字段将为null,第二个节点的链接字段将包含第一个节点的地址,依此类推,最后一个节点的地址将存储在“top”指针中。
The major advantage of linked list usage over an array is we can implement a stack that can grow or shrink according to the need. As the array is of fixed size, it will lead to stack overflow by putting restrictions on the maximum capacity of an array. In the linked list, each new node will be allocated dynamically, so overflow will not occur.
使用链表而非数组的主要优点是,我们可以实现一个能够根据需要增长或缩小的堆栈。由于数组大小固定,限制数组的最大容量会导致堆栈溢出。在链表中,每个新节点都会动态分配,因此不会发生溢出。
Stack Operations are: - push() : This function will insert an element into the linked list which in turn will be added to the top node of Stack.
堆栈操作有:- push() : 该函数将一个元素插入链表,该元素随即被添加到堆栈的顶部节点。
- pop() : This function will return the top element from the Stack and the top pointer will be moved to the second node of Stack.
- peek(): This function will return the topmost element in the stack.
- display(): This function will print all the elements of Stack.
isEmpty(): It will return true if the Stack is empty otherwise it returns false.
// Java program// Java 程序
// Importing package
// 导入包
import static java.lang.System.exit;
import static java.lang.System.exit;
// Creating Stack using Linked list
// 使用链表创建堆栈
class StackLinkedlist
class StackLinkedlist
{
// A node of linked list
// 链表的一个节点
private class Node
private class Node
{
// Integer data
// 整数数据
int info;
int info;
// Reference variable of Node type
// Node类型的引用变量
Node link;
Node link;
}
// Creating a global top reference variable
// 创建全局顶部引用变量
Node top;
Node top;
// Constructor
// 构造函数
StackLinkedlist()
StackLinkedlist()
{
this.top = null;
this.top = null;
}
// Function for adding an element i in the stack
// 用于在栈中添加元素i的函数
public void push(int i) // Insert at the beginning
public void push(int i) // 在开头插入
{
// Creating a new node t and allocate memory
// 创建新节点t并分配内存
Node t = new Node();
Node t = new Node();
/* Checking if the stack is full, then inserting an
/* 检查栈是否已满,如果已满则插入
element would lead to stack overflow*/
元素会导致栈溢出*/
if (t == null) {
if (t == null) {
System.out.print("\nStack Overflow");
System.out.print("\n栈溢出");
return;
return;
}
// Initializing data into info field of t node
// 将数据初始化到t节点的info字段中
t.info = i;
t.info = i;
// Add top reference into link field of t node
// 将top引用添加到t节点的link字段中
t.link = top;
t.link = top;
// Update top reference
// 更新top引用
top = t;
top = t;
}
// Function for checking if the stack is empty or not
// 用于检查栈是否为空的函数
public boolean isEmpty()
public boolean isEmpty()
{
return top == null;
return top == null;
}
// Function for returning topmost element of a stack
// 用于返回栈顶元素的函数
public int peek()
public int peek()
{
// Checking for empty stack
// 检查栈是否为空
if (!isEmpty())
if (!isEmpty())
{
return top.info;
return top.info;
}
else
else
{
System.out.println("Stack is empty");
System.out.println("Stack is empty");
return -1;
return -1;
}
}
// Function to pop the topmost element from the stack
// 从栈中弹出栈顶元素的函数
public void pop()
public void pop()
{
// Checking for stack underflow
// 检查栈下溢
if (top == null)
if (top == null)
{
System.out.print("\nStack Underflow");
System.out.print("\n栈下溢");
return;
return;
}
// Updating the top pointer to point to the next node
// 更新顶部指针以指向下一个节点
top = (top).link;
top = (top).link;
}
public void show()
public void show()
{
// Checking for stack underflow
// 检查栈下溢
if (top == null)
if (top == null)
{
System.out.printf("\nStack Underflow");
System.out.printf("\n栈下溢");
exit(1);
exit(1);
}
else
else
{
Node tmp = top;
Node tmp = top;
while (tmp != null)
while (tmp != null)
{
// Printing node data
// 打印节点数据
System.out.printf("%d->", tmp.info);
System.out.printf("%d->", tmp.info);
// Assigning tmp link to tmp node
// 将 tmp 的链接赋值给 tmp 节点
tmp = tmp.link;
tmp = tmp.link;
}
}
}
}
//Class with main() function
// 包含main()函数的类
public class ImplementStack
public class ImplementStack
{
public static void main(String[] args)
public static void main(String[] args)
{
// Creating object for the StackLinkedList class
// 为StackLinkedList类创建对象
StackLinkedlist ob = new StackLinkedlist();
StackLinkedlist ob = new StackLinkedlist();
// Inserting values for stack
// 为栈插入值
ob.push(15);
ob.push(15);
ob.push(20);
ob.push(20);
ob.push(25);
ob.push(25);
ob.push(30);
ob.push(30);
// Printing elements of Stack
// 打印栈的元素
ob.display();
ob.display();
// Printing Top element of Stack
// 打印栈顶元素
System.out.printf("\nTop element of Stack is %d\n", ob.peek());
System.out.printf("\n栈顶元素是 %d\n", ob.peek());
// Deleting top element of the Stack
// 删除栈的顶部元素
ob.pop();
ob.pop();
ob.pop();
ob.pop();
// Printing Stack elements
// 打印栈元素
ob.show();
ob.show();
// Printing Top element of Stack
// 打印栈顶元素
System.out.printf("\nTop element of Stack is %d\n", ob.peek());
System.out.printf("\n栈顶元素是 %d\n", ob.peek());
}
}
Output:
输出:
30->25->20->15->
Top element of Stack is 30
栈顶元素是 30
20->15->
Top element of Stack is 20
栈顶元素是 20
127. What is stored in each of the memory structures- stack and heap, and how are they related to each other?
每个内存结构(栈和堆)中存储了什么,它们之间有何关系?
- 知识点: 算法与数据结构 (标签: interviewbit, cognizant, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Cognizant
- id: 69b37a3058d557c902ba3fdb | 官方: 否 | 付费: 否
答案:
The stack is a section of memory that stores information about nested method (recursive) calls all the way down to the present program location. It also holds all local variables and heap references defined in the currently running procedures. This structure enables the runtime to return from the method knowing the address from which it was invoked, as well as to remove all local variables when the procedure has been exited. Every thread has a stack of its own.
栈是内存的一个区域,存储关于嵌套方法(递归)调用直至当前程序位置的信息。它还保存当前运行过程中定义的所有局部变量和堆引用。这种结构使运行时能够从方法中返回,并知道调用它的地址,以及在过程退出时移除所有局部变量。每个线程都有自己的栈。
The heap is a big chunk of memory used for dynamic allocation. When you use the new keyword to create an object, it is allocated on the heap. The reference to this object, on the other hand, is stored on the stack.
堆是用于动态分配的一大块内存。当你使用 new 关键字创建对象时,它会被分配到堆上。然而,对该对象的引用则存储在栈上。
128. List the differences between RSA (Rivest, Shamir, Adleman) and Digital Signature Algorithm (DSA).
列出 RSA(Rivest, Shamir, Adleman)和数字签名算法(DSA)之间的区别。
- 知识点: 算法与数据结构 (标签: interviewbit, cognizant, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Cognizant
- id: 69b37a3058d557c902ba3fe7 | 官方: 否 | 付费: 否
答案:
| RSA | DSA |
|---|---|
| RSA is a cryptosystem algorithm. RSA 是一种密码系统算法。 | DSA is a digital signature algorithm. DSA 是一种数字签名算法。 |
| This algorithm finds its application in secure data transmission. 该算法应用于安全数据传输。 | This algorithm finds its application in digital signature and its verification. 该算法应用于数字签名及其验证。 |
| It implements the mathematical concept of factorization of the product of two large prime numbers. 它实现了两个大素数乘积的因式分解的数学概念。 | It implements the concept of modular exponentiation and discrete logarithm. 它实现了模幂运算和离散对数的概念。 |
| RSA is slower in key generation as compared to DSA. RSA 在密钥生成方面比 DSA 慢。 | DSA is faster in key generation as compared to RSA. DSA 在密钥生成方面比 RSA 快。 |
| RSA is faster in encryption but slower in decryption as compared to DSA. RSA 在加密方面比 DSA 快,但在解密方面较慢。 | DSA is slower in encryption but faster in decryption as compared to RSA. DSA 在加密方面比 RSA 慢,但在解密方面较快。 |
129. What are the similarities and the differences between Shortest Job FIrst (SJF) and Shortest Remaining TIme FIrst (SRTF) CPU scheduling algorithms?
最短作业优先(SJF)和最短剩余时间优先(SRTF)CPU 调度算法之间有哪些相似之处和区别?
- 知识点: 算法与数据结构 (标签: interviewbit, cognizant, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Cognizant
- id: 69b37a3158d557c902ba4005 | 官方: 否 | 付费: 否
答案:
SJF (Shortest Job First) is a scheduling policy that prioritizes the waiting process with the shortest execution time. Shortest Job Next (SJN) or Shortest Process Next are other names for it (SPN). It is a scheduling algorithm that is not preemptive (that is, one process cannot snatch the resources assigned to a currently running process).
SJF(最短作业优先)是一种调度策略,优先处理执行时间最短的等待进程。它也被称为最短作业优先算法(SJN)或最短进程优先算法(SPN)。它是一种非抢占式调度算法(即,一个进程不能抢占分配给当前正在运行进程的资源)。
The preemptive variant of SJF scheduling is the Shortest Remaining Time First (SRTF). The procedure, next in the queue, with the least amount of time till completion is chosen to be executed in this scheduling technique. Processes that arrive at the same time transform SRTF to SJF.
SJF 调度的抢占式变体是最短剩余时间优先(SRTF)。在此调度技术中,选择队列中下一个完成时间最短的进程执行。同时到达的进程会将 SRTF 转换为 SJF。
Similarities: - Both SJF and SRTF are essentially difficult to implement since the processes' burst time cannot be predicted.
相似之处:- SJF和SRTF本质上都难以实现,因为进程的突发时间无法预测。
- Both SJF and SRTF have the potential to cause process starvation since long processes can be delayed forever if short processes are constantly added.
Once all of the processes are in the ready queue, both SJF and SRTF are regarded the same. This is because no preemption is performed after the processes are added to the ready queue.
Shortest Job First
最短作业优先Shortest Remaining Time First
最短剩余时间优先SJF is a non-preemptive algorithm.
SJF是一种非抢占式算法。SRTF is a preemptive algorithm.
SRTF是一种抢占式算法。SJF involves less overheads than SRTF.
SJF比SRTF开销更少。SRTF involves more overhead than SJF.
SRTF比SJF开销更多。SJF results in comparatively lower throughput.
SJF导致的吞吐量相对较低。SRTF results in increased throughput as execution is faster.
SRTF因执行更快而增加吞吐量。SJF reduces the average waiting time for each process.
SJF减少了每个进程的平均等待时间。SRTF may or may not reduce the average waiting time for each process.
SRTF可能减少也可能不减少每个进程的平均等待时间。SJF involves a lesser number of context switching.
SJF涉及的上下文切换次数较少。SRTF involves a greater number of context switching.
SRTF涉及的上下文切换次数较多。
130. What factors influence whether or not a detection algorithm is required in a deadlock avoidance system?
在死锁避免系统中,哪些因素影响是否需要检测算法?
- 知识点: 算法与数据结构 (标签: interviewbit, cognizant, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Cognizant
- id: 69b37a3158d557c902ba4008 | 官方: 否 | 付费: 否
答案:
One of the factors is that it is dependent on how frequently a deadlock is likely to occur when this algorithm is implemented. The other is the number of processes that will be affected by deadlock if this algorithm is used.
其中一个因素是它取决于实现该算法时死锁可能发生的频率。另一个因素是如果使用此算法,死锁将影响多少个进程。
131. Explain the computer system?
解释一下计算机系统?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba511a | 官方: 否 | 付费: 否
答案:
The computer system is the collection of hardware and software that makes up a computer. It consists of the processor, memory, storage devices, input/output devices, and other components. - The processor is the central processing unit (CPU) that processes information and controls the computer’s operations.
计算机系统是组成计算机的硬件和软件的集合。它包括处理器、内存、存储设备、输入/输出设备和其他组件。- 处理器是中央处理单元(CPU),负责处理信息并控制计算机的操作。
- The memory is the computer’s temporary storage area.
- The storage devices are used to store data and programs.
- The input/output devices are used to connect the computer to external devices such as printers, keyboards, and mice.
- The computer system is a complex device that has many functions. It is used to store and process information, communicate with other computers and other devices, and perform calculations.
132. What is a file?
什么是文件?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba511d | 官方: 否 | 付费: 否
答案:
A file is a collection of data that is stored on a computer or other device. Files can be text, images, sounds, or any combination of these. They can be stored on a computer, a hard drive, or some other device. When you open a file, you are actually opening a copy of the data inside the file. This copy is called the “file” and it is what you see when you open the file. The file can be opened in many different ways. For example, you can open it by clicking on it or by double-clicking on it. The file can also be opened by dragging and dropping it onto the screen or by using other methods. When you open a file, you are actually opening a copy of the data inside the file.
文件是存储在计算机或其他设备上的数据集合。文件可以是文本、图像、声音或这些的任意组合。它们可以存储在计算机、硬盘或其他设备上。当你打开文件时,实际上是在打开文件内部数据的副本。这个副本被称为“文件”,是你打开文件时看到的内容。文件可以通过多种不同方式打开。例如,你可以通过单击或双击打开它。文件也可以通过拖放到屏幕上或其他方法打开。当你打开文件时,实际上是在打开文件内部数据的副本。
133. What is a chipset?
什么是芯片组?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba5123 | 官方: 否 | 付费: 否
答案:
A chipset is a collection of circuit boards and other components that are used to connect a computer to the rest of the world. Chipsets are typically used to connect computers to the internet, printers, scanners, and other peripherals. Chipsets are also used to provide a way for computers to communicate with each other. For example, a chipset might be used to connect a computer to a printer or scanner. A chipset might also be used to communicate with other computers over the internet. Sockets are the most common type of chipset.
芯片组是用于将计算机与外界连接的电路板和其他组件的集合。芯片组通常用于将计算机连接到互联网、打印机、扫描仪和其他外围设备。芯片组还用于提供计算机之间相互通信的方式。例如,芯片组可能用于将计算机连接到打印机或扫描仪。芯片组也可能用于通过互联网与其他计算机通信。插槽是最常见的芯片组类型。
134. What is an operating system?
什么是操作系统?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba5126 | 官方: 否 | 付费: 否
答案:
An operating system is a collection of software that runs on a computer and provides the basic functions of storing and managing information, such as memory, storage devices, and network access. The operating system controls how the computer works and how it interacts with other software and hardware. For example, an operating system can control the way a computer stores and accesses data, such as files and printers. In addition to controlling how the computer works and operating system can also provide many other functions, such as security, communication, and user interface. An operating system can also be used to develop new software applications.
操作系统是运行在计算机上并提供存储和管理信息基本功能(如内存、存储设备和网络访问)的软件集合。操作系统控制计算机的工作方式以及它与其他软件和硬件的交互方式。例如,操作系统可以控制计算机存储和访问数据(如文件和打印机)的方式。除了控制计算机工作方式外,操作系统还可以提供许多其他功能,如安全性、通信和用户界面。操作系统也可以用于开发新的软件应用程序。
135. How many popular operating systems are in use today?
当今使用多少种流行的操作系统?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba5129 | 官方: 否 | 付费: 否
答案:
Operating systems are the software that controls the way a computer works. There are many different operating systems out there, and they all have different features and benefits. The most popular operating systems today are Windows, Mac OS, and Linux. Windows is the most popular because it is the most widely used operating system. It is also the most expensive, but it is also the most secure. Mac OS is another popular operating system that is easy to use and has a lot of features. Linux is a very popular operating system that is free and open-source, which means that anyone can use it. Linux is also very easy to use, so it is great for beginners.
操作系统是控制计算机工作方式的软件。市面上有许多不同的操作系统,它们都有不同的功能和优势。当今最流行的操作系统是 Windows、Mac OS 和 Linux。Windows 最受欢迎,因为它是最广泛使用的操作系统。它也是最昂贵的,但也是最安全的。Mac OS 是另一个流行的操作系统,易于使用且功能丰富。Linux 是一个非常流行的操作系统,它是免费且开源的,这意味着任何人都可以使用它。Linux 也非常易于使用,因此非常适合初学者。
136. What is a microprocessor?
什么是微处理器?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba512c | 官方: 否 | 付费: 否
答案:
A microprocessor is a computerized device that is small enough to fit in a computer’s memory. Microprocessors are used in many different kinds of devices, including computers, cell phones, and industrial robots. Microprocessors are very important because they allow computers to perform many different tasks. For example, microprocessors are used to control the flow of electricity in a computer. They also help computers store and retrieve information. Microprocessors are also used to create new products. For example, microprocessors are used to create new types of computers. They are also used to create new types of robots.
微处理器是一种小到可以放入计算机内存中的计算机化设备。微处理器用于多种不同设备,包括计算机、手机和工业机器人。微处理器非常重要,因为它们使计算机能够执行许多不同任务。例如,微处理器用于控制计算机中的电流流动。它们还帮助计算机存储和检索信息。微处理器还用于创造新产品。例如,微处理器用于创造新型计算机。它们也用于创造新型机器人。
137. What is a class variable?
什么是类变量?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba512f | 官方: 否 | 付费: 否
答案:
A class variable is a variable that is defined in a class and shared by all instances of the class. Class variables can be used to store information about an object, such as its name, its location in memory, and its state at any given time. Class variables are often used to store information that is shared by objects in the same class. For example, a class might have a variable called name that is shared by all instances of the class. Class variables are often created with the special keyword class.
类变量是在类中定义并由该类的所有实例共享的变量。类变量可用于存储有关对象的信息,例如其名称、其在内存中的位置以及其在任何给定时间的状态。类变量通常用于存储同一类中对象共享的信息。例如,一个类可能有一个名为name的变量,该变量由类的所有实例共享。类变量通常使用特殊关键字class创建。
138. What is a Software Development Life Cycle?
什么是软件开发生命周期?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba5132 | 官方: 否 | 付费: 否
答案:
A software development life cycle (SDLC) is a process used to plan and manage the development of software. The SDLC is a set of activities that are performed over a period of time to ensure that the software is developed in a way that is efficient and effective. The SDLC can be divided into three phases: planning, design, and implementation. During the planning phase, the organization identifies the goals and objectives that need to be achieved. During the design phase, the organization identifies the requirements for the software that will be developed. During the implementation phase, the organization prepares the software for production and tests it to ensure that it meets all of its requirements. The SDLC is an important part of any software development process because it ensures that the software is developed in a way that is efficient and effective.
软件开发生命周期(SDLC)是用于规划和管理软件开发的过程。SDLC是一系列在一段时间内执行的活动,以确保软件以高效且有效的方式开发。SDLC可分为三个阶段:规划、设计和实施。在规划阶段,组织确定需要实现的目标和目的。在设计阶段,组织确定将要开发的软件的需求。在实施阶段,组织准备软件进行生产并测试其是否满足所有需求。SDLC是任何软件开发过程的重要组成部分,因为它确保软件以高效且有效的方式开发。
139. What is a programming language?
什么是编程语言?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b37a4d58d557c902ba5135 | 官方: 否 | 付费: 否
答案:
A programming language is a computer language designed to facilitate the creation of software. It is a set of rules and guidelines that govern the structure and format of computer programs. A programming language is typically a high-level language that abstracts away the complexities of programming in order to make it easier for programmers to understand and write code. There are many different programming languages, including C, C++, Java, and Python. The most popular programming languages today are C++ and Java. C++ is a high-level language that abstracts away the complexities of programming in order to make it easier for programmers to understand and write code.
编程语言是一种旨在促进软件创建的计算机语言。它是一套管理计算机程序结构和格式的规则和指南。编程语言通常是高级语言,它抽象了编程的复杂性,以便程序员更容易理解和编写代码。有许多不同的编程语言,包括C、C++、Java和Python。当今最流行的编程语言是C++和Java。C++是一种高级语言,它抽象了编程的复杂性,以便程序员更容易理解和编写代码。
140. What is Integrated Development Environment?
什么是集成开发环境?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba5138 | 官方: 否 | 付费: 否
答案:
An integrated development environment (IDE) is a software tool that allows developers to create, edit, and debug their software in a single interface. IDEs are typically used by software developers who work on large projects. IDEs are typically used to create and edit source code, as well as to debug and test programs. IDEs are also used to create documentation, as well as to share code between different teams. IDEs are typically used to create and edit source code, as well as to debug and test programs. IDEs also allow developers to create and edit documentation.
集成开发环境(IDE)是一种软件工具,允许开发人员在单个界面中创建、编辑和调试其软件。IDE通常由从事大型项目的软件开发人员使用。IDE通常用于创建和编辑源代码,以及调试和测试程序。IDE也用于创建文档,以及在不同团队之间共享代码。IDE通常用于创建和编辑源代码,以及调试和测试程序。IDE还允许开发人员创建和编辑文档。
141. Explain the framework in software development?
解释软件开发中的框架?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba513b | 官方: 否 | 付费: 否
答案:
A framework is a collection of reusable components that can be used to build software. Frameworks are often used to structure large projects and to help teams work together. Frameworks are usually built using a set of reusable components. These components can be used to build different types of software, such as web applications, desktop applications, and mobile apps. A framework can be used to structure large projects and to help teams work together. A framework can also be used to help teams understand the different stages of software development. For example, a framework can help teams understand the different stages of software development when building web applications.
框架是可重用组件的集合,可用于构建软件。框架通常用于构建大型项目并帮助团队协作。框架通常使用一组可重用组件构建。这些组件可用于构建不同类型的软件,例如Web应用程序、桌面应用程序和移动应用程序。框架可用于构建大型项目并帮助团队协作。框架也可用于帮助团队理解软件开发的各个阶段。例如,框架可以帮助团队在构建Web应用程序时理解软件开发的各个阶段。
142. What is an Interface?
什么是接口?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba513e | 官方: 否 | 付费: 否
答案:
An interface is a way of communicating between two objects. The objects can be software or hardware. An interface can be defined in many different ways, but the most common definition is that it is a way for one object to talk to another object. This communication can take many different forms, such as sending data to the other object, receiving data from the other object, or both. An interface can be implemented in many different ways, but the most common way is to use a software class. This class defines the interface and then other classes can use this class to implement the interface. When an object uses an interface, it is saying that it understands how the interface works and can use it to communicate with other objects.
接口是两个对象之间进行通信的方式。这些对象可以是软件或硬件。接口可以以多种不同方式定义,但最常见的定义是它是一种让一个对象与另一个对象交谈的方式。这种通信可以采取多种不同形式,例如向其他对象发送数据、从其他对象接收数据,或两者兼有。接口可以以多种不同方式实现,但最常见的方式是使用软件类。此类定义接口,然后其他类可以使用此类来实现接口。当对象使用接口时,它表示理解接口的工作原理并可以使用它与其他对象进行通信。
143. What is an abstract class?
什么是抽象类?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba5141 | 官方: 否 | 付费: 否
答案:
An abstract class is a class that is not defined in the source code. Instead, it is defined in a file that contains a definition of the class. The file defines the class by defining all of the properties and methods of the class. However, the class does not have to be defined in the source code. Instead, it can be defined in a separate file that is included in the source code. The file can then be referenced by the source code. This allows the class to be abstract and still be defined in the source code. The main advantage of an abstract class is that it allows other classes to use the class without having to know all of its properties and methods. This makes it possible for other classes to use a class without knowing all of its properties and methods.
抽象类是一个未在源代码中定义的类。相反,它定义在包含类定义的文件中。该文件通过定义类的所有属性和方法来定义类。但是,该类不必在源代码中定义。相反,它可以定义在包含在源代码中的单独文件中。然后源代码可以引用该文件。这允许类成为抽象的,并且仍然在源代码中定义。抽象类的主要优点是它允许其他类使用该类,而不必知道其所有属性和方法。这使得其他类可以在不知道其所有属性和方法的情况下使用该类。
144. What is an array?
什么是数组?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba5144 | 官方: 否 | 付费: 否
答案:
An array is a data structure that can hold a lot of data. Arrays are used in a lot of different applications, such as databases, spreadsheets, and games. Arrays are made up of different data types, such as numbers, strings, and characters. Arrays are also called indexed structures because they can be accessed by indexing. Arrays are one of the most important data structures in programming. They are used to store data in a way that is easy to access and to organize it in a way that makes sense. Arrays are also used in many different applications, such as databases, spreadsheets, and games. An array is a data structure that can hold a lot of data. Arrays are used in a lot of different applications, such as databases, spreadsheets, and games.
数组是一种可以容纳大量数据的数据结构。数组用于许多不同的应用程序,例如数据库、电子表格和游戏。数组由不同的数据类型组成,例如数字、字符串和字符。数组也称为索引结构,因为它们可以通过索引进行访问。数组是编程中最重要的数据结构之一。它们用于以易于访问的方式存储数据,并以合乎逻辑的方式组织数据。数组也用于许多不同的应用程序,例如数据库、电子表格和游戏。数组是一种可以容纳大量数据的数据结构。数组用于许多不同的应用程序,例如数据库、电子表格和游戏。
145. What is a constructor?
什么是构造函数?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba5147 | 官方: 否 | 付费: 否
答案:
A constructor is a function that is called when an object is created. A constructor is a function that takes a few arguments the type of object to be created, the initial state of the object, and the name of the class that will contain the object. When an object is created, it is passed to the constructor of the class that contains the object. A constructor can be used in many different ways. For example, a constructor can be used to initialize an array of objects or to initialize a variable that will be used by multiple objects. In these cases, it is important to use a constructor that takes only a few arguments.
构造函数是在创建对象时被调用的函数。构造函数接收几个参数:要创建的对象类型、对象的初始状态以及包含对象的类名。当对象被创建时,它会被传递给包含该对象的类的构造函数。构造函数可以以多种不同方式使用。例如,构造函数可用于初始化对象数组,或初始化将被多个对象使用的变量。在这些情况下,使用只接收少量参数的构造函数非常重要。
146. Define Cin and Cout in C++?
在C++中定义Cin和Cout?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba514a | 官方: 否 | 付费: 否
答案:
Cin and cout are two important functions in C++ that you should know about. Cin and cout are functions that allow you to read and write data to a stream. The basic syntax of cin and cout is as follows: - cin(stream) - Read data from the stream.
Cin和cout是C++中你应该了解的两个重要函数。Cin和cout是允许你向流中读取和写入数据的函数。cin和cout的基本语法如下:- cin(stream) - 从流中读取数据。
- cin(stream, value) - Read data from the stream and assign a value to the variable.
- cout(stream) - Write data to the stream.
cout(stream, value) - Write data to the stream and assign a value to the variable.
The first function cin takes a stream as an argument and reads data from the stream. The second function cout takes a stream as an argument and writes data to the stream. You can use cin and cout to read and write data from a file, a database, or any other source of data.第一个函数cin将流作为参数,并从流中读取数据。第二个函数cout将流作为参数,并向流中写入数据。你可以使用cin和cout从文件、数据库或任何其他数据源读写数据。
147. What is machine learning?
什么是机器学习?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba5151 | 官方: 否 | 付费: 否
答案:
Machine learning is a field of computer science that deals with the identification and analysis of patterns in data. Machine learning algorithms can be used to identify patterns in data, such as relationships between variables, or to make predictions based on those relationships. Machine learning algorithms can be divided into two broad categories: supervised and unsupervised. Supervised machine learning algorithms, such as classification and regression, are used to identify patterns in data. Unsupervised machine learning algorithms, such as clustering and association analysis, are used to identify associations between variables. The most common supervised machine learning algorithms are classification and regression.
机器学习是计算机科学的一个领域,涉及数据中模式的识别和分析。机器学习算法可用于识别数据中的模式,例如变量之间的关系,或基于这些关系进行预测。机器学习算法可分为两大类:监督学习和无监督学习。监督学习算法(如分类和回归)用于识别数据中的模式。无监督学习算法(如聚类和关联分析)用于识别变量之间的关联。最常见的监督学习算法是分类和回归。
148. What are the different OOPS principles?
不同的OOPS原则有哪些?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba5159 | 官方: 否 | 付费: 否
答案:
OOPS, principles are a set of rules and guidelines that organizations can use to ensure that their software is as bug-free as possible. The OOPS principles are:
OOPS原则是一组规则和指南,组织可以使用它们来确保其软件尽可能无缺陷。OOPS原则包括:
Open source- All software should be released under an open-source license, such as the GNU General Public License (GPL) or the Apache License. 2. Patent- All software should be released with a patent waiver, such as the USPTO's Patent Promise or the EU's EPO. 3. Quality- All software should be developed using quality-assured tools and practices, such as unit testing and code reviews. 4. Simplicity- All software should be easy to understand and maintain, and should not require complex configuration or customization. 5. Reuse- All software should be reusable so that it can be adapted to new needs without requiring a complete rewrite. 6. Simplicity- All software should be easy to understand and maintain, and should not require complex configuration or customization.
- 开源- 所有软件都应基于开源许可证发布,如GNU通用公共许可证(GPL)或Apache许可证。 2. 专利- 所有软件都应附带专利豁免发布,如美国专利商标局的专利承诺或欧盟的EPO。 3. 质量- 所有软件都应使用质量保证的工具和做法开发,如单元测试和代码审查。 4. 简洁- 所有软件都应易于理解和维护,并且不应要求复杂配置或定制。 5. 重用- 所有软件都应可重用,以便无需完全重写即可适应新需求。 6. 简洁- 所有软件都应易于理解和维护,并且不应要求复杂配置或定制。
149. Explain the access modifiers?
解释访问修饰符?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba515c | 官方: 否 | 付费: 否
答案:
Access modifiers are a way of specifying which users have access to a resource. Access modifiers are often used to control access to data, files, or other resources. For example, a database might allow only certain users to see the data. Or, a file might be locked down so that only the owner can see it.
访问修饰符是指定哪些用户可以访问资源的一种方式。访问修饰符通常用于控制对数据、文件或其他资源的访问。例如,数据库可能只允许某些用户查看数据。或者,文件可能被锁定,以便只有所有者才能查看它。
150. What do you mean by destructor?
析构函数是什么意思?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba515f | 官方: 否 | 付费: 否
答案:
A destructor is a function that is called when an object is destroyed. A destructor is a way to clean up after an object has been destroyed. When an object is destroyed, the memory associated with the object is released. When an object is created, the memory associated with the object is allocated. The destructor is called when the memory associated with the object is no longer needed. The destructor frees up the memory associated with the object and releases it into the environment. When an object is destroyed, it can be very difficult to find out why an object was destroyed.
析构函数是在对象被销毁时被调用的函数。析构函数是在对象被销毁后进行清理的一种方式。当对象被销毁时,与该对象关联的内存被释放。当对象被创建时,与该对象关联的内存被分配。当与该对象关联的内存不再需要时,会调用析构函数。析构函数释放与该对象关联的内存并将其释放到环境中。当对象被销毁时,可能很难找出对象被销毁的原因。
151. What are the Layers of the OSI Model?
OSI模型的层有哪些?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba5162 | 官方: 否 | 付费: 否
答案:
The OSI model is a system-level networking model that describes the topology of a network. The model consists of seven layers: Physical, Data Link, Transport, Network, Application, and Management. Each layer is responsible for providing a specific function. For example, the Physical layer provides connectivity between devices and the Data Link layer is responsible for data transmission. The Transport layer is responsible for routing data and the Network layer is responsible for managing the network. The Application layer is responsible for providing services to the devices on the network and the Management layer is responsible for managing the network. Each layer in the OSI model has a specific purpose and each layer in the OSI model has a specific role to play in the overall system.
OSI模型是一个系统级网络模型,描述了网络的拓扑结构。该模型由七层组成:物理层、数据链路层、传输层、网络层、应用层和管理层。每一层负责提供特定功能。例如,物理层提供设备之间的连接,数据链路层负责数据传输。传输层负责路由数据,网络层负责管理网络。应用层负责向网络上的设备提供服务,管理层负责管理网络。OSI模型中的每一层都有特定目的,OSI模型中的每一层在整个系统中都有特定角色。
152. What is the thread in programming?
编程中的线程是什么?
- 知识点: 算法与数据结构 / 行为与软技能 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: behavioral | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b37a4d58d557c902ba5165 | 官方: 否 | 付费: 否
答案:
The thread is a fundamental concept in programming. It is a way of organizing and managing code so that it can run in parallel. The thread is a way of keeping code running in the background while the main program is running. Threads are used to parallelize tasks and to share resources among multiple threads. When the main program runs, it sends instructions to the thread that is running the task. When the task is done, the thread that was running the task sends instructions to the main program that is waiting for instructions. This process continues until all tasks are done or until one of them crashes or gets interrupted. Threads are a fundamental concept in programming because they allow programs to run in parallel and to share resources. They are also useful for managing memory and CPU usage.
线程是编程中的一个基本概念。它是一种组织和管理代码的方式,以便代码能够并行运行。线程是在主程序运行的同时让代码在后台继续运行的一种方式。线程用于并行化任务以及在多个线程之间共享资源。当主程序运行时,它会向正在执行任务的线程发送指令。当任务完成时,正在运行该任务的线程会向等待指令的主程序发送指令。此过程持续进行,直到所有任务完成或其中一个任务崩溃或被中断。线程是编程中的一个基本概念,因为它们允许程序并行运行并共享资源。它们还对于管理内存和CPU使用率非常有用。
153. What are Polymorphism, Inheritance, and Dynamic Programming?
什么是多态、继承和动态规划?
- 知识点: 算法与数据结构 (标签: interviewbit, dassault-systemes, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: 达索系统
- id: 69b37a5b58d557c902ba5bd5 | 官方: 否 | 付费: 否
答案:
"Polymorphism", "Inheritance" and "Dynamic Programming" are all important concepts in computer science and object-oriented programming.
“多态”、“继承”和“动态规划”都是计算机科学和面向对象编程中的重要概念。
- Polymorphism: Polymorphism refers to the ability of an object to take on many forms. In object-oriented programming, polymorphism allows objects of different types to be treated as objects of a common base type. Polymorphism can be implemented through the use of virtual functions or interfaces, allowing a single function or method call to be directed to different implementations depending on the type of object being called.
Consider the above image, We have a circle, square, and rectangle. So we can also call the circle a “Shape”. Similarly, the square is also a “shape”. Same for rectangles. It is an example of polymorphism (One name in many forms).
考虑上面的图片,我们有一个圆形、正方形和矩形。所以我们可以把圆形也叫做“形状”。同样,正方形也是“形状”。矩形也是一样。这是多态的一个例子(一个名字有多种形式)。
- Inheritance: Inheritance is a mechanism by which one class can inherit the properties and methods of another class. This allows for the creation of a class hierarchy in which a derived class inherits the properties and methods of a base class and can add new properties and methods of its own. It also allows for code reuse, as the derived class can inherit the implementation of the base class and override it if necessary.
Consider the above image, there is a “Vehicle” that we can drive. Now, suppose there is a truck that is also a vehicle and has an additional feature that we can carry the load in it. Same with “Car” and “Bike”, which have the feature for driving. Also, it has a seating capacity. So we can say that Trucks, Cars, and Bikes are inheriting features of Driving from the parent class “Vehicle” and have their feature of Seating Capacity and Carry Load. It is an example of Inheritance.
考虑上面的图片,有一个我们可以驾驶的“车辆”。现在,假设有一辆卡车,它也是车辆,并且有一个额外功能,即可以在其中装载货物。“汽车”和“摩托车”也是如此,它们具有驾驶的功能。此外,它还有座位容量。所以我们可以说,卡车、汽车和摩托车是从父类“车辆”继承驾驶功能,并具有自己的座位容量和装载货物功能。这是继承的一个例子。
- Dynamic Programming: Dynamic Programming is a method of solving complex problems by breaking them down into simpler subproblems and reusing solutions to these subproblems. The idea is to break down the problem into smaller and overlapping subproblems and store the solution of these subproblems to avoid redundant computation. This technique can be used to solve optimization and search problems, like the shortest path problem, knapsack problem, etc. It's worth noting that these concepts, while separate, are often used together in object-oriented programming. The inheritance mechanism often provides the mechanism for polymorphism, since a derived class can override the implementation of a base class's virtual function.
154. What are Data Structures?
什么是数据结构?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f79 | 官方: 否 | 付费: 否
答案:
A data structure is a mechanical or logical way that data is organized within a program. The organization of data is what determines how a program performs. There are many types of data structures, each with its own uses. When designing code, we need to pay particular attention to the way data is structured. If data isn't stored efficiently or correctly structured, then the overall performance of the code will be reduced.
数据结构是数据在程序中进行组织的一种机械或逻辑方式。数据的组织方式决定了程序的性能表现。数据结构有许多类型,每一种都有其各自的用途。在设计代码时,我们需要特别关注数据的组织方式。如果数据未高效存储或正确结构化,那么代码的整体性能将会降低。
155. Why Create Data Structures?
为什么要创建数据结构?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f7c | 官方: 否 | 付费: 否
答案:
Data structures serve a number of important functions in a program. They ensure that each line of code performs its function correctly and efficiently, they help the programmer identify and fix problems with his/her code, and they help to create a clear and organized code base.
数据结构在程序中发挥着若干重要功能。它们确保每一行代码正确高效地发挥其功能,它们帮助程序员识别和修复代码中的问题,并且它们有助于创建一个清晰且有组织的代码库。
156. What are some applications of Data structures?
数据结构有哪些应用?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f7f | 官方: 否 | 付费: 否
答案:
Following are some real-time applications of data structures:
以下是数据结构的几个实时应用:
- Decision Making
- Genetics
- Image Processing
- Blockchain
- Numerical and Statistical Analysis
- Compiler Design
- Database Design and many more
157. Explain the process behind storing a variable in memory.
解释在内存中存储变量的过程。
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f82 | 官方: 否 | 付费: 否
答案:
A variable is stored in memory based on the amount of memory that is needed. Following are the steps followed to store a variable:
The required amount of memory is assigned first.首先分配所需的内存数量。
Then, it is stored based on the data structure being used.
然后,根据所使用的基础数据结构进行存储。- Using concepts like dynamic allocation ensures high efficiency and that the storage units can be accessed based on requirements in real-time.
158. Can you explain the difference between file structure and storage structure?
你能解释文件结构和存储结构之间的区别吗?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f85 | 官方: 否 | 付费: 否
答案:
- File Structure: Representation of data into secondary or auxiliary memory say any device such as a hard disk or pen drives that stores data which remains intact until manually deleted is known as a file structure representation.
- Storage Structure: In this type, data is stored in the main memory i.e RAM, and is deleted once the function that uses this data gets completely executed.
The difference is that the storage structure has data stored in the memory of the computer system, whereas the file structure has the data stored in the auxiliary memory.
区别在于,存储结构是将数据存储在计算机系统的内存中,而文件结构是将数据存储在辅助存储器中。
159. Describe the types of Data Structures?
描述数据结构的类型?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f88 | 官方: 否 | 付费: 否
答案:
- Linear Data Structure: A data structure that includes data elements arranged sequentially or linearly, where each element is connected to its previous and next nearest elements, is referred to as a linear data structure. Arrays and linked lists are two examples of linear data structures.
- Non-Linear Data Structure: Non-linear data structures are data structures in which data elements are not arranged linearly or sequentially. We cannot walk through all elements in one pass in a non-linear data structure, as in a linear data structure. Trees and graphs are two examples of non-linear data structures.
160. What is a stack data structure? What are the applications of stack?
什么是栈数据结构?栈的应用有哪些?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f8b | 官方: 否 | 付费: 否
答案:
A stack is a data structure that is used to represent the state of an application at a particular point in time. The stack consists of a series of items that are added to the top of the stack and then removed from the top. It is a linear data structure that follows a particular order in which operations are performed. LIFO (Last In First Out) or FILO (First In Last Out) are two possible orders. A stack consists of a sequence of items. The element that's added last will come out first, a real-life example might be a stack of clothes on top of each other. When we remove the cloth that was previously on top, we can say that the cloth that was added last comes out first.
栈是一种用于表示应用程序在特定时间点状态的数据结构。栈由一系列项目组成,这些项目被添加到栈顶,然后从栈顶移除。它是一种线性数据结构,遵循执行操作的特定顺序。LIFO(后进先出)或FILO(先进后出)是两种可能的顺序。栈由一系列项目组成。最后添加的元素将最先出来,一个现实生活中的例子可能是叠放在一起的一堆衣服。当我们移除之前在上面的一件衣服时,我们可以说最后添加的衣服最先出来。
Following are some applications for stack data structure: - It acts as temporary storage during recursive operations
以下是栈数据结构的一些应用:- 它在递归操作期间充当临时存储
- Redo and Undo operations in doc editors
- Reversing a string
- Parenthesis matching
- Postfix to Infix Expressions
- Function calls order
161. What are different operations available in stack data structure?
栈数据结构中有哪些不同的可用操作?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f8e | 官方: 否 | 付费: 否
答案:
Some of the main operations provided in the stack data structure are: - push: This adds an item to the top of the stack. The overflow condition occurs if the stack is full.
栈数据结构提供的一些主要操作包括:- push:将一个元素添加到栈顶。如果栈已满,则会发生溢出条件。
- pop: This removes the top item of the stack. Underflow condition occurs if the stack is empty.
- top: This returns the top item from the stack.
- isEmpty: This returns true if the stack is empty else false.
- size: This returns the size of the stack.
162. What is a queue data structure? What are the applications of queue?
什么是队列数据结构?队列有哪些应用?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f91 | 官方: 否 | 付费: 否
答案:
A queue is a linear data structure that allows users to store items in a list in a systematic manner. The items are added to the queue at the rear end until they are full, at which point they are removed from the queue from the front. Queues are commonly used in situations where the users want to hold items for a long period of time, such as during a checkout process. A good example of a queue is any queue of customers for a resource where the first consumer is served first.
队列是一种线性数据结构,允许用户以系统的方式将项目存储在列表中。项目在队列的后端添加,直到队列满为止,此时它们会从队列的前端被移除。队列通常用于用户希望长时间保留项目的情况,例如结账过程。队列的一个典型例子是顾客排队等待某个资源,其中第一个消费者首先得到服务。
Following are some applications of queue data structure: - Breadth-first search algorithm in graphs
以下是队列数据结构的一些应用:- 图中的广度优先搜索算法
- Operating system: job scheduling operations, Disk scheduling, CPU scheduling etc.
- Call management in call centres
163. What are different operations available in queue data structure?
队列数据结构中有哪些不同的可用操作?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f94 | 官方: 否 | 付费: 否
答案:
- enqueue: This adds an element to the rear end of the queue. Overflow conditions occur if the queue is full.
- dequeue: This removes an element from the front end of the queue. Underflow conditions occur if the queue is empty.
- isEmpty: This returns true if the queue is empty or else false.
- rear: This returns the rear end element without removing it.
- front: This returns the front-end element without removing it.
- size: This returns the size of the queue.
164. Differentiate between stack and queue data structure.
区分栈和队列数据结构。
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f97 | 官方: 否 | 付费: 否
答案:
| Stack 栈 | Queue 队列 |
|---|---|
| Stack is a linear data structure where data is added and removed from the top. 栈是一种线性数据结构,数据从顶部添加和移除。 | Queue is a linear data structure where data is ended at the rear end and removed from the front. 队列是一种线性数据结构,数据在后端添加,并从前端移除。 |
| Stack is based on LIFO(Last In First Out) principle 栈基于后进先出(LIFO)原则 | Queue is based on FIFO(First In First Out) principle 队列基于先进先出(FIFO)原则 |
| Insertion operation in Stack is known as push. 栈中的插入操作称为push。 | Insertion operation in Queue is known as eneque. 队列中的插入操作称为enqueue。 |
| Delete operation in Stack is known as pop. 栈中的删除操作称为pop。 | Delete operation in Queue is known as dequeue. 队列中的删除操作称为dequeue。 |
| Only one pointer is available for both addition and deletion: top() 只有顶部指针可用于添加和删除:top() | Two pointers are available for addition and deletion: front() and rear() 有两个指针可用于添加和删除:front()和rear() |
| Used in solving recursion problems 用于解决递归问题 | Used in solving sequential processing problems 用于解决顺序处理问题 |
165. How to implement a queue using stack?
如何使用栈实现队列?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f9a | 官方: 否 | 付费: 否
答案:
A queue can be implemented using two stacks . Let q be the queue and stack1 and stack2 be the 2 stacks for implementing q . We know that stack supports push, pop, and peek operations and using these operations, we need to emulate the operations of the queue - enqueue and dequeue. Hence, queue q can be implemented in two methods (Both the methods use auxillary space complexity of O(n)):
可以使用两个栈来实现队列。设q为队列,stack1和stack2是实现q的两个栈。我们知道栈支持push、pop和peek操作,利用这些操作,我们需要模拟队列的操作——enqueue和dequeue。因此,队列q可以通过两种方法实现(两种方法都使用O(n)的辅助空间复杂度):
- By making enqueue operation costly:
- Here, the oldest element is always at the top of stack1 which ensures dequeue operation occurs in O(1) time complexity.
- To place the element at top of stack1, stack2 is used.
Pseudocode:
Enqueue: Here time complexity will be O(n)入队(Enqueue):这里的时间复杂度将为O(n)
enqueue(q, data):
入队(q, data):
While stack1 is not empty:
当 stack1 不为空时:
Push everything from stack1 to stack2.
将stack1中的所有内容推送到stack2。
Push data to stack1
将 data 压入 stack1
Push everything back to stack1.
将所有内容推回stack1。- Dequeue: Here time complexity will be O(1)
deQueue(q):
出队(q):
If stack1 is empty then error else
如果 stack1 为空则报错,否则
Pop an item from stack1 and return it
从 stack1 弹出一个元素并返回它
- By making the dequeue operation costly:
- Here, for enqueue operation, the new element is pushed at the top of stack1. Here, the enqueue operation time complexity is O(1).
- In dequeue, if stack2 is empty, all elements from stack1 are moved to stack2 and top of stack2 is the result. Basically, reversing the list by pushing to a stack and returning the first enqueued element. This operation of pushing all elements to a new stack takes O(n) complexity.
Pseudocode:
Enqueue: Time complexity: O(1)入队:时间复杂度:O(1)
enqueue(q, data):
入队(q, data):
Push data to stack1
将 data 压入 stack1- Dequeue: Time complexity: O(n)
dequeue(q):
出队(q):
If both stacks are empty then raise error.
如果两个栈都为空则抛出错误。
If stack2 is empty:
如果 stack2 为空:
While stack1 is not empty:
当 stack1 不为空时:
push everything from stack1 to stack2.
将 stack1 中的所有元素压入 stack2。
Pop the element from stack2 and return it.
从 stack2 弹出元素并返回它。
166. How do you implement stack using queues?
如何使用队列实现栈?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b37a5f58d557c902ba5f9d | 官方: 否 | 付费: 否
答案:
- A stack can be implemented using two queues. We know that a queue supports enqueue and dequeue operations. Using these operations, we need to develop push, pop operations.
- Let stack be ‘s’ and queues used to implement be ‘q1’ and ‘q2’. Then, stack ‘s’ can be implemented in two ways:
- By making push operation costly:
- This method ensures that the newly entered element is always at the front of ‘q1’ so that pop operation just dequeues from ‘q1’.
- ‘q2’ is used as auxillary queue to put every new element in front of ‘q1’ while ensuring pop happens in O(1) complexity.
- Pseudocode:Push element to stack s: Here push takes O(n) time complexity.
push(s, data):
压栈(s, data):
Enqueue data to q2
将 data 入队到 q2
Dequeue elements one by one from q1 and enqueue to q2.
从 q1 中逐一出队元素并入队到 q2。
Swap the names of q1 and q2
交换 q1 和 q2 的名称
- Pop element from stack s: Takes O(1) time complexity.
pop(s):
pop(s):
dequeue from q1 and return it.
从 q1 中出队并返回它。
- By making pop operation costly:
- In push operation, the element is enqueued to q1.
- In pop operation, all the elements from q1 except the last remaining element, are pushed to q2 if it is empty. That last element remaining of q1 is dequeued and returned.
- Pseudocode:Push element to stack s: Here push takes O(1) time complexity.
push(s,data):
push(s,data):
Enqueue data to q1
将数据入队到 q1
- Pop element from stack s: Takes O(n) time complexity.
pop(s):
pop(s):
Step1: Dequeue every elements except the last element from q1 and enqueue to q2.
步骤1:从 q1 中出队除最后一个元素外的所有元素,并将它们入队到 q2。
Step2: Dequeue the last item of q1, the dequeued item is stored in result variable.
步骤2:出队 q1 的最后一项,出队的项存储在结果变量中。
Step3: Swap the names of q1 and q2 (for getting updated data after dequeue)
步骤3:交换 q1 和 q2 的名称(以便在出队后获取更新后的数据)
Step4: Return the result.
步骤4:返回结果。
167. What is array data structure? What are the applications of arrays?
什么是数组数据结构?数组有哪些应用?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5fa0 | 官方: 否 | 付费: 否
答案:
An array data structure is a data structure that is used to store data in a way that is efficient and easy to access. It is similar to a list in that it stores data in a sequence. However, an array data structure differs from a list in that it can hold much more data than a list can. An array data structure is created by combining several arrays together. Each array is then given a unique identifier, and each array’s data is stored in the order in which they are created.
数组数据结构是一种用于以高效且易于访问的方式存储数据的数据结构。它类似于列表,因为它按顺序存储数据。然而,数组数据结构与列表的不同之处在于,它可以容纳比列表多得多的数据。数组数据结构是通过将多个数组组合在一起而创建的。每个数组被赋予一个唯一标识符,并且每个数组的数据按创建顺序存储。
Array data structures are commonly used in databases and other computer systems to store large amounts of data efficiently. They are also useful for storing information that is frequently accessed, such as large amounts of text or images.
数组数据结构常用于数据库和其他计算机系统中,以高效地存储大量数据。它们也适用于存储频繁访问的信息,例如大量文本或图像。
168. Elaborate on different types of array data structure
详细说明不同类型的数组数据结构
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5fa3 | 官方: 否 | 付费: 否
答案:
There are several different types of arrays: - One-dimensional array: A one-dimensional array stores its elements in contiguous memory locations, accessing them using a single index value. It is a linear data structure holding all the elements in a sequence.
有几种不同类型的数组:- 一维数组:一维数组将其元素存储在连续的内存位置中,并使用单个索引值访问它们。它是一种线性数据结构,将所有元素按顺序保存。
- Two-dimensional array: A two-dimensional array is a tabular array that includes rows and columns and stores data. An M × N two-dimensional array is created by grouping M rows and N columns into N columns and rows.
- Three-dimensional array: A three-dimensional array is a grid that has rows, columns, and depth as a third dimension. It comprises a cube with rows, columns, and depth as a third dimension. The three-dimensional array has three subscripts for a position in a particular row, column, and depth. Depth (dimension or layer) is the first index, row index is the second index, and column index is the third index.
169. What is a linked list data structure? What are the applications for the Linked list?
什么是链表数据结构?链表有哪些应用?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5fa6 | 官方: 否 | 付费: 否
答案:
A linked list can be thought of as a series of linked nodes (or items) that are connected by links (or paths). Each link represents an entry into the linked list, and each entry points to the next node in the sequence. The order in which nodes are added to the list is determined by the order in which they are created.
链表可以被视为一系列通过链接(或路径)连接的节点(或项目)。每个链接代表进入链表的一个入口,每个入口指向序列中的下一个节点。节点添加到列表中的顺序由它们被创建的顺序决定。
Following are some applications of linked list data structure: - Stack, Queue, binary trees, and graphs are implemented using linked lists.
以下是链表数据结构的一些应用:- 栈、队列、二叉树和图都是使用链表实现的。
- Dynamic management for Operating System memory.
- Round robin scheduling for operating system tasks.
- Forward and backward operation in the browser.
170. Elaborate on different types of Linked List data structures?
详细说明链表数据结构的不同类型?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5fa9 | 官方: 否 | 付费: 否
答案:
Following are different types of linked lists:
以下是链表的不同类型:
- Singly Linked List: A singly linked list is a data structure that is used to store multiple items. The items are linked together using the key. The key is used to identify the item and is usually a unique identifier. In a singly linked list, each item is stored in a separate node. The node can be a single object or it can be a collection of objects. When an item is added to the list, the node is updated and the new item is added to the end of the list. When an item is removed from the list, the node that contains the removed item is deleted and its place is taken by another node. The key of a singly linked list can be any type of data structure that can be used to identify an object. For example, it could be an integer, a string, or even another singly linked list. Singly-linked lists are useful for storing many different types of data. For example, they are commonly used to store lists of items such as grocery lists or patient records. They are also useful for storing data that is time sensitive such as stock market prices or flight schedules.
- Doubly Linked List: A doubly linked list is a data structure that allows for two-way data access such that each node in the list points to the next node in the list and also points back to its previous node. In a doubly linked list, each node can be accessed by its address, and the contents of the node can be accessed by its index. It's ideal for applications that need to access large amounts of data in a fast manner. A disadvantage of a doubly linked list is that it is more difficult to maintain than a single-linked list. In addition, it is more difficult to add and remove nodes than in a single-linked list.
- Circular Linked List: A circular linked list is a unidirectional linked list where each node points to its next node and the last node points back to the first node, which makes it circular.
- Doubly Circular Linked List: A doubly circular linked list is a linked list where each node points to its next node and its previous node and the last node points back to the first node and first node’s previous points to the last node.
- Header List: A list that contains the header node at the beginning of the list, is called the header-linked list. This is helpful in calculating some repetitive operations like the number of elements in the list etc.
171. Difference between Array and Linked List.
数组和链表之间的区别。
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5fac | 官方: 否 | 付费: 否
答案:
| Arrays 数组 | Linked Lists 链表 |
|---|---|
| An array is a collection of data elements of the same type. 数组是相同类型数据元素的集合。 | A linked list is a collection of entities known as nodes. The node is divided into two sections: data and address. 链表是称为节点的实体的集合。节点分为两部分:数据和地址。 |
| It keeps the data elements in a single memory. 它将数据元素保存在单个内存中。 | It stores elements at random, or anywhere in the memory. 它将元素存储在内存中的随机或任意位置。 |
| The memory size of an array is fixed and cannot be changed during runtime. 数组的内存大小是固定的,不能在运行时更改。 | The memory size of a linked list is allocated during runtime. 链表的内存大小在运行时分配。 |
| An array's elements are not dependent on one another. 数组的元素彼此不依赖。 | Linked List elements are dependent on one another. 链表的元素彼此依赖。 |
| It is easier and faster to access an element in an array. 访问数组中的元素更容易且更快。 | In the linked list, it takes time to access an element. 在链表中,访问元素需要时间。 |
| Memory utilization is ineffective in the case of an array. 在数组的情况下,内存利用率低效。 | Memory utilization is effective in the case of linked lists. 在链表的情况下,内存利用率高效。 |
| Operations like insertion and deletion take longer time in an array. 在数组中,插入和删除等操作耗时更长。 | Operations like insertion and deletion are faster in the linked list. 在链表中,插入和删除等操作更快。 |
172. What is an asymptotic analysis of an algorithm?
什么是算法的渐近分析?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b37a5f58d557c902ba5faf | 官方: 否 | 付费: 否
答案:
Asymptotic analysis of an algorithm defines the run-time performance as per its mathematical boundations. Asymptotic analysis helps us articulate the best case(Omega Notation, Ω), average case(Theta Notation, θ), and worst case(Big Oh Notation, Ο) performance of an algorithm.
算法的渐近分析根据其数学边界来定义运行时性能。渐近分析帮助我们阐述算法的最佳情况(Ω符号,Ω)、平均情况(θ符号,θ)和最坏情况(大O符号,Ο)的性能。
173. What is hashmap in data structure?
数据结构中的哈希表(HashMap)是什么?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5fb2 | 官方: 否 | 付费: 否
答案:
Hashmap is a data structure that uses an implementation of a hash table data structure which allows access to data in constant time (O(1)) complexity if you have the key.
哈希表(HashMap)是一种数据结构,它使用哈希表数据结构的实现,如果拥有键,可以在常数时间(O(1))复杂度内访问数据。
174. What is the requirement for an object to be used as key or value in HashMap?
对象用作HashMap的键或值有什么要求?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5fb5 | 官方: 否 | 付费: 否
答案:
- The key or value object that gets used in the hashmap must implement equals() and hashcode() method.
- The hash code is used when inserting the key object into the map and the equals method is used when trying to retrieve a value from the map.
175. How does HashMap handle collisions in Java?
在Java中,HashMap如何处理碰撞?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5fb8 | 官方: 否 | 付费: 否
答案:
- The java.util.HashMap class in Java uses the approach of chaining to handle collisions. In chaining, if the new values with the same key are attempted to be pushed, then these values are stored in a linked list stored in a bucket of the key as a chain along with the existing value.
- In the worst-case scenario, it can happen that all keys might have the same hashcode, which will result in the hash table turning into a linked list. In this case, searching a value will take O(n) complexity as opposed to O(1) time due to the nature of the linked list. Hence, care has to be taken while selecting hashing algorithm.
176. What is the time complexity of basic operations get() and put() in HashMap class?
HashMap类中基本操作get()和put()的时间复杂度是多少?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37a5f58d557c902ba5fbb | 官方: 否 | 付费: 否
答案:
The time complexity is O(1) assuming that the hash function used in the hash map distributes elements uniformly among the buckets.
时间复杂度为O(1),前提是哈希映射中使用的哈希函数将元素均匀地分布在各个桶中。
177. Can you tell the time complexity for searching an element in a hashmap?
你能说出在哈希表中搜索一个元素的时间复杂度吗?
- 知识点: 算法与数据结构 (标签: interviewbit, de-shaw, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: D. E. Shaw
- id: 69b37a6d58d557c902ba6818 | 官方: 否 | 付费: 否
答案:
- Be it search, insert or delete the time taken by a Hashmap for performing these operations in Java is O(1),
- Note that O(1) is the best and average-case time but in the worst case it can go up to O(N).
178. Determine if there is any subarray present whose sum is 0
确定是否存在任何子数组,其和为0
- 知识点: 算法与数据结构 (标签: interviewbit, de-shaw, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: D. E. Shaw
- id: 69b37a6d58d557c902ba6827 | 官方: 否 | 付费: 否
答案:
Problem Discussion:
问题讨论:
You will be given an array in input and you have to determine whether there is any subarray or not whose sum is equal to 0.
在输入中你会得到一个数组,你必须确定是否存在任何子数组,其和等于0。
Note: The array can contain both positive and negative elements
注意:数组可以包含正数和负数元素
Algorithm:
算法:
- A brute force approach could be to use a nested loop for traversing the elements and check whether the sum is equal to 0 or not, but that would take an order of N^2 time.
- To solve the problem in O(N) time we will be using a set.
- Traverse the array is check for three conditions:
- If the current element is 0
- If the current sum is present is set
- If the current sum is 0
- If any of the above conditions satisfies, then return true in that case
Implementation:
实现:
include<bits/stdc++.h>
using namespace std;
using namespace std;
bool isSubArraypresentWith0Sum(int nums[], int n)
bool isSubArraypresentWith0Sum(int nums[], int n)
{
unordered_setinterviewbit_Set;
unordered_setinterviewbit_Set;
int sum = 0;
int sum = 0;
for (int i = 0 ; i < n ; i++)
for (int i = 0 ; i < n ; i++)
{
sum += nums[i];
sum += nums[i];
if (sum == 0 || interviewbit_Set.find(sum) != interviewbit_Set.end())
if (sum == 0 || interviewbit_Set.find(sum) != interviewbit_Set.end())
return true;
返回 true;
interviewbit_Set.insert(sum);
interviewbit_Set.insert(sum);
}
return false;
返回 false;
}
int main()
int main()
{
int nums[] = {-3, 2, 1, 9, 6};
int nums[] = {-3, 2, 1, 9, 6};
int n = sizeof(nums)/sizeof(nums[0]);
int n = sizeof(nums)/sizeof(nums[0]);
if (isSubArraypresentWith0Sum(nums, n))
if (isSubArraypresentWith0Sum(nums, n))
cout << "Found, A subarray with sum 0 in present";
cout << "Found, A subarray with sum 0 in present";
else
else
cout << "Not found, A subarray with sum 0 is not present";
cout << "Not found, A subarray with sum 0 is not present";
return 0;
return 0;
}
179. How can you implement queue using stack
如何使用栈实现队列
- 知识点: 算法与数据结构 (标签: interviewbit, de-shaw, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: D. E. Shaw
- id: 69b37a6d58d557c902ba6833 | 官方: 否 | 付费: 否
答案:
Problem Discussion:
问题讨论:
You are required to implement the en queue and de queue operations using the stack.
你需要使用栈来实现队列的入队和出队操作。
Algorithm: - Two stacks, i.e. stack1 and stack2, will be required to perform the enqueue and dequeue operations of the queue.
算法:- 需要两个栈,即 stack1 和 stack2,来执行队列的入队和出队操作。
- Imagine the top of stack1 as the rear end of the queue and the bottom of the stack as the front of the queue.
- Enqueue operation in the queue is equivalent to adding an element at the top of stack1 which can be performed in order of 1 time.
Dequeue operation in the queue is equivalent to removing an element from the bottom of stack1 which can be performed by the following operations:
Move all the elements of stack1 to stack2. Pop the top element from stack2 Store it in a variable. Again, move all the elements of stack2 back to stack1. Return the top element which we stored in a variable将 stack1 中的所有元素移到 stack2。从 stack2 弹出顶部元素并将其存储到一个变量中。再次将 stack2 中的所有元素移回 stack1。返回我们存储在变量中的顶部元素
You can understand it through the following diagram:
你可以通过以下图示来理解:
Implementation:
实现:
include<bits/stdc++.h>
using namespace std;
using namespace std;
// Implementation of queue using stacks
// 使用栈实现队列
stackstack1;
stackstack1;
stackstack2;
stackstack2;
void enqueue(int value) {
void enqueue(int value) {
stack1.push(value);
stack1.push(value);
}
int dequeue() {
int dequeue() {
if (stack1.empty()) {
if (stack1.empty()) {
return -1;
return -1;
}
while (!stack1.empty()) {
当(!stack1.empty())时,执行以下循环:
int temp= stack1.top();
整数类型 temp = stack1.top();
stack1.pop();
stack1.pop();
stack2.push(temp);
stack2.push(temp);
}
int top = stack2.top();
整数类型 top = stack2.top();
stack2.pop();
stack2.pop();
while (!stack2.empty()) {
当(!stack2.empty())时,执行以下循环:
int temp = stack2.top();
整数类型 temp = stack2.top();
stack2.pop();
stack2.pop();
stack1.push(temp);
stack1.push(temp);
}
return top;
返回 top;
}
int main() {
int main() {
enqueue(3);
入队(3);
enqueue(5);
入队(5);
enqueue(31);
入队(31);
cout<<dequeue()<<endl;
cout<<dequeue()<<endl;
enqueue(87);
enqueue(87);
cout<<dequeue()<<endl;
cout<<dequeue()<<endl;
cout<<dequeue()<<endl;
cout<<dequeue()<<endl;
return 0;
return 0;
}
Time and space analysis: - Time complexity: Enqueue:O(1) Dequeue:O(N)
时间与空间分析:- 时间复杂度:入队:O(1) 出队:O(N)
- Auxiliary Space: O(N)
- Follow up: Can you perform the enqueue operation in O(N) and dequeue operation in O(1) time using a similar approach?
Successful Tech Career for FREE!
免费开启成功的科技职业生涯!
Successful Tech Career!
成功的技术职业生涯!
Interview Process
面试流程
CTC & Designation
CTC与职位级别
Projects on the Job
工作项目
Referral System
推荐系统
Try It Out
试试看
2 Lakh+ Roadmaps Created
已生成20万+职业规划
180. Write a program to reverse a string with the help of stack
编写一个程序,借助栈来反转字符串
- 知识点: 算法与数据结构 (标签: interviewbit, delhivery, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Delhivery
- id: 69b37a6e58d557c902ba6933 | 官方: 否 | 付费: 否
答案:
Algorithm: - Create a string p of size n.
算法:- 创建一个大小为 n 的字符串 p。
- Create a stack of size n to store all the char of the string
- Traverse the string using a loop from the left and push each and every character in the stack
- When you come out of the loop, create a loop again to pop the elements from the stack and store them in a string.
- Since stack follows LIFO i.e. last in first out, the popped string will be reversed.
Return the reversed string and print it.
Implementation:实现:
include <bits/stdc++.h>
using namespace std;
using namespace std;
class Stack{
class Stack{
public:
public:
int top;
int top;
int size;
int size;
char* array;
char* array;
};
Stack* Stack_create(unsigned size){
Stack* Stack_create(unsigned size){
Stack* new_stk = new Stack();
Stack* new_stk = new Stack();
new_stk->size= size;
new_stk->size= size;
new_stk->top = -1;
new_stk->top = -1;
new_stk->array = new char[(new_stk->size * sizeof(char))];
new_stk->array = new char[(new_stk->size * sizeof(char))];
return new_stk;
return new_stk;
}
int stackfull(Stack* stk){
int stackfull(Stack* stk){
return stk->top == stk->size - 1;
return stk->top == stk->size - 1;
}
int stackempty(Stack* stk){
int stackempty(Stack* stk){
return stk->top == -1;
return stk->top == -1;
}
void push(Stack* stack, char item){
void push(Stack* stack, char item){
if (stackfull(stack))
if (stackfull(stack))
return;
return;
stack->array[++stack->top] = item;
stack->array[++stack->top] = item;
}
char pop(Stack* stk){
char pop(Stack* stk){
if (stackempty(stk))
if (stackempty(stk))
return -1;
return -1;
return stk->array[stk->top--];
return stk->array[stk->top--];
}
void string_reverse(char p[]){
void string_reverse(char p[]){
int n = strlen(p);
int n = strlen(p);
Stack* stk = Stack_create(n);
Stack* stk = Stack_create(n);
int i;
int i;
for(i = 0; i < n; i++){
for(i = 0; i < n; i++){
push(stk, p[i]);
push(stk, p[i]);
}
for(i = 0; i < n; i++){
for(i = 0; i < n; i++){
p[i] = pop(stk);
p[i] = pop(stk);
}
}
int main(){
int main(){
char p[] = "Welcome_To_InterviewBit";
char p[] = "Welcome_To_InterviewBit";
string_reverse(p);
string_reverse(p);
cout<<p<<endl;
cout<<p<<endl;
}
Time and space analysis: - Time Complexity: O(N)
时间和空间分析:- 时间复杂度:O(N)
- Auxiliary Space: O(N)
181. Rotate a matrix by 90 degrees in a clockwise manner.
将矩阵按顺时针方向旋转90度。
- 知识点: 算法与数据结构 (标签: interviewbit, delhivery, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Delhivery
- id: 69b37a6e58d557c902ba6942 | 官方: 否 | 付费: 否
答案:
Problem Discussion:
问题讨论:
Suppose you are given a matrix:
假设你有一个矩阵:
matn = { {1, 2, 3}, { 7,8,9 }, { 10, 11, 12 }, };
matn = { {1, 2, 3}, { 7,8,9 }, { 10, 11, 12 }, };
Your task is to rotate this matrix by 90 degrees in a clockwise manner.
你的任务是将这个矩阵按顺时针方向旋转90度。
So the output will look like this:
因此输出将会是这样:
10 7 1
11 8 2
12 9 3
Algorithm:
算法:
To rotate the matrix by 90 degrees you just have to follow 2 steps: - Take transpose of the matrix
要将矩阵旋转90度,只需遵循以下2个步骤:- 对矩阵进行转置
- Reverse all the rows of the matrix
- 2 3 1 7 10 10 7 1
7 8 9 ——Transpose——> 2 8 11 —-Reverse rows—-> 11 8 2
7 8 9 ——转置——> 2 8 11 —-反转行—-> 11 8 2
10 11 12 3 9 12 12 9 3
Implementation:
实现:
include
using namespace std;
using namespace std;
const int n = 3;
const int n = 3;
void print(int given_matrixn)
void print(int given_matrixn)
{
for (int i = 0; i < n; i++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
for (int j = 0; j < n; j++)
cout << given_matrixi << " ";
cout << given_matrixi << " ";
cout << endl;
cout << endl;
}
}
void rotate_a_matrix_by_90_degrees(int given_matrixn)
void rotate_a_matrix_by_90_degrees(int given_matrixn)
{
for (int i = 0; i < n; i++)
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
for (int j = i + 1; j < n; j++)
swap(given_matrixi, given_matrixj);
swap(given_matrixi, given_matrixj);
for (int i = 0; i < n; i++) {
for (int i = 0; i < n; i++) {
int left = 0, right = n - 1;
int left = 0, right = n - 1;
while (left < right) {
while (left < right) {
swap(given_matrixi, given_matrixi);
swap(given_matrixi, given_matrixi);
left++;
left++;
right--;
right--;
}
}
}
int main()
int main()
{
int given_matrixn
int given_matrixn
= { {1, 2, 3},
{ 7,8,9 },
{ 10, 11, 12 },
};
rotate_a_matrix_by_90_degrees(given_matrix);
rotate_a_matrix_by_90_degrees(given_matrix);
print(given_matrix);
print(given_matrix);
}
Time and space Analysis: - Time Complexity – O(N2)
时间和空间分析:- 时间复杂度 – O(N2)
- Auxiliary Space – O(1)
182. What is amortized time complexity?
什么是摊还时间复杂度?
- 知识点: 算法与数据结构 (标签: interviewbit, delhivery, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Delhivery
- id: 69b37a6e58d557c902ba6945 | 官方: 否 | 付费: 否
答案:
- Amortized time complexity analysis is used in data structures where the frequency of high-cost operations is low compared to low-cost operations.
- Let’s understand it through an example:
- Suppose you have to insert elements in a dynamic array whose initial size is 1. So for 1 insertion, there is no problem but for 2nd insertion, we actually have to double the size of the array.
- In memory, the array size does not double but creates a new array of double size and copies all the elements from the previous array. After copying the previous elements, a new element is inserted. This will take 3(size of array+1) operations. So for inserting n elements the time complexity will be N 3N i.e O(N2).
Now, let’s do an amortized time complexity analysis:
现在,让我们进行摊还时间复杂度分析:
- So this whole process will take 2(for doubling the size)+2(for copying the elements)+1(for inserting new element) operations.
- Again for inserting the next element we have to double the size of the array which will take 4+2+1operations.
- Now the 4th element can be inserted in just 1 operation.
- Again for the 5th element, the size of the array will be doubled and 8+4+1 operations will be performed, and so on.
- Hence, the number of operations is either 1 or 3*size of array +1.
- The 3*(size of array+1) operation will occur when the array size is 1 then 2 then 4 then ……2N.
- It will form a G.P of the form:
3(1+2+4…………+2N).
3(1+2+4…………+2N)。
- After solving this expression you will get 12N will equal to O(N).
As you can observe by using amortized analysis, we reduced the time complexity from the worst case, O (N2) to O(N), just by doing a better analysis. So amortized analysis says that instead of looking at the worst case we should do a better analysis of the algorithm.
如你所见,通过使用摊还分析,我们将时间复杂度从最坏情况 O(N2) 降低到 O(N),仅仅通过进行更好的分析。所以摊还分析说明,与其看待最坏情况,我们应当对算法进行更好的分析。
183. We need to reverse the order of the first k members of a queue of numbers, leaving the other elements in the same relative order, given an integer k and a queue of integers. Only the standard operations like enqueue, dequeue, size and front are allowed.
我们需要反转一个数字队列中前 k 个成员的顺序,使其他元素保持原有相对顺序,给定一个整数 k 和一个整数队列。仅允许使用标准操作,如入队、出队、大小和队首。
- 知识点: 算法与数据结构 (标签: interviewbit, deloitte, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 德勤
- id: 69b37a6f58d557c902ba699f | 官方: 否 | 付费: 否
答案:
Using an auxiliary stack is the strategy. - Create a stack that is empty.
使用辅助栈是策略。- 创建一个空栈。
- Dequeue the first k items from the provided queue one by one and then stack the dequeued items.
- Backfill the queue with the contents of the stack.
Dequeue (size-k) elements from the front and add them to the same queue one by one.
Here is the C++ implementation of the algorithm discussed:这是所讨论算法的C++实现:
// C++
// C++
void reverseFirstKElements(int k, queue& Q)
void reverseFirstKElements(int k, queue& Q)
{
if (Q.empty() || k > Q.size())
if (Q.empty() || k > Q.size())
return;
return;
if (k <= 0)
if (k <= 0)
return;
return;
stack
stackS;
int i = 1;
int i = 1;
/ Push the first k elements of the Queue into the Stack/
/ 将队列的前k个元素推入栈中 /
while (i <= k) {
while (i <= k) {
S.push(Q.front());
S.push(Q.front());
Q.pop();
Q.pop();
i++;
i++;
}
/ Enqueue the elements of the stack at the end of the queue/
/ 将栈中的元素入队到队列末尾 /
while (S.empty() == false) {
while (S.empty() == false) {
Q.push(S.top());
Q.push(S.top());
S.pop();
S.pop();
}
/* the remaining elements to be
/* 剩余元素将
enqueued at the end of the Queue*/
在队列末尾入队*/
for (int i = 0; i < Q.size() - k; i++) {
for (int i = 0; i < Q.size() - k; i++) {
Q.push(Q.front());
Q.push(Q.front());
Q.pop();
Q.pop();
}
}
We dequeue the first k elements from the queue Q and push them into the stack S. We then insert the elements from S to Q. Then (size-k) elements are removed from the front and added to Q one by one.
我们从队列 Q 中出队前 k 个元素,并将它们压入栈 S。然后我们将元素从 S 插入到 Q。接着,从队首移除(size-k)个元素,并逐一添加到 Q 的末尾。
184. What are scheduling algorithms? Explain the FCFS Scheduling Algorithm.
什么是调度算法?解释 FCFS 调度算法。
- 知识点: 算法与数据结构 (标签: interviewbit, dxc, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: DXC Technology
- id: 69b37ab758d557c902ba9502 | 官方: 否 | 付费: 否
答案:
CPU Scheduling is the process of determining which process will have exclusive use of the CPU while another is paused. The basic goal of CPU scheduling is to ensure that whenever the CPU is idle, the OS chooses at least one of the programmes in the ready queue to run. The CPU scheduler will be in charge of the selection process. It chooses from among the processes in memory that are ready to run. It simply solves the problem of selecting which of the outstanding requests should be given priority. Its fundamental goal is to alleviate resource scarcity while also ensuring justice among those who use the resources. In layman's terms, it is a method of allocating resources among multiple competing jobs. The various types of Scheduling Algorithms are as follows: - First Come First Serve (or FCFS)
CPU 调度是确定当另一个进程暂停时,哪个进程将独占使用 CPU 的过程。CPU 调度的基本目标是确保每当 CPU 空闲时,操作系统从就绪队列中选择至少一个程序来运行。CPU 调度器将负责选择过程。它从内存中处于就绪状态的进程中进行选择。它仅解决选择哪些待处理请求应被优先处理的问题。其基本目标是缓解资源稀缺,同时确保资源使用者之间的公平性。通俗来说,这是一种在多个竞争作业之间分配资源的方法。各种类型的调度算法如下:- 先来先服务(或 FCFS)
- Round Robin
- Shortest Time Remaining
- Priority Scheduling
- Multilevel Queue Scheduling
Shortest Job First
First Come First Serve Scheduling Algorithm:先来先服务调度算法:
FCFS (First Come First Serve) is an operating system scheduling technique that executes processes in the order in which they arrive in the Ready Queue of the operating system. To put it another way, the process that comes first will be carried out first. Its nature is non-preemptive. If the burst time of the first process is the longest among all the jobs, FCFS scheduling may generate an issue of hunger. The time required by the process for execution in milliseconds is referred to as burst time. In comparison to other Operating System scheduling algorithms, it is also considered the easiest and simplest. The FIFO (First In First Out) queue is commonly used to handle FCFS implementation.
FCFS(先来先服务)是一种操作系统调度技术,它按照进程到达操作系统就绪队列的顺序来执行进程。换句话说,先到达的进程将首先被执行。其性质是非抢占式的。如果第一个进程的突发时间在所有作业中是最长的,FCFS 调度可能会产生饥饿问题。进程执行所需的时间(以毫秒为单位)称为突发时间。与其他操作系统调度算法相比,它也被认为是最简单且最容易的。FIFO(先进先出)队列通常用于处理 FCFS 的实现。
Let us look at the FCFS Scheduling Algorithm with the help of an example. Let us assume that there are five processes with process IDs P0, P1, P2, P3, and P4 in the following given schedule. In the ready queue, P0 comes at time 0, P1 arrives at time 1, P2 arrives at time 2, P3 arrives at time 3, and Process P4 arrives at time 4. The processes are listed in the table below, along with their respective Arrival and Burst times.
让我们通过一个示例来了解 FCFS 调度算法。假设在以下给定的调度中有五个进程,进程 ID 分别为 P0、P1、P2、P3 和 P4。在就绪队列中,P0 在时间 0 到达,P1 在时间 1 到达,P2 在时间 2 到达,P3 在时间 3 到达,进程 P4 在时间 4 到达。下表列出了这些进程及其各自的到达时间和突发时间。
| Process ID 进程 ID | Time of Arrival 到达时间 | Burst Time 突发时间 | Completion Time 完成时间 | Turn Around Time 周转时间 | Waiting Time 等待时间 |
|---|---|---|---|---|---|
| 0 | 0 | 2 | 2 | 2 | 0 |
| 1 | 1 | 6 | 8 | 7 | 1 |
| 2 | 2 | 4 | 12 | 10 | 6 |
| 3 | 3 | 9 | 21 | 18 | 9 |
| 4 | 6 | 12 | 33 | 29 | 17 |
The following formula is used to compute the turnaround time and the waiting time:
以下公式用于计算周转时间和等待时间:
Turn Around Time = Completion Time - Arrival Time
周转时间 = 完成时间 - 到达时间
Waiting Time = Turnaround time - Burst Time
等待时间 = 周转时间 - 突发时间
The average waiting time is calculated by adding all of the processes' respective waiting times and dividing the total by the total number of processes. Therefore we can say that the average Waiting time is 31/5 units = 6.2 units. Given below is the Gnatt Chart for the entire FCFS algorithm.
平均等待时间是通过将所有进程各自的等待时间相加,再除以进程总数来计算的。因此我们可以说平均等待时间为31/5个单位 = 6.2个单位。下面给出的是整个FCFS算法的甘特图。
185. Could you explain how the stack can be implemented using the array?
你能解释一下如何使用数组来实现栈吗?
- 知识点: 算法与数据结构 (标签: interviewbit, epam, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: EPAM Systems
- id: 69b37aea58d557c902bab2dd | 官方: 否 | 付费: 否
答案:
Stack is a type of linear data structure that follows the LIFO (Last In First Out) principle. Insert and delete operations on the stack are performed from one end (top) only. Inserting a data element on top of the stack is called a push operation, and removing a data element from the top is called a pop operation.
栈是一种遵循LIFO(后进先出)原则的线性数据结构。栈上的插入和删除操作只能从一端(栈顶)执行。在栈顶插入数据元素的操作称为压入操作,而从栈顶移除数据元素的操作称为弹出操作。
Implementation of stack using Array - Using push(): To insert data into the stack, we use the Push() function, but before we do so, we have to check if the stack is full. The push operation cannot be performed if the stack is full, a condition that is sometimes called stack overflow. But, if there is space, the push() function inserts the element and increments the top pointer.
使用数组实现栈——使用push():要向栈中插入数据,我们使用Push()函数,但在执行之前,我们必须检查栈是否已满。如果栈已满,则无法执行压入操作,这种情况有时称为栈溢出。但如果还有空间,push()函数会插入元素并递增栈顶指针。
//Program to implement stack using Array
//使用数组实现栈的程序
//x is element to be added and n is size of the stack
//x是要添加的元素,n是栈的大小
void push (int x, int n)
void push (int x, int n)
{
if (top == n )
if (top == n )
printf("Overflow");
printf("Overflow");
else
else
{
top = top +1;
top = top +1;
stack[top] = x;
stack[top] = x;
}
} - Using pop(): To delete data from the stack, we use the Pop() function, but before we do so, we have to check if the stack is empty. If the stack is empty, the push() operation cannot be performed; otherwise, the pop() function decrements the value at the top of the stack.
} - 使用pop():要从栈中删除数据,我们使用Pop()函数,但在执行之前,我们必须检查栈是否为空。如果栈为空,则无法执行压入操作;否则,pop()函数会递减栈顶的值。
//Program to implement stack using Array
//使用数组实现栈的程序
int pop ()
int pop ()
{
if(top == -1)
如果(top == -1)
{
printf("Underflow");
printf("下溢");
return 0;
return 0;
}
else
else
{
return stack[top - - ];
返回 stack[top - - ];
}
}
186. What is the requirement traceability matrix?
什么是需求可追溯性矩阵?
- 知识点: 算法与数据结构 (标签: interviewbit, epam, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: EPAM Systems
- id: 69b37aea58d557c902bab2e4 | 官方: 否 | 付费: 否
答案:
As the name suggests, the RTM (Requirement Traceability Matrix) is a document, in the form of a table, which connects and traces user requirements with test cases to make sure that all requirements are covered during testing. RTM was designed in order to verify that all test cases had been covered and that no functionality had been missed during testing. In addition, it assists with identifying and maintaining project requirements and deliverables. Simply put, it is a way of tracking project requirements and ensuring they have been met.
顾名思义,RTM(需求可追溯性矩阵)是一种以表格形式呈现的文档,它将用户需求与测试用例连接并追踪起来,以确保在测试过程中所有需求都被覆盖。RTM 的设计目的是验证所有测试用例都已覆盖,并且在测试期间没有遗漏任何功能。此外,它还有助于识别和维护项目需求及交付物。简单来说,它是一种追踪项目需求并确保其得到满足的方式。
Advantages: - Ensure 100% test coverage.
优点: - 确保 100% 测试覆盖率。
- It makes it easy to identify missing functionality.
- Aids you in finding defects related to vital requirements, along with defect severity and priority.
- When requirements change, it is possible to identify test cases that should be updated.
- The overall status of test execution can be tracked easily.
187. State the difference between quick sort and merge sort.
说明快速排序和归并排序之间的区别。
- 知识点: 算法与数据结构 (标签: interviewbit, epam, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: EPAM Systems
- id: 69b37aea58d557c902bab2e7 | 官方: 否 | 付费: 否
答案:
Both Quicksort and Mergesort are sorting algorithms that allow array elements to be arranged in sequence order, thereby, facilitating a faster and easier search for array elements. Both are based on the divide and conquer approach.
快速排序和归并排序都是排序算法,允许数组元素按顺序排列,从而有助于更快、更轻松地查找数组元素。两者都基于分治法。
| Quicksort 快速排序 | Mergesort 归并排序 |
|---|---|
| In Quicksort, each element of the array is compared with a pivot element. 在快速排序中,数组的每个元素都与一个基准元素进行比较。 | Mergesort repeatedly divides the array into two subarrays (n/2) until only one element remains. 归并排序反复将数组分成两个子数组(n/2),直到只剩一个元素。 |
| Quicksort is ideal for small arrays. 快速排序非常适合小数组。 | Merge sort is suitable for any array size, whether small or large. 归并排序适用于任何数组大小,无论大小。 |
| The worst time complexity of Quicksort is O(n^2). 快速排序的最坏时间复杂度为 O(n^2)。 | The worst time complexity of Mergesort is O(n log n). 归并排序的最坏时间复杂度为 O(n log n)。 |
| It doesn't take up any more space to perform the quick sort. 快速排序不占用任何额外空间。 | To merge two subarrays takes additional space as a temporary array. 合并两个子数组需要额外空间作为临时数组。 |
| For small data sets, it will be faster than other sorting algorithms. 对于小数据集,它比其他排序算法更快。 | With this algorithm, all data sets are sorted at the same speed. 使用此算法,所有数据集都以相同的速度进行排序。 |
188. Write the binary search algorithm?
写出二分查找算法?
- 知识点: 算法与数据结构 (标签: interviewbit, epam, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: EPAM Systems
- id: 69b37aea58d557c902bab2ea | 官方: 否 | 付费: 否
答案:
A binary search algorithm is used to determine an element's position within a sorted array. This algorithm is based on the divide and conquers approach. A binary search looks for the target element by comparing it with the middlemost element in the array.
二分查找算法用于确定元素在已排序数组中的位置。该算法基于分治法。二分查找通过将目标元素与数组中最中间的元素进行比较来查找目标元素。
Example: Assume that the array to be searched is 1234567. Suppose x = 5 is the element to be searched. 1 is the leftmost element (low) and 7 is the rightmost element (high) element in the array. Find the middle element (mid) of the array using the formula [(low + high)/2]. In this case, the middle element is (1+7)/2=4. - If x==mid, it will return mid.
示例:假设要搜索的数组为 1234567。假设 x = 5 是要搜索的元素。1 是数组中最左边的元素(low),7 是最右边的元素(high)。使用公式 [(low + high)/2] 找到数组的中间元素(mid)。在这种情况下,中间元素是 (1+7)/2=4。 - 如果 x==mid,它将返回 mid。
- If x>mid, x will be compared against the middle element of the subarray to the right of mid.
- If x Code:
// Binary Search in Java
// Binary Search in Java
import java.util.Scanner;
import java.util.Scanner;
public class Main
public class Main
{
int binarySearch(int array[], int x, int low, int high)
int binarySearch(int array[], int x, int low, int high)
{
// Repeat until the pointers low and high meet each other
// 重复操作直到指针low和high相遇
while (low <= high)
while (low <= high)
{
int mid = low + (high - low) / 2;
int mid = low + (high - low) / 2;
if (array[mid] == x)
if (array[mid] == x)
return mid;
返回 mid;
if (array[mid] < x)
if (array[mid] < x)
low = mid + 1;
low = mid + 1;
else
else
high = mid - 1;
high = mid - 1;
}
return -1;
return -1;
}
public static void main(String args[])
public static void main(String args[])
{
Main obj = new Main();
Main obj = new Main();
int array[] = { 1, 2, 3, 4, 5, 6, 7 };
int array[] = { 1, 2, 3, 4, 5, 6, 7 };
int n = array.length;
int n = array.length;
Scanner s= new Scanner(System.in);
Scanner s= new Scanner(System.in);
System.out.print("Enter a target element: ");
System.out.print("输入目标元素: ");
int x=s.nextInt();
int x=s.nextInt();
int result = obj.binarySearch(array, x, 0, n - 1);
int result = obj.binarySearch(array, x, 0, n - 1);
if (result == -1)
if (result == -1)
System.out.println("Not found");
System.out.println("未找到");
else
else
System.out.println("Element found at index " + result);
System.out.println("元素位于索引 " + result);
}
}
Output:
输出:
Enter a target element: 7
输入目标元素: 7
Element found at index 6
元素位于索引 6
Successful Tech Career for FREE!
免费开启成功的科技职业生涯!
Successful Tech Career!
成功的技术职业生涯!
Interview Process
面试流程
CTC & Designation
CTC与职位级别
Projects on the Job
工作项目
Referral System
推荐系统
Try It Out
试试看
2 Lakh+ Roadmaps Created
已生成20万+职业规划
189. What is the best case and worst case time complexity for the quick sort?.
快速排序的最佳情况和最坏情况时间复杂度是什么?
- 知识点: 算法与数据结构 (标签: interviewbit, epam, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: EPAM Systems
- id: 69b37aea58d557c902bab2ed | 官方: 否 | 付费: 否
答案:
Quicksort can be applied in several different ways based on the position of the pivot in the array: - Selecting the first or last element in the array as a pivot element
快速排序可以根据数组中基准元素的位置以多种不同方式应用:- 选择数组中的第一个或最后一个元素作为基准元素
Selecting a median element of an array as a pivot element
Best Case: Quicksort performs the best if we divide arrays and subarrays into two equal partitions, i.e., when we select the median element of the array as a pivot element. The partition positions for each element happen to be in the middle of the array, resulting in a balanced binary tree of height log(n). Therefore, the total complexity becomes O(n log n).最佳情况:如果我们将数组和子数组分成两个相等的分区,即选择数组的中间元素作为基准元素,快速排序性能最佳。每个元素的分区位置恰好位于数组中间,形成高度为log(n)的平衡二叉树。因此,总复杂度为O(n log n)。
Worst Case: Worst case is when we select the left-most or right-most element of an array as a pivot element. The partition positions for each element happen to be at the edge of the array (left or right), resulting in a skew tree having height n. Therefore, the total complexity becomes O(n^2).
最坏情况:最坏情况是选择数组的最左端或最右端元素作为基准元素。每个元素的分区位置恰好位于数组边缘(左侧或右侧),形成高度为n的倾斜树。因此,总复杂度为O(n^2)。
190. Write an algorithm for quicksort.
编写一个快速排序算法。
- 知识点: 算法与数据结构 (标签: interviewbit, epam, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: EPAM Systems
- id: 69b37aea58d557c902bab2f0 | 官方: 否 | 付费: 否
答案:
Sorting entails arranging items in a systematic manner. With the QuickSort algorithm, data elements can be sorted much faster than with any other sorting algorithm. This algorithm is based on the divide and conquers approach. It begins by selecting an element from the array known as the pivot element. It then uses the partition algorithm to divide the array into two sub-arrays, one containing greater values than the pivot element and the other containing smaller values than the pivot element. After that, the quicksort algorithm recursively sorts these two sub-arrays. As soon as the sorting is completed, both sub-arrays are combined into one sorted array.
排序涉及以系统方式排列项目。使用QuickSort算法,数据元素的排序速度比任何其他排序算法都要快得多。该算法基于分治法。它首先从数组中选择一个元素,称为基准元素。然后使用分区算法将数组分为两个子数组,一个包含大于基准元素的值,另一个包含小于基准元素的值。之后,快速排序算法递归地对这两个子数组进行排序。一旦排序完成,两个子数组合并为一个有序数组。
import java.util.Arrays;
import java.util.Arrays;
class Quicksort
class Quicksort
{
// method to find the partition position
// method to find the partition position
static int partition(int array[], int leftmost, int rightmost)
static int partition(int array[], int leftmost, int rightmost)
{
//leftmost element as pivot
//最左侧元素作为枢轴
int pivot = array[rightmost];
int pivot = array[rightmost];
// pointer for greater element
// 指向较大元素的指针
int i = (leftmost - 1);
int i = (leftmost - 1);
// compare each element with pivot
// 将每个元素与枢轴进行比较
for (int j = leftmost; j < rightmost; j++)
for (int j = leftmost; j < rightmost; j++)
{
if (array[j] <= pivot)
if (array[j] <= pivot)
{
// If element found is smaller than pivot
// 如果找到的元素小于枢轴
//it will be swapped with the larger element pointed by i
// 它将与i指向的较大元素交换
i++;
i++;
// element at i is swapped with element at j
// i处的元素与j处的元素交换
int s = array[i];
int s = array[i];
array[i] = array[j];
array[i] = array[j];
array[j] = s;
array[j] = s;
}
}
// swapt the pivot element with the greater element specified by i
// 将枢轴元素与i指定的较大元素交换
int s = array[i + 1];
int s = array[i + 1];
array[i + 1] = array[rightmost];
array[i + 1] = array[rightmost];
array[rightmost] = s;
array[rightmost] = s;
// return the position from where partition is done
// 返回分区完成的位置
return (i + 1);
return (i + 1);
}
static void quickSort(int array[], int leftmost, int rightmost)
static void quickSort(int array[], int leftmost, int rightmost)
{
if (leftmost < rightmost)
if (leftmost < rightmost)
{
int pi = partition(array, leftmost, rightmost);
int pi = partition(array, leftmost, rightmost);
// recursive call on the left of pivot
// 对枢纽元素左侧进行递归调用
quickSort(array, leftmost, pi - 1);
quickSort(array, leftmost, pi - 1);
// recursive call on the right of pivot
// 对枢纽元素右侧进行递归调用
quickSort(array, pi + 1, rightmost);
quickSort(array, pi + 1, rightmost);
}
}
}
class Main
class Main
{
public static void main(String args[])
public static void main(String args[])
{
int[] arr = { 5, 4, 6, 1, 0, 8, 3 };
int[] arr = { 5, 4, 6, 1, 0, 8, 3 };
System.out.println("Unsorted Array");
System.out.println("Unsorted Array");
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(arr));
int size = arr.length;
int size = arr.length;
Quicksort.quickSort(arr, 0, size - 1);
Quicksort.quickSort(arr, 0, size - 1);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println("升序排序后的数组:");
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(arr));
}
}
Output:
输出:
Unsorted Array
未排序数组
[5, 4, 6, 1, 0, 8, 3]
Sorted Array in Ascending Order:
升序排序后的数组:
[0, 1, 3, 4, 5, 6, 8]
191. Could you tell me how many data structures you are familiar with?
你能告诉我你熟悉多少种数据结构吗?
- 知识点: 算法与数据结构 (标签: interviewbit, epam, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: EPAM Systems
- id: 69b37aea58d557c902bab2f3 | 官方: 否 | 付费: 否
答案:
Data Structures are specialized ways to store and organize data in computer systems in order to perform operations on the data more efficiently. Data structures are used across a wide range of fields in computer science and software engineering. You should choose the appropriate data structure based on your requirements and project. In the case of storing data sequentially in memory, the Array data structure is recommended. In general, data structures can be divided into two categories:
数据结构是在计算机系统中存储和组织数据的专门方式,以便更高效地对数据执行操作。数据结构在计算机科学和软件工程的许多领域中被广泛使用。你应该根据需求和项目选择合适的数据结构。当需要按顺序在内存中存储数据时,推荐使用数组数据结构。一般来说,数据结构可以分为两大类:
Linear data structure: In the linear data structure, elements are arranged one after another in sequence. As the elements are organized in a specific order, they are easily implemented. A few examples of linear data structures are as follows: - Array: In an array, elements are sequentially stored one after another in memory. They all have the same data type.
线性数据结构:在线性数据结构中,元素按顺序一个接一个地排列。由于元素以特定顺序组织,它们易于实现。线性数据结构的一些例子如下:- 数组:在数组中,元素在内存中依次存储。它们都具有相同的数据类型。
- Stack: Data elements in the stack are arranged based on the LIFO (Last in First Out) principle. In other words, the last element stored in a stack will be removed first.
- Queue: Data elements in Queue are arranged based on the FIFO (First in First out) principle. In other words, the first element stored in a queue will be removed first.
Linked List: The elements of a linked list are stored as nodes. Each node contains the data items and the address to the next node. Generally, a node is made up of two parts, one storing the data element, and the other storing the link to the next node.
Non-linear data structure: In non-linear data structures, elements are not in any particular order. Rather, they are organized in a hierarchical manner in which one element is linked to another or more elements. A few examples of non-linear data structures are: - Graph: Graphs are collections of edges and vertices. Graphs consist of nodes called vertices, and vertices are connected to each other by edges.非线性数据结构:在非线性数据结构中,元素不按任何特定顺序排列。相反,它们以层次方式组织,其中一个元素连接到另一个或更多元素。非线性数据结构的一些例子是:- 图:图是边和顶点的集合。图由称为顶点的节点组成,顶点通过边相互连接。
- Trees: Trees are also made up of vertices and edges, just like graphs. Tree data structures allow only one edge to exist between two vertices.
192. Write a program for binary search using recursion.
使用递归编写一个二分搜索程序。
- 知识点: 算法与数据结构 (主题: general-programming;标签: interviewbit, genc, topic-specific, general-programming)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b37afd58d557c902babecd | 官方: 否 | 付费: 否
答案:
public boolean binarySearch(int[] arr, int low, int high, key){
public boolean binarySearch(int[] arr, int low, int high, key){
//base case returns false when index is out of bound
//当索引超出范围时,基本情况返回false
if(low > high)
if(low > high)
return false;
返回 false;
int mid = (low+high)/2
int mid = (low+high)/2
//Searching on mid if key found then return true
//在中间位置搜索,如果找到键值则返回 true
if(arr[mid] == key)
if(arr[mid] == key)
return true
返回 true
//Searching on right sub array if key exist there
//在右侧子数组中搜索,如果键值存在
else if(arr[mid] < key)
else if(arr[mid] < key)
return binarySearch(arr, mid+1, high, key);
返回 binarySearch(arr, mid+1, high, key);
//Searching on left sub-array of key exist there.
//在左侧子数组中搜索,如果键值存在
else
else
return binarySearch(arr, low, mid-1, key);
返回 binarySearch(arr, low, mid-1, key);
}
193. Define Stack Data Structure. And how can you implement it?
定义栈数据结构。以及你如何实现它?
- 知识点: 算法与数据结构 (主题: general-programming;标签: interviewbit, genc, topic-specific, general-programming)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b37afd58d557c902babeea | 官方: 否 | 付费: 否
答案:
A Stack is a linear data structure that uses the LIFO (Last-In-First-Out) method to organize data (e.g., a queue). While queues have two ends (front and rear), stacks have just one. The top pointer points to the top element of the stack (while the front of a queue points to the front element, the rear of the queue points to the rear element). When an element is placed on the stack, it is put on the top (and may only be removed from the stack). In other words, a stack can be defined as a container in which additions and deletions can be made from only one end (the top of the stack).
栈是一种线性数据结构,使用LIFO(后进先出)方法来组织数据(例如队列)。虽然队列有两个端(前端和后端),栈只有一个端。顶部指针指向栈顶元素(而队列的前端指向队首元素,队列的后端指向队尾元素)。当元素放入栈中时,它被放在顶部(并且只能从栈中移除)。换句话说,栈可以被定义为一种容器,其中添加和删除只能从一端(栈顶)进行。
We can implement the stack using two different physical data structures. Arrays and LinkedList.
我们可以使用两种不同的物理数据结构来实现栈。数组和链表。
194. You are required to serialize a binary tree into a string such that when needed, it can be reconstructed to the same tree.
你需要将二叉树序列化为字符串,以便在需要时可以重建为同一棵树。
- 知识点: 算法与数据结构 (主题: general-programming;标签: interviewbit, genc, topic-specific, general-programming)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37afd58d557c902babef3 | 官方: 否 | 付费: 否
答案:
Example - Given tree
示例 - 给定树
If we consider the serialization of the tree by breadth-first traversal or level order traversal. Then the string can be like - “2,4,9,13,15,1,6,7,X,3,9,X,10,X,14,X,9,X,X,X,X,X,X,X,X,X,X”. In this, (X) represents null, and (,) helps as the delimiter between the values. So the code implementation to this problem will be -
如果我们考虑通过广度优先遍历或层序遍历来序列化树。那么字符串可以像这样 - “2,4,9,13,15,1,6,7,X,3,9,X,10,X,14,X,9,X,X,X,X,X,X,X,X,X,X”。其中(X)表示空,并且(,)作为值之间的分隔符。所以这个问题的代码实现将是 -
//Method accepts the root node of the tree, breadth-first traverse on it and serialize it.
//该方法接受树的根节点,对其进行广度优先遍历并序列化。
private String serialize(TreeNode root){
private String serialize(TreeNode root){
//String that stores the serialized tree.
//存储序列化树的字符串。
StringBuffer sb = new StringBuffer();
StringBuffer sb = new StringBuffer();
//Queue that helps traversing level-order.
//帮助层序遍历的队列。
Queuequeue = new LinkedList<>();
Queuequeue = new LinkedList<>();
queue.add(root);
queue.add(root);
while(!queue.isEmpty()){
while(!queue.isEmpty()){
TreeNode currNode = queue.poll();
TreeNode currNode = queue.poll();
if(currNode != null){
if(currNode != null){
queue.add(currNode.left);
queue.add(currNode.left);
queue.add(currNode.right);
queue.add(currNode.right);
//Storing the tree in the serialized form.
//以序列化形式存储树。
sb.append(currNode.val+",");
sb.append(currNode.val+",");
}else
}else
//Apeending X that represents null node.
//追加表示空节点的 X。
sb.append("X,");
sb.append("X,");
}
return sb.toString();
return sb.toString();
}
195. You are given a matrix. Your task is to rotate the matrix by 90 degrees.
给定一个矩阵。你的任务是将其旋转 90 度。
- 知识点: 算法与数据结构 (主题: general-programming;标签: interviewbit, genc, topic-specific, general-programming)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37afd58d557c902babef9 | 官方: 否 | 付费: 否
答案:
In the above image, you can see that the 1st row becomes the last column of the matrix. In short, we can see that the array is rotated 90 degrees clockwise.
在上图中,你可以看到第 1 行变成了矩阵的最后一列。简而言之,我们可以看到数组按顺时针方向旋转了 90 度。
You can solve this problem in 2 steps. Transposing the matrix will make the first-row first-column. Next, we'll swap the first column with the last column to rotate the matrix by 90 degrees. After transposing the first row into the first column, we can swap the first column with the last column in the second step to solve the problem. This solution takes O(mn) time. The time complexity for this will be O(mn) where m is the number of rows in the matrix and n will be the number of columns in the matrix.
你可以分两步解决这个问题。转置矩阵会使第一行变为第一列。接下来,我们将第一列与最后一列交换,将矩阵旋转 90 度。在将第一行转置为第一列后,我们可以在第二步中交换第一列和最后一列来解决该问题。此解法需要 O(mn) 时间。其时间复杂度为 O(mn),其中 m 是矩阵的行数,n 是矩阵的列数。
//This method rotates the matrix by 90 degree clockwise
//此方法将矩阵按顺时针方向旋转 90 度
public void transposeMatrix(int[][] matrix){
public void transposeMatrix(int[][] matrix){
int m = matrix.length;
int m = matrix.length;
int n = matrix[0].length;
int n = matrix[0].length;
//Steps to Transpose the matrix
//转置矩阵的步骤
for(int i = 0; i < m; i++){
for(int i = 0; i < m; i++){
for(int j = i; j < n; j++){
for(int j = i; j < n; j++){
int temp = matrixi;
int temp = matrixi;
matrixi = matrixj;
matrixi = matrixj;
matrixj = temp;
matrixj = temp;
}
}
//Steps to make the 1st column the last column
//将第 1 列变为最后一列的步骤
for(int i = 0; i < m; i++){
for(int i = 0; i < m; i++){
for(int j = 0, l = n-1; j < l; j++){
for(int j = 0, l = n-1; j < l; j++){
int temp = matrixi;
int temp = matrixi;
matrixi = matrixi;
matrixi = matrixi;
matrixi = temp;
matrixi = temp;
l--;
l--;
}
}
}
196. The transpose of a matrix is the matrix with its rows and columns flipped over their vertical main diagonals, switching the matrix's indices. SO write a program to transpose the matrix.
矩阵的转置是将矩阵的行和列沿其垂直主对角线翻转,交换矩阵的索引。所以编写一个程序来转置矩阵。
- 知识点: 算法与数据结构 (主题: general-programming;标签: interviewbit, genc, topic-specific, general-programming)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b37afd58d557c902babefc | 官方: 否 | 付费: 否
答案:
We can transpose the matrix by simply swapping the row value with its corresponding column value.
我们可以通过简单地将行值与其对应的列值交换来转置矩阵。
Code:
代码:
// Method that transpose thee matrix
// 转置矩阵的方法
public void transpose(int[][] matrix)
public void transpose(int[][] matrix)
// Calculating size of row and column
// 计算行和列的大小
int row = matrix.length;
int row = matrix.length;
int col = matrix[0].length;
int col = matrix[0].length;
for(int i = 0; i < row; i++){
for(int i = 0; i < row; i++){
for(int j = i+1; j < col; j++){
for(int j = i+1; j < col; j++){
// Swapping the row value with its corresponding column value.
// 将行值与其对应的列值交换。
int temp = matrixi;
int temp = matrixi;
matrixi = matrixj;
matrixi = matrixj;
matrixj = temp;
matrixj = temp;
}
}
}
197. Given a 2D matrix with n rows and m columns, your task is to print the elements of the matrix in a zigzag manner as shown in the image below :
给定一个具有n行和m列的二维矩阵,你的任务是以如下图片所示之字形方式打印矩阵的元素:
- 知识点: 算法与数据结构 (标签: interviewbit, goldman-sachs, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 高盛
- id: 69b37b1458d557c902bacc10 | 官方: 否 | 付费: 否
答案:
For example, Input: 1 2 3 4
例如,输入:1 2 3 4
Output: 1 2 3 4
输出:1 2 3 4
Input: 1 2 3 4 5 6 7 8 9
输入:1 2 3 4 5 6 7 8 9
Output: 1 2 4 7 5 3 6 8 9
输出:1 2 4 7 5 3 6 8 9
Approach:
方法:
The strategy is straightforward. We will keep iterating over each diagonal element one by one and change the direction based on the previous match.
策略很直接。我们将逐个遍历每个对角线元素,并根据之前的匹配来改变方向。
include<bits/stdc++.h>
using namespace std;
using namespace std;
// function to print the matrix in a zigzag pattern
// 用于以锯齿形模式打印矩阵的函数
void zigZagTraversal(vector<vector> arr, int n, int m)
void zigZagTraversal(vector<vector> arr, int n, int m)
{
int cur_row = 0, cur_col = 0; //denotes the current row and column
int cur_row = 0, cur_col = 0; // 表示当前的行和列
// false denotes cur_col needs to be incremented, true denotes cur_row needs to be incremented
// false 表示 cur_col 需要递增,true 表示 cur_row 需要递增
bool flag = false;
bool flag = false;
// Printing matrix of lower half zig-zag pattern
// 打印矩阵下半部分的锯齿形模式
int mn = min(m, n);
int mn = min(m, n);
for (int length = 1; length <= mn; ++length) {
for (int length = 1; length <= mn; ++length) {
for (int i = 0; i < length; ++i) {
for (int i = 0; i < length; ++i) {
cout << arrcur_row << " ";
cout << arrcur_row << " ";
if (i + 1 == length)
if (i + 1 == length)
break;
break;
// If flag is true we increment cur_row and decrement cur_col else decrement cur_row and increment cur_col
// 如果flag为真,则cur_row加1,cur_col减1;否则cur_row减1,cur_col加1
if (flag == true){
if (flag == true){
cur_row = cur_row + 1;
当前行 = 当前行 + 1;
cur_col = cur_col - 1;
cur_col = cur_col - 1;
}
else{
否则{
cur_row = cur_row - 1;
cur_row = cur_row - 1;
cur_col = cur_col + 1;
当前列 = 当前列 + 1;
}
}
if (length == mn)
if (length == mn)
break;
break;
// We update cur_row or cur_col value according to the last increment
// 根据最后一次增量更新cur_row或cur_col的值
if (flag){
if (flag){
cur_row = cur_row + 1;
当前行 = 当前行 + 1;
flag = false;
标志 = 假;
}
else{
否则{
cur_col = cur_col + 1;
当前列 = 当前列 + 1;
flag = true;
flag = true;
}
}
// Updating the indexes of cur_row and cur_col variable
// 更新 cur_row 和 cur_col 变量的索引
if (cur_row == 0) {
if (cur_row == 0) {
if (cur_col == m - 1)
如果(当前列 == m - 1)
cur_row = cur_row + 1;
当前行 = 当前行 + 1;
else
else
cur_col = cur_col + 1;
当前列 = 当前列 + 1;
flag = 1;
flag = 1;
}
else {
否则 {
if (cur_row == n - 1)
如果(当前行 == n - 1)
cur_col = cur_col + 1;
当前列 = 当前列 + 1;
else
else
cur_row = cur_row + 1;
当前行 = 当前行 + 1;
flag = 0;
flag = 0;
}
// Printing the next half zig-zag pattern
// 打印下一个半锯齿形图案
int mx = max(m, n) - 1;
int mx = max(m, n) - 1;
for (int length, diagonal = mx; diagonal > 0; --diagonal) {
for (int length, diagonal = mx; diagonal > 0; --diagonal) {
if (diagonal > mn)
if (diagonal > mn)
length = mn;
length = mn;
else
else
length = diagonal;
length = diagonal;
for (int i = 0; i < length; ++i) {
for (int i = 0; i < length; ++i) {
cout << arrcur_row << " ";
cout << arrcur_row << " ";
if (i + 1 == length)
if (i + 1 == length)
break;
break;
// We update cur_row or cur_col value according to the last increment
// 根据最后一次增量更新cur_row或cur_col的值
if (flag == true){
if (flag == true){
cur_row = cur_row + 1;
当前行 = 当前行 + 1;
cur_col = cur_col - 1;
cur_col = cur_col - 1;
}
else{
否则{
cur_col = cur_col + 1;
当前列 = 当前列 + 1;
cur_row = cur_row - 1;
cur_row = cur_row - 1;
}
}
// Updating the cur_row and cur_col variables
// 更新cur_row和cur_col变量
if (cur_row == 0 || cur_col == m - 1) {
如果(当前行 == 0 或 当前列 == m - 1){
if (cur_col == m - 1)
如果(当前列 == m - 1)
cur_row = cur_row + 1;
当前行 = 当前行 + 1;
else
else
cur_col = cur_col + 1;
当前列 = 当前列 + 1;
flag = true;
flag = true;
}
else if (cur_col == 0 || cur_row == n - 1) {
否则如果(当前列 == 0 或 当前行 == n - 1){
if (cur_row == n - 1)
如果(当前行 == n - 1)
cur_col = cur_col + 1;
当前列 = 当前列 + 1;
else
else
cur_row = cur_row + 1;
当前行 = 当前行 + 1;
flag = false;
标志 = 假;
}
}
}
int main()
int main()
{
vector<vector> arr = vector<vector >(3, vector (3, 0));
vector<vector> arr = vector<vector >(3, vector (3, 0));
for(int i = 0; i < 3; i ++)
for(int i = 0; i < 3; i ++)
{
for(int j = 0; j < 3; j ++)
for(int j = 0; j < 3; j ++)
arri = 3 * i + (j + 1);
arri = 3 * i + (j + 1);
}
zigZagTraversal(arr, 3, 3);
zigZagTraversal(arr, 3, 3);
return 0;
return 0;
}
Explanation:
说明:
We follow a simulation approach in the above code. First, we print the elements in the first upper half of the matrix. Then, we print the elements of the lower half of the matrix. We iterate each diagonal one by one and print its elements.
在上述代码中,我们采用模拟方法。首先,我们打印矩阵上半部分的元素。然后,打印矩阵下半部分的元素。我们逐个遍历每条对角线并打印其元素。
198. What is a Red-Black Tree in context to data structures?
在数据结构中,什么是红黑树?
- 知识点: 算法与数据结构 (标签: interviewbit, goldman-sachs, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 高盛
- id: 69b37b1458d557c902bacc16 | 官方: 否 | 付费: 否
答案:
A red-black tree is a self-balancing binary search tree with one extra bit at each node, which is commonly read as the colour (red or black). These colours are used to keep the tree balanced as insertions and deletions are made. The tree's balance isn't ideal, but it's good enough to cut down on searching time and keep it around O(log n), where n is the total number of nodes in the tree. Rudolf Bayer invented this tree in 1972.
红黑树是一种自平衡二叉搜索树,每个节点多一个额外位,通常读作颜色(红色或黑色)。这些颜色用于在插入和删除操作时保持树的平衡。树的平衡并非完美,但足以减少搜索时间并将其保持在O(log n)左右,其中n是树中的节点总数。鲁道夫·拜尔于1972年发明了这种树。
It's worth noting that, because each node only needs 1 bit of memory to store the colour information, these trees have the same memory footprint as a traditional (uncoloured) binary search tree.
值得注意的是,由于每个节点仅需1位内存来存储颜色信息,这些树与传统(未着色)二叉搜索树具有相同的内存占用。
Points to remember: - Every node of a red-black tree has a colour, which is either red or black.
记住要点:- 红黑树的每个节点都有一种颜色,要么是红色,要么是黑色。
- The tree's root is always black.
- There are no red nodes that are next to one other (A red node is not allowed to have a red parent or red child).
- There is the same number of black nodes on every path from a node (including root) to any of its descendant's NULL nodes.
Successful Tech Career for FREE!
免费开启成功的科技职业生涯!
Successful Tech Career!
成功的技术职业生涯!
Interview Process
面试流程
CTC & Designation
CTC与职位级别
Projects on the Job
工作项目
Referral System
推荐系统
Try It Out
试试看
2 Lakh+ Roadmaps Created
已生成20万+职业规划
199. Given a binary tree root, imagine yourself standing on the right side of the tree, returning the values of the visible nodes in order from top to bottom.
给定一个二叉树根节点,想象你站在树的右侧,从上到下返回可见节点的值。
- 知识点: 算法与数据结构 (标签: interviewbit, hashedin, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: HashedIn
- id: 69b37b2f58d557c902badb8c | 官方: 否 | 付费: 否
答案:
Explanation -
解释 -
From the right side view the direct node we can see is [8, 9, 3, 25]. The other nodes like 12 are hidden behind 3. So it cannot be printed.
从右侧视角,我们能直接看到的节点是 [8, 9, 3, 25]。其他节点如 12 被 3 遮挡在后面。因此它不能被打印。
Solution:
解决方案:
For Solving this problem, we can traverse the binary tree with the level order and we can print the last node of the level. Level order traversal or BFS (Breadth First Search). We know that we have to use a queue data structure for level breadth first search on trees. So the Solution function will be -
要解决此问题,我们可以按层序遍历二叉树,并打印每一层的最后一个节点。层序遍历或 BFS(广度优先搜索)。我们知道在树上进行广度优先搜索时,需要使用队列数据结构。因此解决方案函数将是 -
//This Function returns the list of nodes that are visible from the right side.
//此函数返回从右侧可见的节点列表。
//This function accepts the root node of the tree.
//此函数接受树的根节点。
public ListrightSideView(TreeNode root) {
public ListrightSideView(TreeNode root) {
Listans = new ArrayList<>();
Listans = new ArrayList<>();
if(root == null)
if(root == null)
return ans;
return ans;
Queue
Queuequeue = new LinkedList<>();
queue.add(root);
queue.add(root);
while(!queue.isEmpty()){
while(!queue.isEmpty()){
int n = queue.size();
int n = queue.size();
for(int i = 0; i < n; i++){
for(int i = 0; i < n; i++){
TreeNode curr = queue.poll();
TreeNode curr = queue.poll();
//adding the node to the answer if it is the last node .
//如果该节点是最后一个节点,则将其添加到答案中。
if(i == n-1)
if(i == n-1)
ans.add(curr.val);
ans.add(curr.val);
//Add the child node to the queue.
//将子节点添加到队列中。
if(curr.left != null)
if(curr.left != null)
queue.add(curr.left);
queue.add(curr.left);
if(curr.right != null)
if(curr.right != null)
queue.add(curr.right);
queue.add(curr.right);
}
}
return ans;
return ans;
}
In the above function, the TreeNode structure will be like -
在上面的函数中,TreeNode结构将如下所示 -
public class TreeNode {
public class TreeNode {
int val;
int val;
TreeNode left; //Pointer to the left-subtree.
TreeNode left; //指向左子树的指针。
TreeNode right; //Pointer to the right-subtree.
TreeNode right; //指向右子树的指针。
}
The above method returns the list containing the nodes that are visible from the right side of the tree. In the above code, we are traversing every node of the tree. So the time complexity will be O(n) . And hence we are using the Queue for traversing the tree, the space complexity will also be O(n) .
上述方法返回包含从树右侧可见节点的列表。在上述代码中,我们遍历了树的每个节点,因此时间复杂度为 O(n)。而且我们使用队列来遍历树,空间复杂度也将是 O(n)。
200. Explain the internal working of a HashMap.
解释 HashMap 的内部工作原理。
- 知识点: 算法与数据结构 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b3558d557c902badec1 | 官方: 否 | 付费: 否
答案:
A hashmap uses a hashtable but what many people don’t know is that it is internally created using two data structures namely an array and a linked list. Whenever you declare a hashmap what is going to happen internally is that it will create an array of buckets. The buckets are referred to as nodes or you can say a linked list. These nodes contain mainly:
The key,键,
Value
值
Hashcode
哈希码
Address of the next node.
下一个节点的地址。- Now, when you insert values in a key like this:
map.put("hashmap implementation in Java",1);
map.put("hashmap implementation in Java",1);
Then hashcode will be calculated by the put method. This hashcode will help us to store the key at a particular index. Also, hashcode will make the process of retrieving the values faster.
然后,put 方法会计算哈希码。这个哈希码将帮助我们把键存储在特定的索引位置。同时,哈希码也会使值的检索过程更快。
hashcode=hash(“hashmap implementation in Java”);
hashcode=hash(“hashmap implementation in Java”);
This hash code is further computed and will generate an index for storing the value. The value of our key will be stored at the index given by the hashcode in the form of a LinkedList. - It’s important to note that Java 8 introduced BST in place of a linked list to make retrieval of the key-value pairs more efficient.
这个哈希码会进一步计算,并生成一个用于存储值的索引。我们的键值将存储在由哈希码给出的索引处,以链表的形式。 - 重要的是要注意,Java 8 引入了二叉搜索树(BST)来代替链表,使键值对的检索更加高效。
201. Which property of a hashmap is used to find the intersection of two arrays?
哈希映射的哪个属性用于查找两个数组的交集?
- 知识点: 算法与数据结构 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b3558d557c902badec4 | 官方: 否 | 付费: 否
答案:
- Since a hashmap stores only unique elements, this property of a hashmap can be used to find intersections i.e common elements of two arrays.
- The approach to this problem is: first we will create a hashmap and fill the elements of the first array in it.
- The next step is to iterate over the second array and check whether the element is present in the hashmap or not.
- In this way, we can find all common elements of two arrays in O(n) time complexity.
202. What is collision in HashMap?
什么是 HashMap 中的冲突?
- 知识点: 算法与数据结构 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b3558d557c902badec7 | 官方: 否 | 付费: 否
答案:
- A collision occurs when more than one key generates the same hashCode() value.
- An inefficient hashCode() algorithm causes considerable collisions in a hashmap.
- An increased number of collisions can affect the performance of a hashmap.
203. Discuss the approach for calculating all the equal combinations formed by a pair of numbers in an array using a hashmap i.e The numbers must satisfy these two conditions: nums[i] == nums[j] and i < j Answer)
讨论使用哈希映射计算数组中一对数字形成的所有相等组合的方法,即数字必须满足这两个条件:nums[i] == nums[j] 且 i < j 答案)
- 知识点: 算法与数据结构 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b3558d557c902badeca | 官方: 否 | 付费: 否
答案:
- You all must have studied combinations, so the concept of combinations states that every time we just have to select a pair from n numbers in an array that satisfies the given conditions and the formula for doing so is NCR which is equivalent to n*(n-1)/2.
- Now hashmap will be used for calculating the frequency of all the numbers in the array.
- While iterating the array we will store the frequency of every element in a hashmap.
- The final step would be to iterate over the map and apply the formula n*(n-1)/2, where n is the frequency of each element in the array.
204. How Does Java's Capacity And Size Of Hashmap Differ?
Java 中 HashMap 的容量和大小有何不同?
- 知识点: 算法与数据结构 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b3558d557c902badecd | 官方: 否 | 付费: 否
答案:
Sometimes it's confusing for students to understand the difference between capacity is size.
有时,学生们理解容量和大小之间的区别会感到困惑。
So basically, HashMap's capacity indicates the number of entries it can hold, while its length indicates how many key-value pairs are presently in existence.
基本上,HashMap 的容量表示它可以容纳的条目数量,而其长度表示当前存在的键值对数量。
- Data Science
- All Events
- My Events
205. How can iteration be performed in a HashMap?
如何在 HashMap 中进行迭代?
- 知识点: 算法与数据结构 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b3558d557c902baded0 | 官方: 否 | 付费: 否
答案:
import java.util.Map;
import java.util.Map;
import java.util.HashMap;
import java.util.HashMap;
public class example_____iteration
public class example_____iteration
{
public static void main(String[] arg)
public static void main(String[] arg)
{
Map<String,String> INTERVIEW_BIT = new HashMap<String,String>();
Map<String,String> INTERVIEW_BIT = new HashMap<String,String>();
INTERVIEW_BIT.put("hashmap coding interview questions", "AT INTERVEWBIT");
INTERVIEW_BIT.put("hashmap coding interview questions", "AT INTERVEWBIT");
INTERVIEW_BIT.put("hashmap programming interview questions", "AT INTERVEWBIT");
INTERVIEW_BIT.put("hashmap programming interview questions", "AT INTERVEWBIT");
for (Map.Entry<String,String> entry : INTERVIEW_BIT.entrySet())
for (Map.Entry<String,String> entry : INTERVIEW_BIT.entrySet())
System.out.println("Key = " + entry.getKey() +
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
", Value = " + entry.getValue());
}
}
Output:
输出:
Key = hashmap coding interview questions, Value = AT INTERVEWBIT
Key = hashmap coding interview questions, Value = AT INTERVEWBIT
Key = hashmap programming interview questions, Value = AT INTERVEWBIT
Key = hashmap programming interview questions, Value = AT INTERVEWBIT
206. What is the order in which keys are stored in a hashmap?
hashmap 中键的存储顺序是什么?
- 知识点: 算法与数据结构 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b3558d557c902baded3 | 官方: 否 | 付费: 否
答案:
- There is no particular order for storing keys in a hashmap. All the keys are stored in an unsorted order.
- For storing the elements in a particular order a Treemap can be used in Java but a hashmap does not guarantee the ordering of your elements.
207. Does hashmap allow you to store null values?
hashmap 允许存储 null 值吗?
- 知识点: 算法与数据结构 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b3558d557c902baded6 | 官方: 否 | 付费: 否
答案:
Yes, We can store as many null values in a hashmap as we want but only one null key can be stored not more than that.
是的,我们可以在 hashmap 中存储任意数量的 null 值,但只能存储一个 null 键,不能超过一个。
Let’s see a program that depicts how we can store null values in a hashmap.
让我们看一个演示如何在哈希映射中存储空值的程序。
import java.util.*;
import java.util.*;
import java.io.*;
import java.io.*;
public class interviewBit {
public class interviewBit {
public static void main(String[] args)
public static void main(String[] args)
{
HashMap hmap=new HashMap();
HashMap hmap=new HashMap();
hmap.put(1,"Program to store null value");
hmap.put(1,"Program to store null value");
hmap.put(null,"InterviewBit");
hmap.put(null,"InterviewBit");
System.out.println(hmap);
System.out.println(hmap);
}
}
OUTPUT:
输出:
{null=InterviewBit, 1=Program to store null value}
{null=InterviewBit, 1=Program to store null value}
208. Specify whether hashmaps in Java are thread-safe or not?
请说明Java中的哈希映射是否为线程安全的?
- 知识点: 算法与数据结构 / 行为与软技能 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: behavioral | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b3558d557c902baded9 | 官方: 否 | 付费: 否
答案:
- The answer is "NO" i.e java.lang.HashMap does not support thread-safety. If several threads are altering the HashMap, for example, insertions or removals, then a HashMap should not be shared with other threads.
- If you want to implement thread-safety then you can either use a ConcurrentHashMap or by using the Collections.synchronizedMap() method.
- When data consistency is crucial, Collections.synchronizedMap() should be used, and ConcurrentHashMap should be used where the number of reads and write operations to be performed are less.
- Since Collections.synchronizedMap() needs every thread to attain a lock on the whole object to accomplish both read and write operations, this results in slow performance.
- With ConcurrentHashMap, threads can simultaneously modify sections while maintaining a lock on individual segments.
209. Specify different methods of creating a hashmap in java along with implementation.
请说明在Java中创建哈希映射的不同方法及其实现。
- 知识点: 算法与数据结构 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b37b3558d557c902badedc | 官方: 否 | 付费: 否
答案:
Different methods of creating a hashmap are:
创建哈希映射的不同方法有:
1) Constructing a hashmap with default capacity - Syntax:
1) 使用默认容量构造哈希映射 - 语法:
HashMap<String, Integer> InterviewBIt_map1 = new HashMap<String, Integer>();
HashMap<String, Integer> InterviewBIt_map1 = new HashMap<String, Integer>();
2) Constructing a hashmap with a defined capacity i.e 50 in our example - Syntax:
2) 使用定义容量(例如我们的示例中为50)构造哈希映射 - 语法:
HashMap<String, Integer> InterviewBIt_map2 = new HashMap<String, Integer>(50);
HashMap<String, Integer> InterviewBIt_map2 = new HashMap<String, Integer>(50);
3) Specifying lead factor along with the capacity - Syntax:
3) 在指定容量的同时指定负载因子 - 语法:
HashMap<String, Integer> InterviewBIt_map3= new HashMap<String, Integer>(50, 0.5f);
HashMap<String, Integer> InterviewBIt_map3= new HashMap<String, Integer>(50, 0.5f);
4) By copying another map into our map - Syntax:
4) 通过将另一个映射复制到我们的映射中 - 语法:
HashMap<String, Integer> InterviewBIt_map4 = new HashMap<String, Integer>( InterviewBIt_map1);
HashMap<String, Integer> InterviewBIt_map4 = new HashMap<String, Integer>( InterviewBIt_map1);
210. Can you store multiple keys with the same value in a hashmap?
你能在哈希映射中存储多个具有相同值的键吗?
- 知识点: 算法与数据结构 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b3558d557c902badedf | 官方: 否 | 付费: 否
答案:
- No, multiple keys with the same value can’t be stored in a hashmap.
- When you try to insert a new key that is already present in the hashmap then overriding will happen and the old key will be replaced with the new key and a new value.
211. State the differences between a Hashmap and a Hashtable in Java.
说明 Java 中 HashMap 和 Hashtable 之间的区别。
- 知识点: 算法与数据结构 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b3558d557c902badee2 | 官方: 否 | 付费: 否
答案:
HashMap Vs HashTable
HashMap Vs HashTable
| Parameter
参数 | HashMap | HashTable |
| Synchronization 同步 | Hashmap and HashTable are very similar to each other except for the fact that a hashmap does not allow synchronization HashMap和HashTable彼此非常相似,除了HashMap不允许同步这一事实 | Unlike a Hashmap, synchronization is permitted in a Hashtable 与HashMap不同,Hashtable允许同步 |
| Performance 性能 | You won't face any performance issues in a hashmap. 你不会在HashMap中遇到任何性能问题。 | Synchronization in a hashtable might sound like a good idea that a particular element would be thread-safe if there’s concurrent access with multiple threads however, the problem with synchronizing every method that allows access to the underlying collection is that it creates performance issues. So you will have performance issues while using a hashtable 哈希表中的同步听起来可能是个好主意,即当多个线程并发访问时,某个特定元素将是线程安全的,然而,同步每个允许访问底层集合的方法的问题是它会产生性能问题。因此,在使用哈希表时会产生性能问题 |
| Null values 空值 | Null values are permitted in a Hashmap i.e you can store as many null values in a hashmap as you want. HashMap中允许空值,即你可以在哈希映射中存储任意多的空值。 | Unlike a Hashmap, Null values are not permitted in a hashtable 与HashMap不同,Hashtable中不允许空值 |
| Null keys 空键 | While using a Hashmap you can store only one null key not more than that. 使用HashMap时,你只能存储一个空键,不能超过一个。 | In a Hashtable null keys, as well as null values, are not allowed similar to a ConcurrentHashmap. 在Hashtable中,空键和空值都不允许,类似于ConcurrentHashMap。 |
| Iterators 迭代器 | We can use iterators for looping through the key and value pairs in a Hashmap. 我们可以使用迭代器来遍历HashMap中的键值对。 | We can use enumerators, as well as iterators, for looping through the key and value pairs in a Hashtable. 我们可以使用枚举器和迭代器来遍历Hashtable中的键值对。 |
Successful Tech Career for FREE!
免费开启成功的科技职业生涯!
Successful Tech Career!
成功的技术职业生涯!
Interview Process
面试流程
CTC & Designation
CTC与职位级别
Projects on the Job
工作项目
Referral System
推荐系统
Try It Out
试试看
2 Lakh+ Roadmaps Created
已生成20万+职业规划
212. What is the time complexity in terms of big o notation of pushing and retrieving an element from a hashmap?
从哈希映射中推送和检索元素的时间复杂度(以大O表示法表示)是多少?
- 知识点: 算法与数据结构 (主题: hashmap, data-structures;标签: interviewbit, hashmap, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b3558d557c902badee5 | 官方: 否 | 付费: 否
答案:
- Time complexity is the measure of the number of CPU cycles utilized by a program to execute.
- Hashmap time complexity for pushing and retrieving the elements is the order of 1 i.e O(1) using put and get methods respectively.
213. Can you explain the RR Scheduling algorithm?
你能解释一下RR调度算法吗?
- 知识点: 算法与数据结构 (标签: interviewbit, hexaware, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Hexaware Technologies
- id: 69b37b3758d557c902badffe | 官方: 否 | 付费: 否
答案:
Round Robin (RR) is a CPU scheduling algorithm that is commonly used to schedule processes. This is the simplest scheduling algorithm used most often for multitasking. Every ready process in the queue is executed in a cyclic way with a limited time slice (Time Quantum). When the process is in the ready queue, it is assigned the CPU for that time quantum. Now, if the process execution is completed within that time quantum, the process will terminate, otherwise, the process will be placed back in the ready queue until its turn comes around to complete the execution as shown below. - BT (Burst Time): Time required by the process to complete its execution.
轮询(RR)是一种常用的CPU调度算法,用于调度进程。这是多任务处理中最常用的最简单的调度算法。队列中的每个就绪进程以循环方式执行,每次分配一个有限的时间片(时间量子)。当进程在就绪队列中时,它被分配CPU在该时间量子内执行。现在,如果进程在该时间量子内完成执行,则进程将终止,否则,进程将被放回就绪队列,直到其轮次到来以完成执行,如下所示。- BT(突发时间):进程完成执行所需的时间。
- TQ (Time Quantum): The amount of time a process is allowed to run uninterrupted.
214. What do you mean by Recursion Function?
你所说的递归函数是什么意思?
- 知识点: 算法与数据结构 (标签: interviewbit, hexaware, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Hexaware Technologies
- id: 69b37b3758d557c902bae026 | 官方: 否 | 付费: 否
答案:
A recursive function is one that refers to itself, directly or indirectly in the code for execution. Recursive functions can either be simple or complex. Some problems can be easily solved with the recursive algorithm. Recursive functions often make use of loop setups in which the initial variable is called multiple times while it is altered by the loop. Factorial computations are classic examples of recursive functions, where an integer is multiplied by itself while being lowered incrementally. Factorial(4), for example, is equal to 4321, and factorial(2) is equal to 21.
递归函数是指在代码执行中直接或间接引用自身的函数。递归函数可以是简单的,也可以是复杂的。有些问题可以很容易地用递归算法解决。递归函数通常利用循环设置,在循环中初始变量被多次调用,同时被循环改变。阶乘计算是递归函数的经典示例,其中整数在递增递减的同时乘以自身。例如,阶乘(4)等于4321,阶乘(2)等于21。
215. Write code to check if a string is a palindrome or not?
编写代码检查一个字符串是否为回文?
- 知识点: 算法与数据结构 (标签: interviewbit, intuit, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Intuit
- id: 69b37b6b58d557c902bb02ad | 官方: 否 | 付费: 否
答案:
When a string is the same from left to right as it is from right to left, then it is a palindrome. Consider the string "str". We need to find out whether its reverse string is the same as its current one.
当一个字符串从左到右与从右到左相同时,它就是回文。考虑字符串"str"。我们需要找出其反向字符串是否与当前字符串相同。
Code:
代码:
// Java program to check whether a string is a Palindrome
// Java程序检查一个字符串是否为回文
import java.util.*;
import java.util.*;
public class Main
public class Main
{
public static void main(String args[])
public static void main(String args[])
{
String str1, str2 = "";
字符串 str1, str2 = "";
Scanner sc = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string: ");
System.out.print("Enter the string: ");
str1 = sc.nextLine();
str1 = sc.nextLine();
int n = str1.length();
int n = str1.length();
for(int i = n - 1; i >= 0; i--)
for(int i = n - 1; i >= 0; i--)
{
str2 = str2 + str1.charAt(i);
str2 = str2 + str1.charAt(i);
}
if(str1.equalsIgnoreCase(str2))
if(str1.equalsIgnoreCase(str2))
{
System.out.println("\nThe string is a palindrome.");
System.out.println("\nThe string is a palindrome.");
}
else
else
{
System.out.println("The string is not a palindrome.");
System.out.println("The string is not a palindrome.");
}
}
}
Sample Output1:
示例输出1:
Enter the string: Radar
输入字符串:Radar
The string is a palindrome.
该字符串是回文。
Sample Output2:
示例输出2:
Enter the string: Scaler
输入字符串:Scaler
The string is not a palindrome.
该字符串不是回文。
216. Explain BST (Binary Search Tree).
解释BST(二叉搜索树)。
- 知识点: 算法与数据结构 (标签: interviewbit, intuit, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Intuit
- id: 69b37b6b58d557c902bb02c2 | 官方: 否 | 付费: 否
答案:
Binary search trees also referred to as sorted or ordered binary trees, are data structures that allow us to maintain sorted lists of numbers rapidly. The following are the properties of binary search trees: - In the left subtree, all of the nodes are smaller than the parent node (root node).
二叉搜索树也被称为有序或排序二叉树,它们是允许我们快速维护有序数字列表的数据结构。以下是二叉搜索树的属性:- 在左子树中,所有节点都比父节点(根节点)小。
- In the right subtree, all of the nodes are greater than the parent node (root node).
- The subtrees of each node are also BSTs, which means that they possess the two properties listed above.
As you can see in the diagram above, the left binary tree follows all the properties of BST, thereby making it a Binary Search Tree. Alternatively, the right binary tree is not a binary search tree since the right subtree of the node "10" contains a value less than it, which is "8."
正如你在上面的图表中所见,左边的二叉树符合BST的所有属性,因此使其成为一棵二叉搜索树。相反,右边的二叉树不是二叉搜索树,因为节点“10”的右子树包含一个小于它的值,即“8”。
217. What does the divide and conquer algorithm mean?
分治算法是什么意思?
- 知识点: 算法与数据结构 (标签: interviewbit, intuit, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Intuit
- id: 69b37b6b58d557c902bb02df | 官方: 否 | 付费: 否
答案:
Divide and conquer is a strategy used to solve large problems. The steps are as follows: - Divide: Divide the given problem into smaller ones using recursion.
分治是一种用于解决大型问题的策略。步骤如下:- 分解:使用递归将给定问题分解为更小的问题。
- Conquer: Solve each smaller subproblem using recursion. For small subproblems, solve them directly if possible.
- Combine: Solve the main problem by combining the solutions of the subproblems that are part of a recursive process.
In case the same subproblem cannot be solved multiple times, employ the divide and conquer strategy. Here are some algorithms that follow the Divide and Conquer approach: - Quicksort
如果同一子问题无法多次解决,则采用分治策略。以下是遵循分治方法的一些算法:- 快速排序
- Merge Sort
- Strassen’s Algorithm
- Binary Search
Closest Pair of Points, etc.
Advantages of Divide and Conquer Algorithm - For the naive method of multiplying two matrices, the complexity is O(n3), while the divide and conquer method (Strassen's matrix multiplication) has a complexity of O(n2.8074). Other problems, such as Hanoi's Tower, can also be solved this way.分治算法的优点:- 对于两个矩阵相乘的朴素方法,其复杂度为O(n3),而分治方法(Strassen矩阵乘法)的复杂度为O(n2.8074)。其他问题,如汉诺塔,也可以这样解决。
- This approach is well suited to multiprocessing systems.
- Memory caches are efficiently used.
218. Differentiate between HashSet and TreeSet. When would you prefer TreeSet to HashSet?
区分 HashSet 和 TreeSet。你什么时候会优先选择 TreeSet 而不是 HashSet?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb0809 | 官方: 否 | 付费: 否
答案:
Following are the differences between HashSet and TreeSet:- - Internal implementation and speed
以下是HashSet和TreeSet之间的区别:- - 内部实现和速度
HashSet: For search, insert, and remove operations, it takes constant time on average. TreeSet is slower than HashSet. A hash table is used to implement HashSet.
HashSet:对于搜索、插入和删除操作,平均需要常数时间。TreeSet比HashSet慢。哈希表用于实现HashSet。
TreeSet: For search, insert, and delete, TreeSet takes O(Log n), which is higher than HashSet. TreeSet, on the other hand, preserves ordered data. Higher() (Returns the least higher element), floor(), ceiling(), and other operations are also supported. In TreeSet, these operations are likewise O(Log n), and HashSet does not implement them. A Self-Balancing Binary Search Tree is used to implement TreeSet (Red Black Tree). In Java, TreeSet is backed by TreeMap. - Way of storing elements The elements of a HashSet are not ordered. In Java, the TreeSet class keeps objects in a Sorted order defined by the Comparable or Comparator methods. By default, TreeSet components are sorted in ascending order. It has a number of methods for dealing with ordered sets, including first(), last(), headSet(), tailSet(), and so on.
TreeSet:对于搜索、插入和删除,TreeSet需要O(Log n),比HashSet更高。另一方面,TreeSet保持有序数据。还支持higher()(返回最小的高于给定元素的元素)、floor()、ceiling()等操作。在TreeSet中,这些操作同样是O(Log n),而HashSet不实现它们。自平衡二叉搜索树用于实现TreeSet(红黑树)。在Java中,TreeSet由TreeMap支持。 - 存储元素的方式 HashSet的元素是无序的。在Java中,TreeSet类按照Comparable或Comparator方法定义的排序顺序保存对象。默认情况下,TreeSet组件按升序排序。它有许多用于处理有序集合的方法,包括first()、last()、headSet()、tailSet()等。
- Allowing Null values Null objects are allowed in HashSet. TreeSet does not allow null objects and throws a NullPointerException. This is because TreeSet compares keys using the compareTo() method, which throws java.lang. NullPointerException.
ComparisonHashSet compares two objects in a Set and detects duplicates using the equals() method. For the same purpose, TreeSet employs the compareTo() method. If equals() and compareTo() are not consistent, that is, if equals() returns true for two equal objects but compareTo() returns zero, the contract of the Set interface will be broken, allowing duplicates in Set implementations like TreeSet.
Following are the cases when TreeSet is preferred to HashSet :以下情况优先选择TreeSet而不是HashSet:
Instead of unique elements, sorted unique elements are required. TreeSet returns a sorted list that is always in ascending order. 2. The locality of TreeSet is higher than that of HashSet. If two entries are close in order, TreeSet places them in the same data structure and hence in memory, but HashSet scatters the entries over memory regardless of the keys to which they are linked. 3. To sort the components, TreeSet employs the Red-Black tree method. TreeSet is a fantastic solution if you need to do read/write operations regularly.
- 需要排序的唯一元素而不是唯一的元素时。TreeSet返回一个始终按升序排列的排序列表。 2. TreeSet的局部性高于HashSet。如果两个条目在顺序上接近,TreeSet会将它们放在相同的数据结构中,从而在内存中也相近,而HashSet则将条目分散在内存中,无论它们关联的键是什么。 3. 为了排序组件,TreeSet采用红黑树方法。如果你需要定期执行读/写操作,TreeSet是一个绝佳的解决方案。
219. Differentiate between Collection and collections in the context of Java.
在Java的上下文中,区分Collection和collections。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb080c | 官方: 否 | 付费: 否
答案:
Collection : In the java.util.package, there is an interface called a collection. It's used to represent a collection of separate objects as a single entity. It's equivalent to the container in the C++ programming language. The collection framework's root interface is referred to as the collection. It has a number of classes and interfaces for representing a collection of individual objects as a single unit. The key sub-interfaces of the collection interface are List, Set, and Queue. Although the map interface is part of the Java collection framework, it does not inherit the interface's collection. The Collection interface's most significant functions are add(), remove(), clear(), size(), and contains().
Collection:在java.util包中,有一个名为Collection的接口。它用于将一组单独的对象表示为单个实体。它相当于C++编程语言中的容器。集合框架的根接口被称为Collection。它有许多类和接口,用于将一组单独的对象表示为单个单元。Collection接口的关键子接口是List、Set和Queue。虽然Map接口是Java集合框架的一部分,但它不继承Collection接口。Collection接口最重要的函数是add()、remove()、clear()、size()和contains()。
Collections : The java.util.package has a utility class called Collections. It defines various utility methods for working with collections, such as sorting and searching. All of the methods are static. These techniques give developers much-needed convenience, allowing them to interact with Collection Framework more successfully. It provides methods like sort() to sort the collection elements in the normal sorting order, and min() and max() to get the minimum and maximum value in the collection elements, respectively.
Collections:java.util包中有一个名为Collections的工具类。它定义了用于处理集合的各种实用方法,例如排序和搜索。所有的方法都是静态的。这些技术为开发人员提供了急需的便利,使他们能够更成功地与集合框架交互。它提供了诸如sort()(按正常排序顺序对集合元素进行排序)以及min()和max()(分别获取集合元素中的最小值和最大值)等方法。
| Collection | Collections |
|---|---|
| It's used to represent a collection of separate objects as a single entity. 它用于将一组独立对象表示为一个单一实体。 | It defines a number of useful methods for working with collections. 它定义了多种用于处理集合的有用方法。 |
| It is an interface. 它是一个接口。 | It is a utility class. 它是一个工具类。 |
| Since Java 8, the Collection is an interface with a static function. Abstract and default methods can also be found in the Interface. 自Java 8起,Collection是一个带有静态函数的接口。接口中也可以找到抽象方法和默认方法。 | It only has static methods in it. 它只包含静态方法。 |
220. Explain the hierarchy of the Collection framework in Java.
解释Java中Collection框架的层次结构。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb080f | 官方: 否 | 付费: 否
答案:
The entire collection framework hierarchy is made up of four fundamental interfaces: Collection, List, Set, Map, and two specific interfaces for sorting called SortedSet and SortedMap. The java.util package contains all of the collection framework's interfaces and classes. The following diagram depicts the Java collection structure.
整个集合框架层次结构由四个基本接口组成:Collection、List、Set、Map,以及两个用于排序的特定接口,称为SortedSet和SortedMap。java.util包包含了集合框架的所有接口和类。下图描绘了Java集合的结构。
Here, e denotes extends, i denotes implements - Extends: The keyword extends is used to create inheritance between two classes and two interfaces.
这里,e表示extends,i表示implements- Extends:关键字extends用于在两个类和两个接口之间创建继承关系。
- Implements: The keyword implements are used to create inheritance across classes and interfaces.
221. What are the advantages of the Collection framework?
Collection框架有哪些优点?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb0812 | 官方: 否 | 付费: 否
答案:
Following are the advantages of the Collection framework:-
以下是Collection框架的优点:-
Consistent API : The API has a core set of interfaces like Collection, Set, List, or Map, and all the classes (ArrayList, LinkedList, Vector, and so on) that implement these interfaces have some common set of methods.
一致的API:API具有一组核心接口,如Collection、Set、List或Map,并且所有实现这些接口的类(如ArrayList、LinkedList、Vector等)都有一组公共的方法。
Cuts programming effort : Instead of worrying about the Collection's design, a programmer may concentrate on how best to use it in his program. As a result, the fundamental principle of Object-oriented programming (i.e. abstraction) has been applied successfully.
减少编程工作量:程序员不必担心Collection的设计,而是可以专注于如何在程序中最有效地使用它。因此,面向对象编程的基本原则(即抽象)已被成功应用。
Improves program speed and quality by offering high-performance implementations of useful data structures and algorithms, as the programmer does not have to worry about the optimum implementation of a certain data structure in this scenario. They can simply use the best implementation to improve the performance of their program significantly.
通过提供有用数据结构和算法的高性能实现来提高程序的速度和质量,因为在这种情况下,程序员不必担心某种数据结构的最优实现。他们可以简单地使用最佳实现来显著提高程序的性能。
222. Explain the various interfaces used in the Collection framework.
解释Collection框架中使用的各种接口。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb0815 | 官方: 否 | 付费: 否
答案:
The collection framework has several interfaces, each of which is used to store a different sort of data. The interfaces included in the framework are listed below.
集合框架有多个接口,每个接口用于存储不同类型的数据。框架中包含的接口如下所列。
- Iterable Interface : This is the collection framework's primary interface. The iterable interface is extended by the collection interface. As a result, all interfaces and classes implement this interface by default. This interface's main purpose is to provide an iterator for the collections. As a result, this interface only has one abstract method, the iterator.
- Collection Interface : The collection framework's classes implement this interface, which extends the iterable interface. This interface covers all of the basic methods that every collection has, such as adding data to the collection, removing data from the collection, clearing data, and so on. All of these methods are incorporated in this interface because they are used by all classes, regardless of their implementation style. Furthermore, including these methods in this interface guarantees that the method names are consistent across all collections. In summary, we may conclude that this interface lays the groundwork for the implementation of collection classes.
- List Interface : The collection interface has a child interface called the list interface. This interface is devoted to list data, in which we can store all of the objects in an ordered collection. This also allows for the presence of redundant data. Various classes, such as ArrayList, Vector, Stack, and others, implement this list interface. We can create a list object with any of these classes because they all implement the list.
- Queue Interface : A queue interface, as the name implies, follows the FIFO (First In First Out) order of a real-world queue line. This interface is for storing all elements in which the order of the elements is important. When we try to shop at a store, for example, the bills are issued on a first-come, first-served basis. As a result, the individual whose request is first in line receives the bill first. PriorityQueue, Deque, ArrayDeque, and other classes are available. Because all of these subclasses implement the queue, we can use any of them to create a queue object.
- Deque Interface : It differs slightly from the queue data structure. Deque, also known as a double-ended queue, is a data structure in which elements can be added and removed from both ends. The queue interface is extended by this interface. ArrayDeque is the class that implements this interface. Because this class implements the deque, we can use it to create a deque object.
- Set Interface : A set is an unordered group of objects in which duplicate values cannot be kept. This collection is utilised when we want to avoid duplication of things and only keep the ones that are unique. Various classes, such as HashSet, TreeSet, LinkedHashSet, and others, implement this set interface. We can create a set object with any of these classes because they all implement the set.
- Sorted Set Interface : This interface resembles the set interface in appearance. The only difference is that this interface provides additional methods for maintaining element ordering. The sorted set interface is an extension of the set interface that is used to manage sorted data. TreeSet is the class that implements this interface. We can create a SortedSet object using this class because it implements the SortedSet interface.
- Data Science
- All Events
- My Events
223. Difference between ArrayList and LinkedList.
ArrayList和LinkedList之间的区别。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb0819 | 官方: 否 | 付费: 否
答案:
| ArrayList | LinkedList |
|---|---|
| The elements of this class are stored in a dynamic array. This class now supports the storage of all types of objects thanks to the addition of generics. 此类的元素存储在动态数组中。由于引入了泛型,此类现在支持存储所有类型的对象。 | The elements of this class are stored in a doubly-linked list. This class, like the ArrayList, allows for the storage of any type of object. 此类的元素存储在双向链表中。与ArrayList一样,此类允许存储任何类型的对象。 |
| The List interface is implemented by this class. As a result, this serves as a list. 此类实现了List接口。因此,它充当一个列表。 | The List and Deque interfaces are both implemented by this class. As a result, it can be used as both a list and a deque. 此类同时实现了List和Deque接口。因此,它既可以用作列表,也可以用作双端队列。 |
| Because of the internal implementation, manipulating an ArrayList takes longer. Internally, the array is scanned and the memory bits are shifted whenever we remove an element. 由于内部实现,操作ArrayList需要更长的时间。在内部,当我们移除一个元素时,会扫描数组并移动内存位。 | Because there is no concept of changing memory bits in a doubly-linked list, manipulating it takes less time than manipulating an ArrayList. The reference link is changed after traversing the list. 因为在双向链表中没有改变内存位的概念,操作它比操作ArrayList花费的时间更少。遍历列表后,更改引用链接。 |
| This class is more useful when the application requires data storage and access. 当应用程序需要数据存储和访问时,此类更有用。 | This class is more useful when the application requires data manipulation. 当应用程序需要数据操作时,此类更有用。 |
224. Differentiate between ArrayList and Vector in java.
在Java中,ArrayList和Vector之间的区别。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb081c | 官方: 否 | 付费: 否
答案:
Following are the differences between ArrayList and Vector in java : - Vector is synchronized, which means that only one thread can access the code at a time, however, ArrayList is not synchronized, which means that multiple threads can operate on ArrayList at the same time. In a multithreading system, for example, if one thread is executing an add operation, another thread can be performing a removal action. If multiple threads access ArrayList at the same time, we must either synchronize the code that updates the list fundamentally or enable simple element alterations. The addition or deletion of element(s) from the list is referred to as structural change. It is not a structural change to change the value of an existing element.
以下是Java中ArrayList和Vector之间的区别:- Vector是同步的,这意味着同一时间只能有一个线程访问代码,然而ArrayList不是同步的,这意味着多个线程可以同时对ArrayList进行操作。例如,在多线程系统中,如果一个线程正在执行添加操作,另一个线程可以执行删除操作。如果多个线程同时访问ArrayList,我们必须从根本上同步更新列表的代码,或者允许简单的元素更改。从列表中增加或删除元素被称为结构更改。更改现有元素的值不是结构更改。
- Data Growth: Both ArrayList and Vector dynamically expand and shrink to make the most use of storage space, but the manner they do it is different. If the number of elements in an array exceeds its limit, ArrayList increments 50% of the current array size, while vector increments 100%, thereby doubling the current array size.
- Performance: ArrayList is faster than vector operations because it is non-synchronized, but vector operations are slower since they are synchronized (thread-safe). When one thread works on a vector, it acquires a lock on it, requiring any other threads working on it to wait until the lock is released.
- Vector can traverse over its elements using both Enumeration and Iterator, whereas ArrayList can only traverse using Iterator.
225. Differentiate between List and Set in Java.
在Java中,List和Set之间的区别。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb081f | 官方: 否 | 付费: 否
答案:
The List interface is used to keep track of an ordered collection. It is the Collection's child interface. It is an ordered collection of objects that allows for the storage of duplicate values. The insertion order is preserved in a list, which enables positional access and element insertion.
List接口用于跟踪有序集合。它是Collection的子接口。它是一个有序的对象集合,允许存储重复值。列表中保留了插入顺序,这实现了位置访问和元素插入。
The set interface is part of java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It's an interface for using the mathematical set. This interface inherits the Collection interface's methods and adds a feature that prevents duplicate elements from being inserted.
Set接口是java.util包的一部分,并扩展了Collection接口。它是一个无序的对象集合,其中不能存储重复值。它是用于数学集合的接口。此接口继承了Collection接口的方法,并添加了防止插入重复元素的功能。
| Set | List |
|---|---|
| It is an unordered sequence. 它是无序序列。 | It is an ordered sequence. 它是有序序列。 |
| Duplicate elements are not permitted in Set. Set中不允许重复元素。 | Duplicate elements are allowed in the list List中允许重复元素。 |
| Access to items from a certain position is not permitted. 不允许从特定位置访问项目。 | Elements can be accessed based on their position. 可以根据位置访问元素。 |
| A null element can only be stored once. 空元素只能存储一次。 | It is possible to store several null elements. 可以存储多个空元素。 |
226. Differentiate between Iterator and ListIterator in Java.
区分Java中的Iterator和ListIterator。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb0822 | 官方: 否 | 付费: 否
答案:
In Java's Collection framework, iterators are used to obtain elements one by one. It can be used on any type of Collection object. We can execute both read and remove operations using Iterator. Iterator must be used whenever we want to iterate elements in all Collection framework implemented interfaces, such as Set, List, Queue, and Deque, as well as all Map interface implemented classes. The only cursor accessible for the entire collection framework is the iterator.
在Java的Collection框架中,迭代器用于逐个获取元素。它可以用于任何类型的Collection对象。我们可以使用Iterator执行读取和删除操作。当我们想要遍历所有Collection框架实现接口(如Set、List、Queue和Deque)以及所有Map接口实现类中的元素时,必须使用Iterator。迭代器是整个集合框架可用的唯一游标。
ListIterator is only useful for classes that implement List collections, such as array lists and linked lists. It can iterate in both directions. When we wish to enumerate List elements, we must use ListIterator. This cursor has additional methods and capabilities than the iterator.
ListIterator仅对实现List集合的类有用,例如数组列表和链表。它可以双向迭代。当我们想要枚举List元素时,必须使用ListIterator。此游标比迭代器具有更多的方法和功能。
| Iterator | ListIterator |
|---|---|
| Only has the ability to traverse components in a Collection in a forward direction. 只能以正向方向遍历Collection中的组件。 | In both forward and backward orientations, can traverse components in a Collection. 可以以正向和反向两个方向遍历Collection中的组件。 |
| Iterators cannot be used to obtain indexes. 迭代器不能用于获取索引。 | It offers methods to get element indexes at any time while traversing List, such as next Index() and previous Index(). 它提供方法在遍历List时随时获取元素索引,例如next Index()和previous Index()。 |
| It aids in the traversal of Maps, Lists, and Sets. 它有助于遍历Map、List和Set。 | Only List may be traversed, not the other two. 只能遍历List,不能遍历其他两种。 |
| It throws a Concurrent Modification Exception since it can't add elements. 它抛出Concurrent Modification Exception,因为它不能添加元素。 | At any time, you can quickly add elements to a collection. 您可以随时快速向集合添加元素。 |
| next(), remove(), and has Next are some of the Iterator's functions (). next()、remove()和has Next是Iterator的一些函数。 | next(), previous(), has Next(), has Previous(), and add() are some of the List Iterator's methods next()、previous()、has Next()、has Previous()和add()是List Iterator的一些方法。 |
227. What is the difference between Array and Collection in java?
在Java中,Array和Collection有什么区别?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb0825 | 官方: 否 | 付费: 否
答案:
Array and Collection are equivalent in terms of storing object references and manipulating data, but they differ in a number of ways. The following are the primary distinctions between an array and a Collection:
在存储对象引用和操作数据方面,Array和Collection是等效的,但它们在许多方面有所不同。以下是数组和Collection之间的主要区别:
| Array | Collection |
|---|---|
| Arrays have a set size, which means that once we build one, we can't change it to meet our needs. 数组具有固定大小,这意味着一旦我们构建一个,就不能更改它以满足我们的需求。 | Collection are naturally grow-able and can be customized to meet our needs. We can change its size as per our requirement. Collection天然是可增长的,并且可以根据我们的需求进行自定义。我们可以根据需要更改其大小。 |
| When it comes to performance, Arrays are the preferred to Collection. 在性能方面,数组比Collection更受青睐。 | Considering performance, Collection are not preferred to Arrays. 考虑到性能,Collection不如数组受青睐。 |
| Only homogeneous data type elements can be stored in arrays. 数组中只能存储同质数据类型元素。 | Both homogeneous and heterogeneous components can be stored in a collection. 集合中可以存储同质和异质组件。 |
| Because arrays have no underlying data structure, there is no ready-made method support. 因为数组没有底层数据结构,所以没有现成的方法支持。 | Any collection class is built on a standard data structure, and so there is ready-made method support for every demand as a performance. These methods can be used directly, and we are not responsible for their implementation. 任何集合类都基于标准数据结构构建,因此对于每个需求都有现成的方法支持作为性能。这些方法可以直接使用,我们不负责它们的实现。 |
| Objects and primitives can both be stored in arrays. 数组可以存储对象和基本类型。 | Only object types can be stored in a collection. 集合中只能存储对象类型。 |
| When it comes to memory, Arrays are not preferred to Collection. 在内存方面,数组不如Collection受青睐。 | Considering memory, Collection are preferred to Arrays. 考虑到内存,Collection比数组更受青睐。 |
228. Can you add a null element into a TreeSet or HashSet?
你能向TreeSet或HashSet中添加空元素吗?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb0828 | 官方: 否 | 付费: 否
答案:
We can add null elements in a HashSet but we cannot add null elements in a TreeSet. The reason is that TreeSet uses the compareTo() method for comparing and it throws a NullPointerException when it encounters a null element.
我们可以在HashSet中添加空元素,但不能在TreeSet中添加空元素。原因是TreeSet使用compareTo()方法进行比较,当遇到空元素时会抛出NullPointerException。
229. What is a priority queue in Java?
Java中的优先级队列是什么?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb082b | 官方: 否 | 付费: 否
答案:
When the objects are meant to be processed in order of priority, a PriorityQueue is used. A Queue is known to follow the First-In-First-Out method, however, there are occasions when the components of the queue must be handled in order of priority, which is where the PriorityQueue comes into play. The priority heap is the foundation of the PriorityQueue. The members of the priority queue are ordered according to natural ordering or by a Comparator provided at queue construction time.
当对象需要按优先级顺序处理时,使用PriorityQueue。队列通常遵循先进先出(FIFO)方法,但有时队列中的组件必须按优先级顺序处理,这时PriorityQueue就派上了用场。优先级堆是PriorityQueue的基础。优先级队列的成员根据自然顺序或队列构造时提供的Comparator进行排序。
Serializable, Iterable, Collection, Queue interfaces are implemented by the PriorityQueue class in Java.
Java中的PriorityQueue类实现了Serializable、Iterable、Collection、Queue接口。
Successful Tech Career for FREE!
免费开启成功的科技职业生涯!
Successful Tech Career!
成功的技术职业生涯!
Interview Process
面试流程
CTC & Designation
CTC与职位级别
Projects on the Job
工作项目
Referral System
推荐系统
Try It Out
试试看
2 Lakh+ Roadmaps Created
已生成20万+职业规划
230. What are some of the best practices while using Java Collections?
使用Java Collections时,有哪些最佳实践?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb082e | 官方: 否 | 付费: 否
答案:
Following are some of the best practices while using Java Collections : - Selecting the appropriate Collection:Before we use a collection, we must choose the most relevant collection for the problem we are seeking to solve. If we pick the wrong one, our program may still run, but it will be inefficient. On the other hand, if we pick the right one, our solution will be a lot simpler and our program will run much faster.
以下是在使用 Java Collections 时的一些最佳实践:- 选择合适的 Collection:在使用集合之前,我们必须为要解决的问题选择最相关的集合。如果我们选错了,程序可能仍然能运行,但效率会很低。另一方面,如果我们选对了,解决方案会简单得多,程序运行速度也会快得多。
- Specifying the initial capacity of the Collection :Almost all collection classes contain an overloaded constructor that determines the collection's initial capacity. That is, if we know exactly how many pieces will be added to the collection, we can define the initial capacity when establishing a new instance.
- Using isEmpty() instead of size():To check if a collection is empty or not we should use the isEmpty() method rather than finding the size of the collection and comparing it with zero. This enhances the readability of the code.
- Using Iterators for iterating over the collections:We should use iterators for traversing over the collection elements instead of using a for loop for the same. The reason is that the iterator may throw ConcurrentModificationException if any other thread tries to modify the collection after the iterator has been created. This saves us from bugs.
- Using Concurrent Collections over synchronized wrappers:Instead of utilizing the synchronized collections generated by the Collections.synchronizedXXX() methods, we should consider using concurrent collections from the java.util.concurrent package in multi-threaded applications. Because concurrent collections employ various synchronization strategies such as copy-on-write, compare-and-swap, and specific locks, they are designed to give maximum performance in concurrent applications.
- Eliminating Unchecked warnings:We should not disregard unchecked warnings from the Java compiler. The ideal practice is to get rid of any warnings that aren't checked.
- Favoring Generic types:We should build new methods with generic parameters in mind, and convert existing methods to use type parameters, just as we should with generic types because generic methods are safer and easier to use than non-generic ones. Generic methods also aid in the creation of APIs that are both general and reusable.
231. Differentiate between Set and Map in Java.
在 Java 中区分 Set 和 Map。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb0831 | 官方: 否 | 付费: 否
答案:
The Set interface is provided by the Java.util package. The set interface is established by extending the collection interface. We can't add the same element to it since it won't let us. Because it contains elements in a sorted order, it does not keep the insertion order. The Set interface in Java is used to build the mathematical Set.
Set 接口由 Java.util 包提供。Set 接口通过扩展 Collection 接口而建立。我们不能向其中添加相同的元素,因为它不允许这样做。由于它以排序顺序包含元素,因此它不保持插入顺序。Java 中的 Set 接口用于构建数学意义上的 Set。
Map is similar to Set in that it is used to store a collection of objects as a single entity. A key-value pair is used to store each object. Because each value is associated with a unique key, we can quickly obtain the value using just the key.
Map 与 Set 类似,它用于将对象集合存储为单个实体。每个对象都以键值对的形式存储。由于每个值都与一个唯一的键相关联,我们仅使用键就可以快速获取值。
| Set | Map |
|---|---|
| It cannot have values that are repeated. It is not possible to add the same elements to a set. Only the unique value is stored in each class that implements the Set interface. 它不能有重复的值。无法向 Set 中添加相同的元素。实现 Set 接口的每个类只存储唯一的值。 | It is possible for different keys to have the same value. The map has a unique key and values that are repeated. 不同的键可以具有相同的值。Map 具有唯一的键,但值可以重复。 |
| Using the keyset() and entryset() methods, we can quickly iterate the Set items. 使用 keyset() 和 entryset() 方法,我们可以快速迭代 Set 项。 | It is not possible to iterate across map elements. To iterate the elements, we must convert Map to Set. 无法直接迭代 Map 元素。要迭代元素,我们必须将 Map 转换为 Set。 |
| The Set interface does not keep track of insertion order. Some of its classes, such as LinkedHashSet, however, keep the insertion order. Set 接口不跟踪插入顺序。然而,它的一些类(如 LinkedHashSet)会保持插入顺序。 | The Map does not keep track of the insertion sequence. Some Map classes, such as TreeMap and LinkedHashMap, do the same thing. Map 不跟踪插入顺序。一些 Map 类(如 TreeMap 和 LinkedHashMap)也如此。 |
232. Differentiate between HashSet and HashMap.
区分 HashSet 和 HashMap。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb083a | 官方: 否 | 付费: 否
答案:
HashSet is a Set Interface implementation that does not allow duplicate values. The essential point is that objects stored in HashSet must override equals() and hashCode() methods to ensure that no duplicate values are stored in our set.
HashSet 是 Set 接口的实现,不允许有重复值。关键的一点是,存储在 HashSet 中的对象必须重写 equals() 和 hashCode() 方法,以确保集合中不存储重复值。
HashMap is a Map Interface implementation that maps a key to a value. In a map, duplicate keys are not permitted.
HashMap 是 Map 接口的实现,它将键映射到值。在 Map 中,不允许有重复的键。
| HashSet | HashMap |
|---|---|
| It implements the Set Interface. 它实现 Set 接口。 | It implements the Map Interface. 它实现 Map 接口。 |
| It does not allow duplicate values. 它不允许重复值。 | The key needs to be unique while two different keys can have the same value. 键必须唯一,而两个不同的键可以有相同的值。 |
| While adding an element it requires only one object as a parameter. 添加元素时,它只需要一个对象作为参数。 | While adding an entry, it requires two object values, the Key and the Value as the parameter. 添加条目时,它需要两个对象值(键和值)作为参数。 |
| Internally, HashSet uses HashMap to add entries. The key K in a HashSet is the argument supplied in the add(Object) method. For each value supplied in the add(Object) method, Java assigns a dummy value. 在内部,HashSet 使用 HashMap 来添加条目。HashSet 中的键 K 是 add(Object) 方法中提供的参数。对于 add(Object) 方法中提供的每个值,Java 都会分配一个虚拟值。 | There is no concept of duplicate values. 不存在重复值的概念。 |
| It is slower than HashMap. 它比 HashMap 慢。 | It is faster than HashSet. 它比 HashSet 快。 |
| It uses the add() method for adding elements. 它使用 add() 方法添加元素。 | It uses the put() method for adding data elements. 它使用 put() 方法添加数据元素。 |
233. What is the default size of the load factor in hashing based collection?
基于哈希的集合中加载因子的默认大小是多少?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb083d | 官方: 否 | 付费: 否
答案:
The default load factor size is 0.75 . The default capacity is calculated by multiplying the initial capacity by the load factor.
默认加载因子大小为 0.75。默认容量通过将初始容量乘以加载因子来计算。
234. Differentiate between Array and ArrayList in Java.
在 Java 中区分 Array 和 ArrayList。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb0840 | 官方: 否 | 付费: 否
答案:
Following are the differences between Arrays and ArrayLists in Java :
以下是 Java 中 Arrays 和 ArrayLists 之间的区别:
- Java provides arrays as a fundamental functionality. ArrayList is a component of Java's collection system. As a result, It is used to access array members, while ArrayList provides a set of methods for accessing and modifying components.
- ArrayList is not a fixed-size data structure, but Array is. When creating an ArrayList object, there is no need to provide its size. Even if we set a maximum capacity, we can add more parts afterward.
- Arrays can include both primitive data types and class objects, depending on the array's definition. ArrayList, on the other hand, only accepts object entries and not primitive data types. Note that when we use arraylist.add(1);, the primitive int data type is converted to an Integer object.
- Members of ArrayList are always referencing to objects at various memory locations since ArrayList can't be constructed for primitive data types As a result, the actual objects in an ArrayList are never kept in the same place. The references to the real items are maintained in close proximity. Whether an array is primitive or an object depends on the type of the array. Actual values for primitive kinds are continuous regions, whereas allocation for objects is equivalent to ArrayList.
- Many other operations, such as indexOf() and delete(), are supported by Java ArrayList. Arrays do not support these functions.
235. How can you make an ArrayList read-only in Java?
如何在 Java 中使 ArrayList 变为只读?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, data-structures;标签: interviewbit, java-collections, topic-specific, java, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7258d557c902bb0843 | 官方: 否 | 付费: 否
答案:
With the help of Collections.unmodifiableList() method, we can easily make an ArrayList read-only. This function takes a changeable ArrayList as an input and returns the ArrayList's read-only, unmodified view.
借助 Collections.unmodifiableList() 方法,我们可以轻松地将 ArrayList 变为只读。该函数将可修改的 ArrayList 作为输入,并返回 ArrayList 的只读、不可修改视图。
Example:
示例:
import java.util.*;
import java.util.*;
public class InterviewBit {
public class InterviewBit {
public static void main(String[] args)
public static void main(String[] args)
throws Exception
throws Exception
{
try {
try {
// creating object of ArrayList
// 创建 ArrayList对象
Listsample_list = new ArrayList ();
Listsample_list = new ArrayList ();
sample_list.add(“practice”);
sample_list.add(“practice”);
sample_list.add(“solve”);
sample_list.add(“solve”);
sample_list.add(“interview”);
sample_list.add(“interview”);
// displaying the initial list
// 显示初始列表
System.out.println("The initial list is : "
System.out.println("The initial list is : "
sample_list);
- sample_list);
// using unmodifiableList() method
// 使用 unmodifiableList() 方法
List
List
read_only_list = Collections
read_only_list = Collections
.unmodifiableList(sample_list);
.unmodifiableList(sample_list);
// displaying the read-only list
// 显示只读列表
System.out.println("The ReadOnly ArrayList is : "
System.out.println("The ReadOnly ArrayList is : "
read_only_list);
- read_only_list);
// Trying to add an element to the read-only list
// 尝试向只读列表添加元素
System.out.println("Trying to modify the ReadOnly ArrayList.");
System.out.println("尝试修改只读ArrayList。");
read_only_list.add(“job”);
read_only_list.add("job");
}
catch (UnsupportedOperationException e) {
catch (UnsupportedOperationException e) {
System.out.println("The exception thrown is : " + e);
System.out.println("抛出的异常是:" + e);
}
}
}
Output:
输出:
The initial list is : [practice, solve, interview]
初始列表是:[practice, solve, interview]
The ReadOnly ArrayList is : [practice, solve, interview]
只读ArrayList是:[practice, solve, interview]
Trying to modify th eReadOnly ArrayList.
尝试修改只读ArrayList。
Exception thrown : java.lang.UnsupportedOperationException
抛出的异常:java.lang.UnsupportedOperationException
We can see that as we try to add an element to a read-only ArrayList we get an exception thrown.
我们可以看到,当我们尝试向只读ArrayList添加元素时,会抛出异常。
236. What is the difference between str1 == str2 and str1.equals(str2)?
str1 == str2和str1.equals(str2)之间有什么区别?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c55 | 官方: 否 | 付费: 否
答案:
Java offers both the equals() method and the "==" operator for comparing objects. However, here are some differences between the two: - Essentially, equals() is a method, while == is an operator.
Java提供了equals()方法和"=="运算符来比较对象。然而,两者之间有一些区别:- 本质上,equals()是一个方法,而==是一个运算符。
The == operator can be used for comparing references (addresses) and the .equals() method can be used to compare content. To put it simply, == checks if the objects point to the same memory location, whereas .equals() compares the values of the objects.
Example:示例:
public class StringComparison
public class StringComparison
{
public static void main(String[] args)
public static void main(String[] args)
{
String str1=new String("Scaler");
String str1=new String("Scaler");
String str2=new String("Scaler");
String str2=new String("Scaler");
System.out.println(str1 == str2);
System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
System.out.println(str1.equals(str2));
}
}
Output:
输出:
false
false
true
true
In this example, two different String objects are being created, str1 and str2. - If str1 and str2 are compared using the == operator, then the result will be false, because both have different addresses in the memory. Both must have the same address in the memory for the result to be true.
在这个例子中,创建了两个不同的字符串对象,str1 和 str2。 - 如果使用 == 运算符比较 str1 和 str2,那么结果将是 false,因为两者在内存中具有不同的地址。要使结果为 true,两者在内存中必须具有相同的地址。
- If you use the equals method, the result is true since it's only comparing the values given to str1 and str2, even though they are different objects.
237. Is String a primitive or derived type in Java?
在Java中,String是基本类型还是派生类型?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c59 | 官方: 否 | 付费: 否
答案:
Strings are derived data types. Strings are Java objects that represent sequences of characters. String objects are created using the java.lang.String class. There are many functions that need to be called upon when processing a string, such as substring(), indexof(), equals(), toUppercase(), etc, which primitives types do not have.
字符串是派生数据类型。字符串是表示字符序列的Java对象。字符串对象是使用 java.lang.String 类创建的。处理字符串时需要调用许多函数,例如 substring()、indexof()、equals()、toUppercase() 等,这些是基本类型所不具备的。
238. State the difference between String in C and String in Java.
说明C语言中的String和Java中的String之间的区别。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c5c | 官方: 否 | 付费: 否
答案:
- String in C: In C, strings are just arrays of characters, and they are terminated with a /0, which is why we commonly refer to them as "null-terminated". Strings in C, like "abc$%", actually consist of 6 characters 'a' 'b' 'c' '$' '%' and '/0', but these can be easily manipulated.
- String in Java: Java treats Strings as objects, not arrays. String objects are created using the java.lang.String class. String objects in Java are immutable; you cannot modify their contents. This means whenever we manipulate a String object, the new String is created rather than the original string being modified.
239. Explain String pool in Java.
解释Java中的字符串池。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c5f | 官方: 否 | 付费: 否
答案:
String Pool, also known as SCP (String Constant Pool), is a special storage space in Java heap memory that is used to store unique string objects. Whenever a string object is created, it first checks whether the String object with the same string value is already present in the String pool or not, and if it is available, then the reference to the string object from the string pool is returned. Otherwise, the new string object is added to the string pool, and the respective reference will be returned.
字符串池,也称为SCP(字符串常量池),是Java堆内存中的一个特殊存储空间,用于存储唯一的字符串对象。每当创建一个字符串对象时,它首先检查字符串池中是否已经存在具有相同字符串值的字符串对象,如果存在,则返回字符串池中该字符串对象的引用。否则,将新的字符串对象添加到字符串池中,并返回相应的引用。
As shown in the above image, two Strings s1 and s2 are created with the values "Apple" and "Mango". Therefore, when the third String s3 containing the value "Apple" is created, instead of creating a new object, the existing object reference will be returned. Here, s1==s2 is false both strings s1 and s2 refer to different string values from the string pool i.e. apple and mango. We can see that s1==s3 is true because both strings s1 and s3 refer to a single string value from a string pool i.e., apple.
如上图所示,创建了两个字符串 s1 和 s2,其值分别为“Apple”和“Mango”。因此,当创建包含值“Apple”的第三个字符串 s3 时,不会创建新对象,而是返回现有对象的引用。在这里,s1==s2 为 false,因为两个字符串 s1 和 s2 引用字符串池中的不同字符串值,即 apple 和 mango。我们可以看到 s1==s3 为 true,因为字符串 s1 和 s3 都引用字符串池中的单个字符串值,即 apple。
240. Is String immutable or final in Java? If so, then what are the benefits of Strings being Immutable?
在Java中,String是不可变还是final?如果是,那么字符串不可变的好处是什么?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c62 | 官方: 否 | 付费: 否
答案:
Yes, Strings are immutable in Java. Immutable objects mean they can't be changed or altered once they've been created. However, we can only modify the reference to the string object. The String is immutable in Java because of many reasons like security, caching, synchronization and concurrency, and class loading.
是的,Java中的String是不可变的。不可变对象意味着一旦创建,它们就不能被更改或修改。然而,我们只能修改对字符串对象的引用。Java中的String不可变的原因有很多,如安全性、缓存、同步和并发性以及类加载。
- Data Science
- All Events
- My Events
241. What does the string intern() method do in Java?
在Java中,字符串的 intern() 方法有什么作用?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c65 | 官方: 否 | 付费: 否
答案:
If you apply the intern() method to a few strings, you will ensure that all strings having the same content share the same memory. As soon as a String object is invoked with intern(), it first checks if the string value of the String object is already present in the string pool and if it is available, then the reference to that string from the string constant pool is returned. If not, a new string object is added to the string pool, and a reference to it is returned.
如果对几个字符串应用 intern() 方法,你将确保所有具有相同内容的字符串共享相同的内存。当字符串对象调用 intern() 时,它首先检查该字符串对象的值是否已经存在于字符串池中,如果存在,则返回字符串常量池中该字符串的引用。如果不存在,则将新的字符串对象添加到字符串池中,并返回对其的引用。
Example:
示例:
String str1 = new String("Scaler by InterviewBit").intern(); //Line1
String str1 = new String("Scaler by InterviewBit").intern(); //第1行
String str2 = new String("Scaler by InterviewBit").intern(); //Line2
String str2 = new String("Scaler by InterviewBit").intern(); //第2行
System.out.println(str1 == str2); //prints true
System.out.println(str1 == str2); //打印true
As you can see, the intern() method is invoked on the String objects. When Line1 is executed, memory is allocated within the SCP. In line 2, no new string objects are created in the SCP because str1 and str2 have the same content. As a result, the reference to the object created in line1 is returned. This means that str1 and str2 both point to the same memory. Therefore, the print statement prints true.
正如你所看到的,intern() 方法被调用在字符串对象上。当执行第1行时,内存被分配在SCP内。在第2行中,由于str1和str2具有相同的内容,因此在SCP中不会创建新的字符串对象。结果,返回第1行中创建的对象的引用。这意味着str1和str2都指向相同的内存。因此,打印语句打印true。
242. State the difference between String and StringBuffer.
说明String和StringBuffer之间的区别。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c68 | 官方: 否 | 付费: 否
答案:
String objects in Java are immutable and final, so we can't change their value after they are created. Since strings are commonly used in applications, we need to perform several operations on them such as substring(), equals(), indexof(), toUppercase(), etc. Each time we manipulate a string, a new String object is created, and all previous objects will be garbage, placing a strain on the garbage collector. This is why The Java team developed StringBuffer. A StringBuffer is a mutable object, meaning it can be changed, but the string is an immutable object, so it cannot be changed once it has been created. - String
Java中的String对象是不可变且final的,所以一旦创建后我们无法更改它们的值。由于字符串在应用程序中经常使用,我们需要对它们执行多种操作,比如substring()、equals()、indexof()、toUppercase()等。每次我们操作一个字符串时,都会创建一个新的String对象,并且所有之前的对象都会变成垃圾,给垃圾收集器带来压力。这就是Java团队开发StringBuffer的原因。StringBuffer是一个可变对象,意味着它可以被更改,但字符串是不可变对象,所以一旦创建就不能被更改。- String
Syntax:
语法:
String str1="InterviewBit";
String str1="InterviewBit";
String str2=new String("Scaler");
String str2=new String("Scaler");
Scanner str3=new Scanner(System.in);
Scanner str3=new Scanner(System.in);
String str4=str3.nextLine();
String str4=str3.nextLine();
Example: Concatenation Example of String. A string class takes longer to perform a concatenation operation than a string buffer class.
示例:String的连接示例。字符串类执行连接操作所需的时间比字符串缓冲类更长。
public class Scanner
public class Scanner
{
public static void main(String []args)
public static void main(String []args)
{
StringBuilder stbu=new StringBuilder();
StringBuilder stbu=new StringBuilder();
//Initial object size
//初始对象大小
System.out.println(stbu.capacity());
System.out.println(stbu.capacity());
String str="Scaler";
String str="Scaler";
System.out.println(str);
系统.输出.打印行(str);
String str1 = new String("InterviewBit");
String str1 = new String("InterviewBit");
System.out.println(str1);
System.out.println(str1);
str1 += " Articles"; //string update
str1 += " Articles"; //字符串更新
System.out.println(str1);
System.out.println(str1);
}
}
Output:
输出:
16
Scaler
Scaler
InterviewBit
InterviewBit
InterviewBit Articles
InterviewBit 文章
- StringBuffer
Syntax:
语法:
StringBuffer var = new StringBuffer(str);
StringBuffer var = new StringBuffer(str);
Example: Concatenation Example of StringBuffer. String buffer class perform concatenation operations more quickly than string classes.
示例:StringBuffer 的拼接示例。StringBuffer 类执行拼接操作比字符串类更快。
public class StringBuffer
public class StringBuffer
{
public static void main(String []args)
public static void main(String []args)
{
StringBuilder stbu=new StringBuilder();
StringBuilder stbu=new StringBuilder();
//Initial object size
//初始对象大小
System.out.println(stbu.capacity());
System.out.println(stbu.capacity());
StringBuffer stbr= new StringBuffer("InterviewBit");
StringBuffer stbr= new StringBuffer("InterviewBit");
System.out.println(stbr);
System.out.println(stbr);
stbr.append(" Articles"); //string update
stbr.append(" Articles"); //字符串更新
System.out.println(stbr);
System.out.println(stbr);
stbr=new StringBuffer("Scaler");
stbr=new StringBuffer("Scaler");
System.out.println(stbr);
System.out.println(stbr);
}
}
Output:
输出:
16
InterviewBit
InterviewBit
InterviewBit Articles
InterviewBit 文章
Scaler
Scaler
243. State the difference between StringBuffer and StringBuilder in Java.
说明Java中StringBuffer和StringBuilder之间的区别。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c6b | 官方: 否 | 付费: 否
答案:
StringBuffer and StringBuilder are two Java classes for manipulating strings. These are mutable objects, i.e., they can be modified, and provide various methods such as insert(), substring(), delete(), and append(), for String manipulation. - StringBuffer: The StringBuffer class was created by the Java Team when they realized the need for an editable string object. Nevertheless, StringBuffer has all methods synchronized, meaning they are thread-safe. Therefore, StringBuffer allows only one thread to access a method at once, so it is not possible to call StringBuffer methods from two threads simultaneously, which means it takes more time to access. The StringBuffer class has synchronized methods, making it thread-safe, slower, and less efficient than StringBuilder. The StringBuffer class was introduced in Java 1.0.Syntax:
StringBuffer和StringBuilder是用于操作字符串的两个Java类。它们是可变对象,即可以被修改,并提供各种方法,如insert()、substring()、delete()和append(),用于字符串操作。- StringBuffer: Java团队在意识到需要可编辑的字符串对象时创建了StringBuffer类。然而,StringBuffer的所有方法都是同步的,这意味着它们是线程安全的。因此,StringBuffer一次只允许一个线程访问一个方法,所以不能同时从两个线程调用StringBuffer方法,这意味着访问时需要更多时间。StringBuffer类具有同步方法,使其线程安全,但比StringBuilder更慢、效率更低。StringBuffer类是在Java 1.0中引入的。语法:
StringBuffer var = new StringBuffer(str); - StringBuilder: It was at that point that the Java Team realized that making all methods of StringBuffer synchronized wasn't the best idea, which led them to introduce StringBuilder. The StringBuilder class has no synchronized methods. Unlike StringBuffer, StringBuilder does not offer synchronized methods, which makes it less thread-safe, faster, and more efficient. StringBuilder was introduced in Java 1.5 in response to StringBuffer's shortcomings.Syntax:
StringBuffer var = new StringBuffer(str); - StringBuilder: 正是在那时,Java团队意识到让StringBuffer的所有方法都同步并不是最好的主意,这促使他们引入了StringBuilder。StringBuilder类没有同步方法。与StringBuffer不同,StringBuilder不提供同步方法,这使得它的线程安全性较低,但更快、更高效。StringBuilder是在Java 1.5中为应对StringBuffer的缺陷而引入的。语法:
StringBuilder var = new StringBuilder(str);
StringBuilder var = new StringBuilder(str);
244. In Java, how can two strings be compared?
在Java中,如何比较两个字符串?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c6e | 官方: 否 | 付费: 否
答案:
In Java, there are several ways for comparing two strings. The following are a few of them: - String Equals Method: In this method, the strings are compared based on the values within them. If the values of the two strings are the same, it returns true; otherwise, it returns false. This method is case-sensitive.
在Java中,有几种方法可以比较两个字符串。以下是其中几种:- String Equals方法:在这种方法中,字符串根据其中的值进行比较。如果两个字符串的值相同,则返回true;否则,返回false。此方法区分大小写。
Syntax:
语法:
str1.equals(str2);
str1.equals(str2);
For example:
例如:
Input 1= Scaler
输入 1 = Scaler
Input 2= InterviewBit
输入 2 = InterviewBit
Output= false
输出= false
Input 1= Scaler
输入 1 = Scaler
Input 2= Scaler
输入 2 = Scaler
Output= true
输出= true
Input 1= Scaler
输入 1 = Scaler
Input 2= scaler
输入2= scaler
Output= false
输出= false
- String Equals Ignore Case: By using this method, the two strings are compared without taking into account the case (upper or lower). It returns true if the two values are the same and not null.Syntax:
str1.equalsIgnoreCase(str2);
str1.equalsIgnoreCase(str2);
For Example:
例如:
Input 1= Scaler
输入 1 = Scaler
Input 2= InterviewBit
输入 2 = InterviewBit
Output= false
输出= false
Input 1= Scaler
输入 1 = Scaler
Input 2= Scaler
输入 2 = Scaler
Output= true
输出= true
Input 1= Scaler
输入 1 = Scaler
Input 2= scaler
输入2= scaler
Output= true
输出= true
- Object Equals Method: The method returns true if its arguments are equal, otherwise, it returns false. Accordingly, if both arguments are null, the result is true, and if just one argument is null, the result is false.
Syntax:
语法:
Object.equals(str1, str2)
Object.equals(str1, str2)
For example:
例如:
Input 1= Scaler
输入 1 = Scaler
Input 2= InterviewBit
输入 2 = InterviewBit
Output= false
输出= false
Input 1= Scaler
输入 1 = Scaler
Input 2= Scaler
输入 2 = Scaler
Output= true
输出= true
Input 1= Scaler
输入 1 = Scaler
Input 2= null
输入2= null
Output= false
输出= false
Input 1= null
输入1= null
Input 2= null
输入2= null
Output= True
输出= True
- String Compare To Method: This method compares input strings with each other. Upon comparison, the following value is returned:
If (str1>str2), a positive value is returned.
- 如果(str1>str2),返回一个正值。
If (str1==str2), 0 is returned.
- 如果(str1==str2),返回0。
If (str1Syntax:
- 如果(str1Syntax:
str1.compareTo(str2)
str1.compareTo(str2)
Example:
示例:
Input 1= InterviewBit
输入1= InterviewBit
Input 2= Scaler
输入 2 = Scaler
Output= -10
输出= -10
Input 1= Scaler
输入 1 = Scaler
Input 2= Scaler
输入 2 = Scaler
Output= 0
输出 = 0
Input 1= Scaler
输入 1 = Scaler
Input 2= InterviewBit
输入 2 = InterviewBit
Output= 10
输出 = 10
245. How to declare a string in Java?
如何在Java中声明字符串?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c71 | 官方: 否 | 付费: 否
答案:
String declaration in Java can be done in two ways: - By string literal: Double quotes are used to create Java String literals. Example: String str= "Scaler";
在Java中,字符串声明可以通过两种方式完成:- 通过字符串字面量:双引号用于创建Java字符串字面量。例如:String str= "Scaler";
- By new keyword: Keyword "new" is used to create a Java string.Example: String str=new String ("Scaler");
246. Is it possible to compare Strings using the == operator? If so, what is the risk involved?
是否可以使用 == 运算符比较字符串?如果可以,其中涉及的风险是什么?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c74 | 官方: 否 | 付费: 否
答案:
Yes, you can compare strings using the == operator. One can use == operators for reference comparison (address comparison). The majority of the time, developers compare strings with the == operator, instead of using the equals() method, resulting in an error.
是的,你可以使用 == 运算符比较字符串。可以使用 == 运算符进行引用比较(地址比较)。大多数情况下,开发人员使用 == 运算符比较字符串,而不是使用 equals() 方法,这会导致错误。
Example:
示例:
public class StringComparison
public class StringComparison
{
public static void main(String args[])
public static void main(String args[])
{
String str1="Scaler";
String str1="Scaler";
String str2="Scaler";
String str2="Scaler";
String str3=new String("Scaler");
String str3=new String("Scaler");
System.out.println(str1==str2);
System.out.println(str1==str2);
//true because both points to same memory allocation
//true,因为两者指向相同的内存分配
System.out.println(str1==str3);
System.out.println(str1==str3);
//false because str3 refers to instance created in heap
//false 因为str3引用的是堆中创建的实例
System.out.println(str1.equals(str3));
System.out.println(str1.equals(str3));
//true because both share same content
//true 因为两者共享相同的内容
//even if both are different string objects
//即使它们是不同的字符串对象
}
}
Output:
输出:
true
true
false
false
true
true
247. What is the use of the substring() method in Java?
Java中的substring()方法有什么用途?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c77 | 官方: 否 | 付费: 否
答案:
The substring method is used to return substring from a specified string. This method takes two parameters i.e., beginIndex (the starting index) and endIndex (the ending index). In the case of substring(), method startIndex is inclusive and endIndex is exclusive.
substring方法用于从指定字符串中返回子字符串。该方法接受两个参数,即beginIndex(起始索引)和endIndex(结束索引)。对于substring()方法,startIndex包含在内,endIndex不包含在内。
Syntax:
语法:
substring(int beginIndex, int endIndex)
substring(int beginIndex, int endIndex)
Or
或者
substring(int beginIndex)
substring(int beginIndex)
Here, - beginIndex: Index that marks the starting of subsequence and it is inclusive.
这里,- beginIndex:标记子序列起始的索引,且包含该索引。
endIndex: Index that marks the ending of subsequence and it is exclusive.
Example:示例:
import java.lang.Math;
import java.lang.Math;
public class InterviewBit
public class InterviewBit
{
// driver code
// 驱动程序代码
public static void main(String args[])
public static void main(String args[])
{
String str = "Scaler by InterviewBit";
String str = "Scaler by InterviewBit";
//prints substring from 7th index
//打印从第7个索引开始的子字符串
System.out.print("Returns: ");
System.out.print("Returns: ");
System.out.println(str.substring(7));
System.out.println(str.substring(7));
// prints substring from 0-6, exclusive 6th index
// 打印从索引0到6的子字符串,不包含第6个索引
System.out.print("Returns: ");
System.out.print("Returns: ");
System.out.println(str.substring(0, 6));
System.out.println(str.substring(0, 6));
// prints the substring from 10-22, exclusive 22th index
// 打印从索引10到22的子字符串,不包含第22个索引
System.out.print("Returns: ");
System.out.print("Returns: ");
System.out.println(str.substring(10, 22));
System.out.println(str.substring(10, 22));
}
}
Output:
输出:
Returns: by InterviewBit
返回值:by InterviewBit
Returns: Scaler
返回值:Scaler
Returns: InterviewBit
返回值:InterviewBit
Successful Tech Career for FREE!
免费开启成功的科技职业生涯!
Successful Tech Career!
成功的技术职业生涯!
Interview Process
面试流程
CTC & Designation
CTC与职位级别
Projects on the Job
工作项目
Referral System
推荐系统
Try It Out
试试看
2 Lakh+ Roadmaps Created
已生成20万+职业规划
248. Can we use a string in the switch case in java?
在Java中,我们可以在switch case中使用字符串吗?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: interviewbit, java-string, topic-specific, java)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b7658d557c902bb0c7a | 官方: 否 | 付费: 否
答案:
Yes, Java allows you to use strings in switch case conditions. Below is a Java program that shows the use of string in switch case.
是的,Java允许你在switch case条件中使用字符串。下面是一个展示在switch case中使用字符串的Java程序。
Example:
示例:
public class StringinSwitchCase
public class StringinSwitchCase
{
public static void main(String[] args)
public static void main(String[] args)
{
String fruit = "Apple";
String fruit = "Apple";
switch(fruit)
switch(fruit)
{
case "Mango":
case "Mango":
System.out.println("Sweet");
System.out.println("甜");
break;
break;
case "Apple":
case "Apple":
System.out.println("Delicious");
System.out.println("Delicious");
break;
break;
case "Orange":
case "Orange":
System.out.println("Luscious");
System.out.println("Luscious");
break;
break;
default:
default:
System.out.println("Not a fruit");
System.out.println("Not a fruit");
}
}
}
Output:
输出:
Delicious
Delicious
249. Problem statement: You are given the head of a linked list, to determine whether the cycle is present in the linked list.
问题陈述:给定一个链表的头节点,判断链表中是否存在环。
- 知识点: 算法与数据结构 (标签: interviewbit, jp-morgan, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 摩根大通
- id: 69b37b7c58d557c902bb10d8 | 官方: 否 | 付费: 否
答案:
Input Format:
输入格式:
You are required to complete bool hasCycle(ListNode* head) function.
您需要完成bool hasCycle(ListNode* head)函数。
Output:
输出:
True: If loop or cycle is present
True:如果存在循环或环
False: Otherwise
False:否则
Constraints:
约束:
1 -10^5 Time Limit: 1 sec
1 -10^5 时间限制:1秒
Sample Input 1:
样本输入 1:
Sample Output 1:
样本输出 1:
True
True
Sample Input 2:
样本输入 2:
Sample Output 2:
样本输出 2:
False
False
Approach
方法
To solve this problem, you need to go back to your high school physics. Let us consider a scenario in which you and one of your friends are running on a circular track but with different speeds. You both started running at the same point initially. Now a moment would come when you both again meet at some position.
要解决此问题,你需要回顾高中物理知识。让我们考虑一个场景:你和一位朋友在圆形跑道上以不同的速度跑步。你们最初从同一点开始跑。那么会出现一个时刻,你们两人再次在某个位置相遇。
We can use this concept to solve this problem.
我们可以利用此概念来解决这个问题。
Source Code:
源代码:
/**
Definition for singly-linked list.
- 单链表的定义。
struct ListNode {
- struct ListNode {
int val;
- int val;
ListNode *next;
- ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
- ListNode(int x) : val(x), next(NULL) {}
};
*/
class Solution {class Solution {
public:
public:
bool hasCycle(ListNode *head) {
bool hasCycle(ListNode *head) {
/*
slow pointer moves one step forward at a time
慢指针每次向前移动一步
fast pointer moves two step forward at a time
快指针每次向前移动两步
*/
ListNode* slow = head;
ListNode* slow = head;
ListNode* fast = head;
ListNode* fast = head;
/*
Iterating using do while loop to check
使用 do-while 循环进行迭代检查
*/
do
do
{
/*
Since, fast pointer moves faster
由于快指针移动得更快
hence if loop is not present in the linked list
因此如果链表中不存在循环
then it will the first to encounter NULL
它将首先遇到 NULL
*/
if(!fast)
if(!fast)
return false;
返回 false;
/*
Otherwise we will move slow pointer and fast pointer
否则,我们将移动慢指针和快指针
one step forward
向前一步
If fast pointer is not NULL then we will move
如果快指针不为 NULL,则我们将移动
fast pointer again one step forward
快指针再次向前移动一步
Otherwise, we would return false
否则,我们将返回false
*/
slow = slow -> next;
slow = slow -> next;
fast = fast -> next;
fast = fast -> next;
if(fast)
if(fast)
fast = fast -> next;
fast = fast -> next;
else
else
return false;
返回 false;
}
while(slow != fast);
while(slow != fast);
/*
If everything remains fine that it means both pointers
如果一切正常,这意味着两个指针
now point to the same node
现在指向同一个节点
Hence, we will return true
因此,我们将返回true
*/
return true;
返回 true;
}
};
250. How will you modify a linked list of integers so that all even numbers appear before all odd numbers in the modified linked list? Also, keep the even and odd numbers in the same order.
你将如何修改一个整数链表,使得修改后的链表中所有偶数都出现在所有奇数之前?同时,保持偶数和奇数原有的顺序。
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b8558d557c902bb16bf | 官方: 否 | 付费: 否
答案:
Example: Input: 17->15->8->12->10->5->4->1->7->6->NULL Output: 8->12->10->4->6->17->15->5->1->7->NULL
示例:输入:17->15->8->12->10->5->4->1->7->6->NULL 输出:8->12->10->4->6->17->15->5->1->7->NULL
Algorithm: The approach is to divide the linked list into two sections, one with all even nodes and the other with all odd nodes. In order to split the Linked List, traverse the original Linked List and move all odd nodes to a new Linked List. The original list will include all the even nodes at the end of the loop, while the odd node list will have all the odd nodes. We must place all the odd nodes at the end of the odd node list to maintain the same ordering of all nodes. And, in order to do it in real-time, we'll need to maintain track of the last pointer in the odd node list. Finally, the odd node linked list is to be attached after the even node linked list.
算法:该方法是将链表分成两部分,一部分包含所有偶数节点,另一部分包含所有奇数节点。为了拆分链表,遍历原始链表并将所有奇数节点移动到新链表。循环结束后,原始链表将包含所有偶数节点,而奇数节点链表将包含所有奇数节点。我们必须将所有奇数节点放在奇数节点链表的末尾,以保持所有节点的相同顺序。并且,为了实时完成,我们需要跟踪奇数节点链表中的末尾指针。最后,将奇数节点链表附加到偶数节点链表之后。
Implementation:
实现:
Node separateEvenOdd(struct Node head)
Node separateEvenOdd(struct Node head)
{
// Starting node of the list having
// 链表的起始节点,包含
// even values
// 偶数值
Node *evenStart = NULL;
Node *evenStart = NULL;
// Starting node of the list having odd values
// 链表的起始节点,包含奇数值
Node *oddStart = NULL;
Node *oddStart = NULL;
// Ending node of the list having even values
// 链表中具有偶数值的末尾节点
Node *evenEnd = NULL;
Node *evenEnd = NULL;
// Ending node of the list having odd values
// 链表中具有奇数值的末尾节点
Node *oddEnd = NULL;
Node *oddEnd = NULL;
// Node for list traversal.
// 用于链表遍历的节点
Node *currentNode;
Node *currentNode;
for(currentNode = head; currentNode != NULL; currentNode = currentNode -> next)
for(currentNode = head; currentNode != NULL; currentNode = currentNode -> next)
{
int value = currentNode -> value;
int value = currentNode -> value;
// If the current value is even, add
// 如果当前值是偶数,则添加
// it to the list of even values.
// 到偶数值列表中。
if(value % 2 != 0)
if(value % 2 != 0)
{
if(oddStart != NULL)
if(oddStart != NULL)
{
oddEnd -> next = currentNode;
oddEnd -> next = currentNode;
oddEnd = oddEnd -> next;
oddEnd = oddEnd -> next;
}
else
else
{
oddStart = currentNode;
oddStart = currentNode;
oddEnd = oddStart;
oddEnd = oddStart;
}
}
// If current value is odd, add
// 如果当前值是奇数,则添加
// it to the list of odd values.
// 它到奇数值的列表中。
else
else
{
if(evenStart != NULL)
if(evenStart != NULL)
{
evenEnd -> next = currentNode;
evenEnd -> next = currentNode;
evenEnd = evenEnd -> next;
evenEnd = evenEnd -> next;
}
else
else
{
evenStart = currentNode;
evenStart = currentNode;
evenEnd = evenStart;
evenEnd = evenStart;
}
}
}
// If any of the two- odd list or even list is empty,
// 如果两个列表中的任何一个-奇数列表或偶数列表为空,
// no change is required
// 则无需进行更改
if(!oddStart || !evenStart)
if(!oddStart || !evenStart)
{
return;
return;
}
// Add the odd list after the even list.
// 在偶数列表之后添加奇数列表。
evenEnd -> next = oddStart;
evenEnd -> next = oddStart;
oddEnd -> next = NULL;
oddEnd -> next = NULL;
// Modify the head pointer to
// 修改头指针为
// the start of the even list.
// 偶数列表的起始位置。
head = evenStart;
head = evenStart;
return head;
return head;
}
Time Complexity: O(n) Space Complexity: O(1)
时间复杂度:O(n) 空间复杂度:O(1)
251. A given linked list is sorted based on absolute values. Write a function to sort the list based on actual values in O(n) time.
给定链表基于绝对值排序。编写一个函数在 O(n) 时间内按实际值对链表进行排序。
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b37b8558d557c902bb16c2 | 官方: 否 | 付费: 否
答案:
All the negative elements can be found in the reverse order. Therefore, as we traverse the list, whenever we find an element that is out of order, it is moved to the front of the linked list.
所有负数元素可以按相反顺序找到。因此,当我们遍历链表时,一旦发现一个元素顺序不对,就将其移动到链表头部。
Auxiliary Space: O(1)
辅助空间:O(1)
Implementation:
实现:
void sortList(Node** head)
void sortList(Node** head)
{
// Initialize the previous and the current nodes
// 初始化前一个节点和当前节点
Node previous = (head);
Node previous = (head);
Node* current;
Node* current;
// list traversal
// 链表遍历
for(current = (*head)->next; current != NULL; current = current->next)
for(current = (*head)->next; current != NULL; current = current->next)
{
// continue if the current element
// 如果当前元素
// is at its right place
// 在其正确位置,则继续
if (current->value >= previous->value)
if (current->value >= previous->value)
{
previous = current;
previous = current;
}
// If current is smaller than previous, then
// 如果当前元素小于前一个元素,则
// it must be moved to head
// 必须将其移动到头部
else
else
{
// Detach current from the linked list
// 将当前节点从链表中分离出来
previous->next = current->next;
previous->next = current->next;
// Move the current node to the beginning
// 将当前节点移动到开头
current->next = (*head);
current->next = (*head);
(*head) = current;
(*head) = current;
// Update current
// 更新 current
current = previous;
current = previous;
}
}
}
252. Given a linked list and a number n, you have to find the sum of the last n nodes of the linked list in a single traversal. Explain your approach in brief.
给定一个链表和一个数字 n,你需要在单次遍历中找到链表最后 n 个节点的和。简要解释你的方法。
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b8558d557c902bb16c5 | 官方: 否 | 付费: 否
答案:
The use of two-pointers will require a single traversal. We will have to maintain two pointers – reference pointer and main pointer. Both these pointers will be initialized to head. First, the reference pointer will be moved to n nodes from the head, and while traversing, we will keep adding the values and store them into a variable called sum1. Now both the pointers will move simultaneously until the reference pointer reaches the end of the list and while traversing, we will keep adding the values of the nodes. The reference pointer is storing this sum in the variable sum1, and the main pointer will be storing it in sum2. Now, (sum1 – sum2) is the answer, that is the required sum of the last n nodes.
使用双指针将只需要单次遍历。我们需要维护两个指针——参考指针和主指针。这两个指针都将初始化为头节点。首先,参考指针将从头节点移动到 n 个节点处,并在遍历过程中不断累加值,存入一个名为 sum1 的变量中。现在,两个指针将同时移动,直到参考指针到达链表末尾,并在遍历过程中不断累加节点的值。参考指针将此和存入变量 sum1,主指针则将其存入 sum2。现在,(sum1 - sum2) 就是答案,即最后 n 个节点的所需和。
int getSum(Node* head, int n)
int getSum(Node* head, int n)
{
if (n <= 0)
if (n <= 0)
return 0;
return 0;
int sum1 = 0, sum2 = 0;
int sum1 = 0, sum2 = 0;
struct Node* ptr1 = head;
struct Node* ptr1 = head;
struct Node* ptr2 = head;
struct Node* ptr2 = head;
// the sum of the first n nodes is to be calculated
// 需要计算前 n 个节点的和
for (ptr1 = head; ptr1 != NULL; ptr1 = ptr1->next;)
for (ptr1 = head; ptr1 != NULL; ptr1 = ptr1->next;)
{
sum += ptr1->value;
sum += ptr1->value;
n--;
n--;
if(n == 0)
if(n == 0)
break;
break;
}
// now there is a distance of n nodes between the two pointers
// 现在两个指针之间有 n 个节点的距离
// move to the end of the linked list
// 移动到链表的末尾
while (ptr1 != NULL)
while (ptr1 != NULL)
{
// sum of all the nodes
// 所有节点的总和
sum1 += ptr1->value;
sum1 += ptr1->value;
// sum of the first length - n nodes
// 前 length - n 个节点的总和
sum2 += ptr2->value;
sum2 += ptr2->value;
ptr1 = ptr2->next;
ptr1 = ptr2->next;
ptr2 = ptr2->next;
ptr2 = ptr2->next;
}
// returning the required sum
// 返回所需的差值
return (sum1 - sum2);
return (sum1 - sum2);
}
Time Complexity is O(n) and space complexity is O(1).
时间复杂度为 O(n),空间复杂度为 O(1)。
253. How will you find the middle element of a singly linked list without iterating the list more than once?
在不遍历链表超过一次的情况下,如何找到单链表的中间元素?
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b8558d557c902bb16c8 | 官方: 否 | 付费: 否
答案:
To solve this problem, we can use the two-pointer method. You have two pointers, one fast and one slow, in the two-pointer approach. The fast pointer travels two nodes per step, while the slow pointer only moves one. The slow pointer will point to the middle node of the linked list when the fast pointer points to the last node, i.e. when the next node is null.
为了解决这个问题,我们可以使用双指针方法。在双指针方法中,你有两个指针,一个快指针和一个慢指针。快指针每步移动两个节点,而慢指针每次只移动一个。当快指针指向最后一个节点(即下一个节点为 null)时,慢指针将指向链表的中间节点。
Node getMiddle(Node head)
Node getMiddle(Node head)
{
struct Node *slow = head;
struct Node *slow = head;
struct Node *fast = head;
struct Node *fast = head;
if (head)
if (head)
{
while (fast != NULL && fast->next != NULL)
while (fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
fast = fast->next->next;
slow = slow->next;
slow = slow->next;
}
}
return slow;
return slow;
}
Time Complexity: O(n) Space Complexity: O(1)
时间复杂度:O(n) 空间复杂度:O(1)
254. A linked list of coordinates is given, with neighboring points forming either a vertical or horizontal line. Remove points in between the starting and ending points of the horizontal or vertical line from the linked list.
给定一个坐标链表,相邻点形成垂直或水平线。从链表中删除水平或垂直线的起点和终点之间的点。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: behavioral | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b8558d557c902bb16cf | 官方: 否 | 付费: 否
答案:
The objective is to keep track of the current node, the next node, and the node after that. Continue deleting the next node when it is the same as the next-next node. We must keep a watch on the shifting of pointers and check for NULL values throughout the entire procedure.
目标是跟踪当前节点、下一个节点以及下一个的下一个节点。当下一个节点与下下一个节点相同时,继续删除下一个节点。在整个过程中,我们必须密切关注指针的移动,并检查NULL值。
Time Complexity is O(n). Space Complexity is O(1)
时间复杂度为O(n)。空间复杂度为O(1)。
Implementation:
实现:
void deleteNode(Node head, Node t)
void deleteNode(Node head, Node t)
{
head->next = t->next;
head->next = t->next;
t->next = NULL;
t->next = NULL;
free(t);
free(t);
}
// This function deletes the intermediate nodes in a sequence of
// 此函数删除序列中的中间节点
// horizontal and vertical line segments represented by a
// 由链表表示的水平和垂直线段
// linked list.
// 链表。
Node deleteMiddleNodes(Node head)
Node deleteMiddleNodes(Node head)
{
if (head == NULL || head->next == NULL || head->next->next == NULL)
if (head == NULL || head->next == NULL || head->next->next == NULL)
return head;
return head;
Node* t = head->next;
Node* t = head->next;
Node *tt = t->next;
Node *tt = t->next;
// Check whether this is a vertical line or horizontal line
// 检查这是垂直线还是水平线
if (t->y == head->y)
if (t->y == head->y)
{
// Find intermediate nodes with same y value, and delete them
// 查找具有相同 y 值的中间节点,并删除它们
while (tt != NULL && t->y == tt->y)
while (tt != NULL && t->y == tt->y)
{
deleteNode(head, t);
删除节点(head, t);
// Update t and tt for the next iteration
// 更新 t 和 tt 以进行下一次迭代
t = tt;
t = tt;
tt = tt->next;
tt = tt->next;
}
}
// check for vertical line
// 检查垂直线
else if (t->x == head->x)
else if (t->x == head->x)
{
// Find intermediate nodes with same x value, and delete them
// 查找具有相同 x 值的中间节点并删除它们
while (tt != NULL && t->x == tt->x)
当 (tt != NULL && t->x == tt->x) 时
{
deleteNode(head, t);
删除节点(head, t);
// Update t and tt for the next iteration
// 更新 t 和 tt 以进行下一次迭代
t = tt;
t = tt;
tt = tt->next;
tt = tt->next;
}
}
// Adjacent points must either have same x or same y
// 相邻点必须具有相同的 x 或相同的 y
else
else
{
cout<<"Given linked list is not valid";
cout<<"给定的链表无效";
return NULL;
return NULL;
}
// Recursion for the next segment
// 递归处理下一个段
deleteMiddleNodes(head->next);
删除中间节点(head->next);
return head;
return head;
}
- Data Science
- All Events
- My Events
255. Construct a doubly linked list out of a ternary tree.
从三元树构建一个双向链表。
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b8558d557c902bb16d2 | 官方: 否 | 付费: 否
答案:
A ternary tree is similar to a binary tree, except that instead of two nodes, it has three: left, middle, and right.
三元树与二叉树类似,区别在于它不是两个节点,而是三个:左、中、右。
The attributes of the doubly linked list should be as follows: - The ternary tree's left pointer should be used as the previous pointer in a doubly-linked list.
双向链表的属性应如下:- 三元树的左指针应作为双向链表中的前一个指针使用。
- The ternary tree's middle pointer should not point to anything.
- The ternary tree's right pointer should be the doubly linked list's next pointer.
- Each ternary tree node is entered into a doubly-linked list before its subtrees, with the left child of each node being inserted first, followed by the middle and right child (if any).
The approach is to make a preorder traversal of the tree. When we visit a node, we will use a tail pointer to insert it into a doubly-linked list at the end. That's how we keep the required insertion order. Then, in that order, we call for the left child, middle child, and right child.
方法是进行树的先序遍历。当我们访问一个节点时,我们将使用尾指针将其插入到双向链表的末尾。这就是我们保持所需插入顺序的方式。然后,按照该顺序,我们依次调用左子节点、中子节点和右子节点。
Implementation:
实现:
//Utility function that creates a doubly linked list
// 创建双向链表的工具函数
//by inserting the current node at the end of the doubly
// 通过在双向链表的末尾插入当前节点来实现
//linked list by employing a tail pointer
//通过使用尾指针的链表
void push(Node* tail_reference, Node n)
void push(Node* tail_reference, Node n)
{
// the tail pointer is to be initialized
// 尾指针需要被初始化
if (*tail_reference == NULL)
if (*tail_reference == NULL)
{
*tail_reference = n;
*tail_reference = n;
// set left, middle and right child to point
// 将左、中、右子节点设置为指向
// to NULL
// NULL
n->left = NULL;
n->left = NULL;
n->middle = NULL;
n->middle = NULL;
n->right = NULL;
n->right = NULL;
return;
return;
}
// using tail pointer, insert node in the end
// 使用尾指针,在末尾插入节点
(*tail_reference)->right = n;
(*tail_reference)->right = n;
// the middle and right child are set to point to NULL
// 中间和右子节点被设置为指向NULL
n->right = NULL;
n->right = NULL;
n->middle = NULL;
n->middle = NULL;
// set previous of the node
// 设置节点的前一个节点
n->left = (*tail_reference);
n->left = (*tail_reference);
// now tail pointer is pointing to the inserted node
// 现在尾指针指向已插入的节点
(*tail_reference) = n;
(*tail_reference) = n;
}
// From a ternary tree, create a doubly linked list,
// 从三叉树创建一个双向链表,
// by making a preorder traversal of the tree
// 通过对树进行前序遍历
Node ternaryTreeToList(Node head_reference, Node root)
Node ternaryTreeToList(Node head_reference, Node root)
{
// Base case
// 基础情况
if (!root)
if (!root)
return NULL;
return NULL;
//a static tail pointer to be created
// 创建一个静态尾指针
static Node* tail = NULL;
static Node* tail = NULL;
// left, middle and right nodes to be stored
// 存储左、中、右节点
// for future calls.
// 以备后续调用使用。
Node* left = root->left;
Node* left = root->left;
Node* middle = root->middle;
Node* middle = root->middle;
Node* right = root->right;
Node* right = root->right;
// set the head of the doubly linked list
// 设置双向链表的头节点
// as the root of the ternary tree
// 为三叉树的根节点
if (*head_reference == NULL)
if (*head_reference == NULL)
*head_reference = root;
*head_reference = root;
// push the current node in the end of the doubly linked list
// 将当前节点推入双向链表的末尾
push(&tail, root);
push(&tail, root);
//recursion for left, middle and right child
// 对左、中、右子节点进行递归
ternaryTreeToList(head_reference, left);
ternaryTreeToList(head_reference, left);
ternaryTreeToList(head_reference, middle);
ternaryTreeToList(head_reference, middle);
ternaryTreeToList(head_reference, right);
ternaryTreeToList(head_reference, right);
}
Time Complexity: O(n) Space Complexity: O(1)
时间复杂度:O(n) 空间复杂度:O(1)
256. The task is to determine pairs in a doubly-linked list whose sum equals the provided value ‘val’ without consuming any extra space for a given sorted doubly-linked list of positive distinct entries. The expected complexities are O(n) time and O(1) space.
任务是确定一个双向链表中和等于给定值‘val’的配对,对于给定的正相异条目排序双向链表,且不消耗任何额外空间。预期复杂度为O(n)时间和O(1)空间。
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b8558d557c902bb16d5 | 官方: 否 | 付费: 否
答案:
The approach is as follows: - Two pointer variables are to be initialized to find the possible elements in the sorted doubly linked list. Initialize num1 with the head of the doubly linked list,i.e., num1=head, and num2 with the last node of the doubly linked list, i.e., num2=lastNode.
方法如下:- 初始化两个指针变量以在排序双向链表中找到可能的元素。将num1初始化为双向链表的头节点,即num1=head,并将num2初始化为双向链表的最后一个节点,即num2=lastNode。
- If the current sum of num1 and num2 is less than Val, then we advance num1 in the forward direction. If the current total of the num1 and num2 is greater than x, then num2 is moved in the backward direction.
When the two pointers cross each other (num2->next = num1) or they become equal (num1 == num2), the loop ends. The condition "num1==num2" will handle the circumstance where no such pairs are present.
Implementation:实现:
vector<pair<int,int>> sumPair(struct Node *head, int val)
vector<pair<int,int>> sumPair(struct Node *head, int val)
{
// Two pointers are to be set, one to the beginning
// 设置两个指针,一个指向开始
// and the other to the last of the DLL.
// 另一个指向双向链表的末尾。
struct Node *num1 = head;
struct Node *num1 = head;
struct Node *num2 = head;
struct Node *num2 = head;
while (num2->next != NULL) //to get to the last node
while (num2->next != NULL) // 到达最后一个节点
num2 = num2->next;
num2 = num2->next;
vector<pair<int,int>> ans;
vector<pair<int,int>> ans;
// The loop ends when two pointers
// 当两个指针
// cross each other or they are equal
// 交叉或相等时,循环结束
while (num1 != num2 && num2->next != num1)
while (num1 != num2 && num2->next != num1)
{
if ((num1->value + num2->value) == val)
如果 ((num1->value + num2->value) == val)
{
ans.push_back(make_pair(num1->value,num2->value));
ans.push_back(make_pair(num1->value,num2->value));
// move num1 in the forward direction
// 向前移动num1
num1 = num1->next;
num1 = num1->next;
// move num2 in the backward direction
// 向后移动num2
num2 = num2->prev;
num2 = num2->prev;
}
else
else
{
if ((num1->value + num2->value) > val)
if ((num1->value + num2->value) > val)
num2 = num2->prev;
num2 = num2->prev;
else
else
num1 = num1->next;
num1 = num1->next;
}
}
return ans;
return ans;
}
Time Complexity: O(n) Space Complexity: O(1)
时间复杂度:O(n) 空间复杂度:O(1)
257. Given a 2-D matrix. You need to convert it into a linked list matrix such that each node is linked to its next right and down node and display it.
给定一个二维矩阵。你需要将其转换为链表矩阵,使得每个节点都链接到其右侧和下方的节点并显示它。
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b8558d557c902bb16d8 | 官方: 否 | 付费: 否
答案:
The idea is to create a new node for each element of the matrix and then create its next down and right nodes in a recursive manner.
思路是为矩阵的每个元素创建一个新节点,然后以递归方式创建其下方和右侧的节点。
Implementation:
实现:
Node* construct(int A[][3], int m, int n, int i, int j)
Node* construct(int A[][3], int m, int n, int i, int j)
{
// check if i or j is out of bounds
// 检查 i 或 j 是否超出边界
if (i > n - 1 || j > m - 1)
if (i > n - 1 || j > m - 1)
return NULL;
return NULL;
// a new node for current i and j is created
// 为当前 i 和 j 创建一个新节点
// and its down and right pointers are
// 并且其向下和向右的指针
//recursively allocated
// 被递归地分配
Node* t = new Node();
Node* t = new Node();
t->value = Ai;
t->value = Ai;
t->right = construct(A, m, n, i, j + 1);
t->right = construct(A, m, n, i, j + 1);
t->down = construct(A, m, n, i + 1, j);
t->down = construct(A, m, n, i + 1, j);
return t;
return t;
}
// function to display linked list data
// 用于显示链表数据的函数
void printData(Node* head)
void printData(Node* head)
{
// pointer to move down
// 指向向下移动的指针
Node* d;
Node* d;
// pointer to move down
// 指向向下移动的指针
Node* r;
Node* r;
// loop till node->down is not NULL
// 循环直到 node->down 不为 NULL
for( d = head; d!=NULL; d = d->down)
for( d = head; d!=NULL; d = d->down)
{
for( r = d; r!=NULL; r = r->right)
for( r = d; r!=NULL; r = r->right)
{
// loop till node->right is not NULL
// 循环直到 node->right 不为 NULL
cout << r->value << " ";
cout << r->value << " ";
}
cout << endl;
cout << endl;
}
}
Time Complexity: O(m * n) Space Complexity: O(1), ignoring the space required for the final answer.
时间复杂度:O(m * n) 空间复杂度:O(1),忽略最终答案所需的空间。
258. Extract all leaves from a Binary Tree into a Doubly Linked List (DLL).
将二叉树中的所有叶子节点提取到双向链表(DLL)中。
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b8558d557c902bb16db | 官方: 否 | 付费: 否
答案:
It's worth noting that the DLL must be created in place. Assume that the DLL and Binary Tree node structures are identical, with the exception that the meanings of the left and right pointers. Left denotes the previous pointer, whereas right denotes the next pointer in DLL.
值得注意的是,DLL 必须原地创建。假设 DLL 和二叉树节点的结构相同,只是 left 和 right 指针的含义不同。在 DLL 中,left 表示前驱指针,而 right 表示后继指针。
All of the leaves must be traversed and connected by adjusting the left and right pointers. By adjusting the left or right pointers in parent nodes, we can also delete them from the Binary Tree. There are numerous options for resolving this issue. We add leaves to the beginning of the current linked list and update the list's head using the pointer to head pointer in the following code. We must process leaves in reverse order because we insert from the beginning. We traverse the right subtree first, then the left subtree, in reverse order. To update the left and right pointers in parent nodes, we employ return values.
必须通过调整 left 和 right 指针来遍历并连接所有叶子节点。通过调整父节点中的 left 或 right 指针,我们也可以将它们从二叉树中删除。解决此问题的方法有多种。在下面的代码中,我们将叶子节点添加到当前链表的开头,并使用指向头指针的指针更新链表的头。由于我们从头插入,因此必须逆序处理叶子节点。我们首先遍历右子树,然后遍历左子树,以逆序处理。为了更新父节点中的 left 和 right 指针,我们使用返回值。
Implementation:
实现:
// The function extracts all the
// 此函数从给定的二叉树中
// leaves from a given Binary Tree.
// 提取所有叶子节点。
// The function returns new root of
// 此函数返回二叉树的
// the Binary Tree. The function also sets
// 新根。该函数还将
// *head_reference as the head of the DLL.
// *head_reference 设置为 DLL 的头。
// The left pointer of the tree is used as prev
// 树的 left 指针用作 DLL 中的 prev
// and the right pointer is used as next in the DLL.
// 而 right 指针用作 DLL 中的 next。
Node extractLeaf(Node head_reference, Node root)
Node extractLeaf(Node head_reference, Node root)
{
if (!root)
if (!root)
return NULL;
return NULL;
if (root->right == NULL && root->left == NULL)
if (root->right == NULL && root->left == NULL)
{
// This node will be added to the doubly linked
// 这个节点将被添加到叶节点的
// list of leaves. We will have to
// 双向链表中。我们需要
// set the right pointer of this node
// 将此节点的右指针
// as the previous head of DLL. We
// 设置为 DLL 的前一个头节点。我们
// don't need to set the left pointer
// 不需要设置左指针,
// as the left is already NULL.
// 因为左指针已经是 NULL。
root->right = *head_reference;
root->right = *head_reference;
// Change the left pointer of previous head
// 更改前一个头节点的左指针
if (*head_reference)
if (*head_reference)
(*head_reference)->left = root;
(*head_reference)->left = root;
// Change the head of the linked list
// 更改链表的头节点
*head_reference = root;
*head_reference = root;
return NULL;
return NULL;
}
// Recursion for right and left subtrees
// 递归处理右子树和左子树
root->right = extractLeaf(&head_reference, root->right);
root->right = extractLeaf(&head_reference, root->right);
root->left = extractLeaf(&head_reference, root->lef);
root->left = extractLeaf(&head_reference, root->lef);
return root;
return root;
}
Time Complexity: O(n) Space Complexity: O(1), ignoring the recursion stack space
时间复杂度:O(n) 空间复杂度:O(1),忽略递归栈空间
259. Write a program to delete all odd positioned nodes from a circular linked list. (Consider 1-based indexing).
编写一个程序,从循环链表中删除所有奇数位置的节点。(考虑基于1的索引)。
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b37b8558d557c902bb16de | 官方: 否 | 付费: 否
答案:
The approach is to begin traversing the circular linked list by keeping track of the current node's position using a count variable. Delete the current node if it is at an odd position.
该方法是从循环链表开始遍历,通过计数变量跟踪当前节点的位置。如果当前节点处于奇数位置,则删除该节点。
Implementation:
实现:
// l is the length of the linked list
// l 是链表的长度
void DeleteAllOddNodes(struct Node** head_reference, int l)
void DeleteAllOddNodes(struct Node** head_reference, int l)
{
int cnt = 0;
int cnt = 0;
struct Node prev = head_reference, next = head_reference;
struct Node prev = head_reference, next = head_reference;
// check if the list is empty
// 检查链表是否为空
if (*head_reference == NULL)
if (*head_reference == NULL)
{
cout<<"List is empty"<<endl;
cout<<"列表为空"<<endl;
return;
return;
}
// check if there is a single node in the list
// 检查列表中是否只有一个节点
if (l == 1)
if (l == 1)
{
// Function to delete first node
// 删除第一个节点的函数
*head_reference=NULL;
*head_reference=NULL;
return;
return;
}
while (l > 0)
while (l > 0)
{
// delete first position node as it is odd
// 删除第一个位置节点,因为它是奇数位置
if (cnt == 0)
if (cnt == 0)
{
struct Node t1 = head_reference, t2 = head_reference;
struct Node t1 = head_reference, t2 = head_reference;
if (t1->next == t1)
if (t1->next == t1)
{
*head_reference = NULL;
*head_reference = NULL;
}
while(t1->next!=*head_reference)
while(t1->next!=*head_reference)
{
t1 = t1->next;
t1 = t1->next;
t2 = t1->next;
t2 = t1->next;
}
t1->next = t2->next;
t1->next = t2->next;
*head_reference = t1->next;
*head_reference = t1->next;
free(t2);
free(t2);
}
// if the position is odd, delete that node
// 如果位置是奇数,删除该节点
if (cnt % 2 == 0 && cnt != 0)
if (cnt % 2 == 0 && cnt != 0)
{
struct Node* tmp = head_reference;
struct Node* tmp = head_reference;
if (head_reference == prev)
if (head_reference == prev)
{
head_reference = prev->next;
head_reference = prev->next;
}
while (tmp->next != prev)
while (tmp->next != prev)
{
tmp = tmp->next;
tmp = tmp->next;
}
tmp->next = prev->next;
tmp->next = prev->next;
free(prev);
free(prev);
}
prev = prev->next;
prev = prev->next;
next = prev->next;
next = prev->next;
cnt++;
cnt++;
l--;
l--;
}
turn;
turn;
re}
re}
Time Complexity: O(n^2) Space Complexity: O(1)
时间复杂度:O(n^2) 空间复杂度:O(1)
260. Why is merge sort a better option than quicksort for linked lists?
为什么对于链表来说,归并排序比快速排序是更好的选择?
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b8558d557c902bb16e1 | 官方: 否 | 付费: 否
答案:
- When it comes to linked lists, there are a few things to keep in mind. The issue is unique due to the memory allocation differences between arrays and linked lists. Unlike arrays, linked list nodes in memory may not be adjacent.
- We can insert items in the middle of a linked list in O(1) extra space and O(1) time if we are given a reference/pointer to the previous node, unlike an array. As a result, the merge sort operation can be accomplished without the need for additional linked list space.
- We can do random access in arrays since the elements are continuous in memory. In contrast to arrays, we can't access a linked list at random.
- Quick Sort necessitates a great deal of this type of access. Because we don't have a continuous block of memory, we have to travel from the head to the i'th node to get to the i'th index in a linked list. Merge sort accesses data in a sequential manner, with less requirement for random access.
261. What algorithm will you implement to find similar elements from two Linked Lists given and return the result in the form of a Linked List? Assume there are no duplicates.
你将实现什么算法来从给定的两个链表中找出相似元素,并以链表形式返回结果?假设没有重复项。
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: fullstack
- id: 69b37b8558d557c902bb16ea | 官方: 否 | 付费: 否
答案:
Create an empty hash table and set the result list to NULL. While traversing List1, insert the element in the hash table for each element visited in List1. While traversing List2, look for the entries in the hash table for each element visited in List2. If the element is already existing, add it to the result list. If the element isn't present, it is to be ignored.
创建一个空的哈希表,并将结果链表设置为NULL。遍历List1时,对于List1中访问的每个元素,将其插入哈希表。遍历List2时,对于List2中访问的每个元素,在哈希表中查找条目。如果元素已存在,则将其添加到结果链表。如果元素不存在,则忽略它。
The overall time and space complexity are linear.
整体时间和空间复杂度都是线性的。
Node getIntersection(Node head1, Node* head2)
Node getIntersection(Node head1, Node* head2)
{
unordered_map < int > m;
unordered_map < int > m;
Node* n1 = head1;
Node* n1 = head1;
Node* n2 = head2;
Node* n2 = head2;
Node* head = NULL;
Node* head = NULL;
// loop stores all the elements of list1 in hset
// 循环将链表1的所有元素存储在hset中
while (n1)
while (n1)
{
m[n1->value] = 1;
m[n1->value] = 1;
n1 = n1->next;
n1 = n1->next;
}
// For every element of list2 present in hset
// 对于hset中存在的链表2的每个元素
// loop inserts the element into the result
// 循环将该元素插入到结果中
while (n2 != null)
while (n2 != null)
{
if (m[n2->value] == 1)
if (m[n2->value] == 1)
{
Node* temp = new Node();
Node* temp = new Node();
temp->value = n2->value;
temp->value = n2->value;
temp->next = head;
temp->next = head;
head = temp;
head = temp;
}
n2 = n2->next;
n2 = n2->next;
}
return head;
return head;
}
Successful Tech Career for FREE!
免费开启成功的科技职业生涯!
Successful Tech Career!
成功的技术职业生涯!
Interview Process
面试流程
CTC & Designation
CTC与职位级别
Projects on the Job
工作项目
Referral System
推荐系统
Try It Out
试试看
2 Lakh+ Roadmaps Created
已生成20万+职业规划
262. How will you remove a cycle from a linked list?
你将如何从链表中移除一个循环?
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b8558d557c902bb170b | 官方: 否 | 付费: 否
答案:
One method of identifying the cycle is Floyd's cycle detect technique, popularly known as the tortoise and hare algorithm since it uses two pointers/references that move at opposite speeds. If there is a cycle, after a limited number of steps, the two pointers (say, slow and fast) will point to the same element.
识别循环的一种方法是弗洛伊德循环检测技术,通常称为龟兔算法,因为它使用两个速度相反的指针/引用。如果存在循环,在有限步数后,两个指针(例如,慢指针和快指针)将指向相同元素。
It's interesting to note that the element where they meet will be the same distance from the loop's start (continuing to traverse the list in the same, forward direction) as the loop's start is from the list's head. That is, if the linear component of the list contains k elements, the two pointers will meet inside a loop of length m at a location m-k from the loop's start or k elements from the loop's 'end' (of course, it's a loop, so there is no 'end' - it's just the ‘start' again). That gives us a technique to find the loop's beginning.
有趣的是,它们相遇的元素与循环起点的距离(沿相同方向继续向前遍历列表)等于循环起点与列表头部的距离。也就是说,如果列表的线性部分包含k个元素,两个指针将在长度为m的循环内、距离循环起点m-k处(或距离循环“终点”k个元素处)相遇(当然,这是一个循环,所以没有“终点”——它只是“起点”再次出现)。这为我们提供了一种找到循环起点的方法。
Once a cycle has been detected, keep fast pointing to the element where the loop for the previous step ended, but reset slow to point back to the beginning of the list. Now, one element at a time, move each pointer. Fast will keep looping because it started inside the loop. Slow and fast will meet again after k steps (equivalent to the distance between the start of the loop and the head of the list). This will serve as a pointer to the beginning of the loop.
一旦检测到循环,保持快指针指向上一步循环结束处的元素,但将慢指针重置为指向列表的开始。现在,每次移动每个指针一个元素。快指针将继续循环,因为它从循环内部开始。慢指针和快指针将在k步后再次相遇(相当于循环起点与列表头部之间的距离)。这将作为指向循环起点的指针。
It's now simple to set slow (or fast) to point to the loop's starting element and traverse the loop until slow returns to the starting element. Slow is referring to the 'last' element list at this point, and its next pointer can be adjusted to null.
现在简单地将慢指针(或快指针)设置为指向循环的起始元素,并遍历循环直到慢指针返回起始元素。此时慢指针指向列表的“最后一个”元素,其下一个指针可以设置为空。
Implementation:
实现:
Node getLastNode(Node head)
Node getLastNode(Node head)
{
Node* slow = head;
Node* slow = head;
Node* fast = head;
Node* fast = head;
// find the intersection point using Tortoise and Hare algorithm
// 使用龟兔算法找到交点
while (fast->next != NULL)
while (fast->next != NULL)
{
slow = slow->next;
slow = slow->next;
fast = fast->next->next;
fast = fast->next->next;
if (slow == fast)
if (slow == fast)
break;
break;
}
//check if there is no loop
//检查是否存在循环
if (fast->next == NULL)
if (fast->next == NULL)
{
return NULL;
return NULL;
}
slow = head;
slow = head;
// run this loop till both the references are one short of the start of the loop
// 运行此循环,直到两个引用都接近循环起点一个位置
while (slow->next != fast->next)
while (slow->next != fast->next)
{
slow = slow->next;
slow = slow->next;
fast = fast->next;
fast = fast->next;
}
// Now the fast pointer is pointing to the start of the loop
// 现在快指针指向循环的起点
return fast;
return fast;
}
Node* getLastNode = findStartOfLoop(head);
Node* getLastNode = findStartOfLoop(head);
getLastNode->next = null;
getLastNode->next = null;
Time Complexity: O(n) Space Complexity: O(1)
时间复杂度:O(n) 空间复杂度:O(1)
263. How will you convert a binary tree into a doubly-linked list?
如何将二叉树转换为双向链表?
- 知识点: 算法与数据结构 (主题: linked-list, data-structures;标签: interviewbit, linked-list, topic-specific, data-structures)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37b8558d557c902bb170f | 官方: 否 | 付费: 否
答案:
In a converted doubly linked list, the left and right pointers in nodes of a binary tree will be used as previous and next pointers, respectively. The nodes in the doubly linked list must be in the same order as the provided Binary Tree's Inorder. The head node of the doubly linked list must be the first node of Inorder traversal (leftmost node in the binary tree).
在转换后的双向链表中,二叉树节点的左指针和右指针将分别用作前驱指针和后继指针。双向链表中的节点必须与给定二叉树的中序遍历顺序相同。双向链表的头节点必须是中序遍历的第一个节点(二叉树中最左边的节点)。
void btToDLL(Node *root, Node head_reference, Node previous)
void btToDLL(Node *root, Node head_reference, Node previous)
{
if (!root)
if (!root)
return;
return;
// Recursive conversion of left subtree
// 递归转换左子树
btToDLL(root->left, head_reference, previous);
btToDLL(root->left, head_reference, previous);
if (*head_reference == NULL)
if (*head_reference == NULL)
*head_reference = root;
*head_reference = root;
else
else
{
root->left = *previous;
root->left = *previous;
*previous->right = root;
*previous->right = root;
}
*previous = root;
*previous = root;
// Recursive conversion of right subtree
// 递归转换右子树
btToDLL(root->right, head_reference, previous);
btToDLL(root->right, head_reference, previous);
}
- Time Complexity: O(n)
- Auxiliary Space: O(1)
264. Given a sorted array of distinct integers, return the index if the target value is found, or if not, the index where the value would be inserted in order. An algorithm with O(log n) runtime must be written to handle it.
给定一个有序的不同整数数组,如果找到目标值则返回其索引,如果未找到,则返回按顺序插入该值时应处的索引。必须编写一个运行时间复杂度为O(log n)的算法来处理。
- 知识点: 算法与数据结构 (标签: interviewbit, maq, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: MAQ Software
- id: 69b37bc758d557c902bb4542 | 官方: 否 | 付费: 否
答案:
Example 1: - Input: nums = [1,3,5,6], target = 5
示例 1:- 输入:nums = [1,3,5,6],目标值 = 5
Output: 2
Example 2: - Input: nums = [1,3,5,6], target = 2示例 2:- 输入:nums = [1,3,5,6],目标值 = 2
Output: 1
Example 3: - Input: nums = [1,3,5,6], target = 7示例 3:- 输入:nums = [1,3,5,6],目标值 = 7
Output: 4
Solution-解决方案-
We must be careful if the start is greater than the end, because if this statement is true, we know that the target is NOT FOUND, and we just return the insertion position. Now, let's take a look at what happens if the previous caller was the case mid=start=end. binarySearchInsert(nums, mid+1, end, target), in case 1, the insertion position should be mid+1 (insert target after mid) in case 2, the insertion position should be mid (insert target into mid and shift old mid value afterwards). It is also clear in the next call when start>end that the start should be at the insertion position. But wait, if the target is found, how do you know whether the idx >= 0, if the target is not found, how do you know whether the idx >= 0? To find out the original value when not found, we use a trick to return a negative value. What about the found value? It is 0, so we use another trick to increment the insertion idx before negation.
当 start 大于 end 时我们必须小心,因为如果这个条件为真,我们就知道 target 未被找到,只需返回插入位置。现在,让我们看看如果之前的调用是 mid=start=end 的情况会发生什么。binarySearchInsert(nums, mid+1, end, target),在情况 1 中,插入位置应为 mid+1(在 mid 之后插入 target),在情况 2 中,插入位置应为 mid(将 target 插入到 mid 位置,然后将旧的 mid 值后移)。在接下来的调用中,当 start>end 时,也很清楚 start 应位于插入位置。但是等等,如果 target 被找到,如何知道 idx >= 0?如果 target 未被找到,又如何知道 idx >= 0?为了在未找到时找出原始值,我们使用一个技巧返回负值。那找到时的值呢?它是 0,所以我们使用另一个技巧,在取反之前将插入 idx 加一。
public class Solution {
public class Solution {
public int binarySearchInsert(int[] nums, int start, int end, int target) {
公共 int binarySearchInsert(int[] nums, int start, int end, int target) {
if(start>end)
如果 (start>end)
return -(start+1);
返回 -(start+1);
int mid = start+(end-start)/2;
int mid = start+(end-start)/2;
if(nums[mid]==target)
如果 (nums[mid]==target)
return mid;
返回 mid;
else if(nums[mid]<target)
否则如果 (nums[mid]<target)
return binarySearchInsert(nums, mid+1, end, target);
返回 binarySearchInsert(nums, mid+1, end, target);
else
else
return binarySearchInsert(nums, start, mid-1, target);
返回 binarySearchInsert(nums, start, mid-1, target);
}
public int searchInsert(int[] nums, int target) {
公共 int searchInsert(int[] nums, int target) {
int idx = binarySearchInsert(nums, 0, nums.length-1, target);
int idx = binarySearchInsert(nums, 0, nums.length-1, target);
return idx>=0 ? idx : -idx-1;
返回 idx>=0 ? idx : -idx-1;
}
}
- Data Science
- All Events
- My Events
265. Return the median of the two sorted arrays given two arrays of size m and n, nums1 and nums2, respectively. It is recommended that the run-time complexity be O(log (m+n)).
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2,返回这两个有序数组的中位数。建议运行时复杂度为 O(log (m+n))。
- 知识点: 算法与数据结构 (标签: interviewbit, maq, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: MAQ Software
- id: 69b37bc758d557c902bb4545 | 官方: 否 | 付费: 否
答案:
Example 1:
示例1:
Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2.
输入:nums1 = [1,3], nums2 = [2] 输出:2.00000 解释:合并后的数组 = [1,2,3],中位数为 2。
Example 2:
示例2:
Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
输入:nums1 = [1,2], nums2 = [3,4] 输出:2.50000 解释:合并后的数组 = [1,2,3,4],中位数为 (2 + 3) / 2 = 2.5。
Solution: When two arrays are combined, the middle element will be the median since it splits the total number of items into two equal halves. However, O(m+n) more space will be needed. However, by taking note of the fact that when merging the arrays, we are only interested in the border elements of the arrays because the arrays are already sorted, this solution may be optimised to operate in const space. As a result, we must determine how many elements from the first array should be chosen to go before the median. The number of elements from the second array that should go before the median may be computed as total elements/2 - the number of selected elements from the first array. Additionally, while computing the median, we need to know the values of either just one middle element or two middle elements (if there are even numbers of components) (in case of odd number of elements). So, when conducting a binary search, we will keep track of these values.
解决方案:当两个数组合并时,中间元素就是中位数,因为它将总元素数分成两个相等的部分。然而,需要 O(m+n) 的额外空间。但是,注意到在合并数组时,由于数组已经排序,我们只关心数组的边界元素,因此可以优化此解决方案以在常量空间内运行。因此,我们需要确定应该从第一个数组中选择多少个元素放在中位数之前。应当从中位数之前选择的第二个数组的元素数量可以计算为总元素数/2 - 从第一个数组中选择的元素数量。此外,在计算中位数时,我们需要知道一个中间元素或两个中间元素的值(如果有偶数个元素)(如果是奇数个元素)。因此,在进行二分搜索时,我们将跟踪这些值。
Note: Since arrays are already sorted, left values will always be smaller than right values of its own array when merging, i.e. left value of one array with right value of another array.
注意:由于数组已经排序,在合并时,左值总是小于其自身数组的右值,即一个数组的左值与另一个数组的右值。
class Solution {
class Solution {
public:
public:
double findMedianSortedArrays(vector& nums1, vector & nums2) {
double findMedianSortedArrays(vector& nums1, vector & nums2) {
int m = nums1.size();
int m = nums1.size();
int n = nums2.size();
int n = nums2.size();
if(m > n)
if(m > n)
{
return findMedianSortedArrays(nums2, nums1);
return findMedianSortedArrays(nums2, nums1);
}
int l=0, r= m;
int l=0, r= m;
int total = m+n+1;
int total = m+n+1;
while(l<=r)
while(l<=r)
{
int fir = l + (r-l)/2;
int fir = l + (r-l)/2;
int sec = total/2 - fir;
int sec = total/2 - fir;
int l1=INT_MIN, l2=INT_MIN;
int l1=INT_MIN, l2=INT_MIN;
int r1=INT_MAX, r2=INT_MAX;
int r1=INT_MAX, r2=INT_MAX;
if(fir > 0)
if(fir > 0)
{
l1 = nums1[fir-1];
l1 = nums1[fir-1];
}
if(sec>0)
if(sec>0)
{
l2 = nums2[sec-1];
l2 = nums2[sec-1];
}
if((fir>=0) && (fir<m))
if((fir>=0) && (fir<m))
{
r1 = nums1[fir];
r1 = nums1[fir];
}
if((sec>=0) && (sec<n))
if((sec>=0) && (sec<n))
{
r2 = nums2[sec];
r2 = nums2[sec];
}
if(l1<=r2 && l2<=r1)
if(l1<=r2 && l2<=r1)
{
if((n+m)%2 == 0)
if((n+m)%2 == 0)
{
return (max(l1, l2)+min(r1, r2))/2.0;
return (max(l1, l2)+min(r1, r2))/2.0;
}
else
else
{
return max(l1, l2);
return max(l1, l2);
}
}
else if(l1> r2)
else if(l1> r2)
{
r = fir-1;
r = fir-1;
}
else
else
{
l = fir+1;
l = fir+1;
}
}
return 0;
return 0;
}
};
266. An array of k linked-list lists is provided to you; each linked-list is arranged in ascending order. Create one sorted linked list out of the combined linked lists, then return it.
给定一个由k个链表组成的数组,每个链表均按升序排列。将合并后的链表组合成一个有序链表,然后返回它。
- 知识点: 算法与数据结构 (标签: interviewbit, maq, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: MAQ Software
- id: 69b37bc758d557c902bb4548 | 官方: 否 | 付费: 否
答案:
Example 1: - Input: lists = [[1,4,5],[1,3,4],[2,6]]
示例1:- 输入:lists = [[1,4,5],[1,3,4],[2,6]]
- Output: [1,1,2,3,4,4,5,6]
Explanation:
The linked lists are:链表为:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list: 1->1->2->3->4->4->5->6
将它们合并成一个有序列表:1->1->2->3->4->4->5->6
Example 2: - Input: lists = []
示例2:- 输入:lists = []
Output: []
Example 3: - Input: lists = [[]]示例3:- 输入:lists = [[]]
Output: []
Solution:解决方案:
Taken as our initial starting point, k=2. 1->2->3, 2->7->11 The linked list's pointer is then advanced by selecting the least pointer value. The process for raising k will proceed in the same way. The least number will be arbitrarily selected, and the corresponding pointer will be advanced. The issue is that for k=2, we can simply use the or > sign to determine which number is smaller of the two. However, adopting such an approach will take years to compute if k is huge, let's say 1 million. To answer this question, we'll need to use a more intelligent data structure. Consider a data structure that can hold all values and provide the lowest value in the shortest amount of time. A little mound would be preferable.
以此为初始起点,k=2。1->2->3,2->7->11 然后通过选择最小的指针值来推进链表指针。提升k的过程将以相同方式进行。将任意选择最小数字,并相应推进对应指针。问题是,对于k=2,我们可以直接使用或>符号来确定两者中哪个数字更小。然而,如果k很大(比如100万),采用这种方法将需要多年时间计算。为了回答这个问题,我们需要使用更智能的数据结构。考虑一种能容纳所有值并在最短时间内提供最小值的结构。小堆会更合适。
- All first pointers from each linked list will be pushed into the heap. 2. We also need to advance that list's pointer. 3. Next, we begin linking all of the smallest nodes to obtain the answer. Though I've represented heaps in this way for convenience, keep in mind that heaps actually take the form of trees.
struct comp
struct comp
{
bool operator()(const ListNode a,ListNode b)
bool operator()(const ListNode a,ListNode b)
{
return a->val>b->val;
return a->val>b->val;
}
};
ListNode mergeKLists(vector<ListNode>& lists) {
ListNode mergeKLists(vector<ListNode>& lists) {
priority_queue<ListNode,vector<ListNode>,comp> pq;
priority_queue<ListNode,vector<ListNode>,comp> pq;
for(auto x:lists)
for(auto x:lists)
{
if(x)pq.push(x);
if(x)pq.push(x);
}
if(pq.empty())return NULL;
if(pq.empty())return NULL;
ListNode* result=pq.top();
ListNode* result=pq.top();
pq.pop();
pq.pop();
if(result->next)pq.push(result->next);
if(result->next)pq.push(result->next);
ListNode* t=result;
ListNode* t=result;
while(!pq.empty())
while(!pq.empty())
{
t->next3e=pq.top();
t->next3e=pq.top();
pq.pop();
pq.pop();
t=t->next;
t=t->next;
if(t->next)pq.push(t->next);
if(t->next)pq.push(t->next);
}
return result;
return result;
}
267. The smallest missing positive integer should be returned from an unsorted integer array called nums. You must build an algorithm that requires constant additional space and runs in O(n) time.
从不含排序的整数数组 nums 中,应返回最小缺失的正整数。你必须构建一个需要常量额外空间且运行时间为 O(n) 的算法。
- 知识点: 算法与数据结构 (标签: interviewbit, maq, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: MAQ Software
- id: 69b37bc758d557c902bb454e | 官方: 否 | 付费: 否
答案:
Example 1: - Input: nums = [1,2,0]
示例 1: - 输入:nums = [1,2,0]
Output: 3
Example 2: - Input: nums = [3,4,-1,1]示例 2: - 输入:nums = [3,4,-1,1]
Output: 2
Example 3: - Input: nums = [7,8,9,11,12]示例3:- 输入:nums = [7,8,9,11,12]
Output: 1
Solution:解决方案:
Cycle sort is an unstable in-place sorting algorithm that does comparison sorting and is theoretically the least amount of writes to the original array. Regarding the quantity of memory writes, it is ideal. It reduces the amount of memory writes required for sorting (each value is either written once to its right spot or zero times if it is already there). Its foundation is the notion that an array to be sorted may be broken up into cycles. Graphs can be used to represent cycles. If the element at index I must also be present at index j in the sorted array, then we have n nodes and an edge that runs from node I to node j.
循环排序是一种不稳定的原地排序算法,它进行比较排序,并且理论上对原始数组的写入次数最少。就内存写入数量而言,它是理想的。它减少了排序所需的内存写入次数(每个值要么被写入其正确位置一次,如果已经在那里则为零次)。其基础理念是待排序的数组可以被分解为多个循环。循环可以用图来表示。如果索引i处的元素在排序后的数组中必须出现在索引j处,那么我们就有n个节点和一条从节点i指向节点j的边。
Cycle in arr [] = 2, 4, 5, 1, 3. Cycle in arr [] = 4, 3, 2, 1
数组arr[]中的循环 = 2, 4, 5, 1, 3。数组arr[]中的循环 = 4, 3, 2, 1
We evaluate each cycle individually. We start by thinking about the cycle that contains the first ingredient. We locate the first element's right position and set it at, let's say, position j. We take into account the previous value of arr[j] and determine its proper location. We continue repeating this until all of the components of the current cycle are in their proper positions, meaning that we never return to the cycle's starting point.
我们分别评估每个循环。我们首先考虑包含第一个元素的循环。我们找到第一个元素的正确位置,并将其放置在,假设是位置j处。我们考虑arr[j]的先前值,并确定其正确位置。我们继续重复此操作,直到当前循环的所有元素都处于其正确位置,也就是说,我们永远不会回到循环的起点。
As a result, we may cycle sort just the positive items in this question and disregard the negative and zero elements. The element that is not at its predicted index will serve as our response as we proceed through the positive elements. Additionally, our response will be one greater than the greatest positive if all positive factors are at their predicted indices.
因此,在这个问题中,我们可以只对正数项进行循环排序,而忽略负数和零元素。当我们遍历正数元素时,不在其预期索引处的元素将成为我们的答案。此外,如果所有正数因子都处于其预期索引处,那么我们的答案将是最大正数加一。
class Solution {
class Solution {
public:
public:
int firstMissingPositive(vector& arr) {
int firstMissingPositive(vector& arr) {
//Cycle sort
//循环排序
int n = arr.size();
int n = arr.size();
int i = 0, correct_idx;
int i = 0, correct_idx;
while(i < n) {
while(i < n) {
if(arr[i] == i+1 or arr[i] > n or arr[i] <= 0)
if(arr[i] == i+1 or arr[i] > n or arr[i] <= 0)
i++;
i++;
else {
否则 {
correct_idx = arr[i] - 1;
correct_idx = arr[i] - 1;
if(arr[i] != arr[correct_idx])
if(arr[i] != arr[correct_idx])
swap(arr[i], arr[correct_idx]);
swap(arr[i], arr[correct_idx]);
else
else
i++;
i++;
}
}
//Find first missing positive
//查找第一个缺失的正数
int max = 1;
int max = 1;
for(int i = 0; i < n; i++) {
for(int i = 0; i < n; i++) {
if(arr[i] > 0)
if(arr[i] > 0)
max = arr[i];
max = arr[i];
if(arr[i] != i+1)
if(arr[i] != i+1)
return i+1;
return i+1;
}
return max+1;
return max+1;
}
};
268. Return the smallest window substring of s such that every character in t (including duplicates) is contained in the window, given two strings s and t of lengths m and n, respectively.
给定两个长度分别为m和n的字符串s和t,返回s中包含t中所有字符(包括重复字符)的最小子串窗口。
- 知识点: 算法与数据结构 (标签: interviewbit, maq, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: MAQ Software
- id: 69b37bc758d557c902bb4554 | 官方: 否 | 付费: 否
答案:
Return the void string "if there is no such substring." The test cases will be created so that each test case yields a distinct answer. A continuous group of characters within the string is referred to as a substring.
如果没有这样的子串,则返回空字符串""。测试用例将确保每个测试用例都有唯一答案。字符串中连续的一组字符称为子串。
Example 1: - Input: s = "ADOBECODEBANC", t = "ABC"
示例1: - 输入:s = "ADOBECODEBANC",t = "ABC"
- Output: "BANC"
Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2: - Input: s = "a", t = "a"示例2:- 输入:s = "a",t = "a"
- Output: "a"
Explanation: The entire string s is the minimum window.
Example 3: - Input: s = "a", t = "aa"示例3:- 输入:s = "a",t = "aa"
- Output: ""
Explanation: Both 'a's from t must be included in the window.Since the largest window of s only has one 'a', return empty string.
Solution :解决方案:
Use variable count to find the first valid substring from index p to index I then for each I we increase p until it still qualifies as a valid substring, at which time we update the result string.
使用变量count找到从索引p到索引i的第一个有效子串,然后对于每个i,我们增大p直到它仍然符合有效子串的条件,此时更新结果字符串。
class Solution {
class Solution {
public:
public:
string minWindow(string s, string t) {
string minWindow(string s, string t) {
unordered_map < char , int > a;
unordered_map < char , int > a;
unordered_map < char , int > b;
unordered_map < char , int > b;
for(auto ch: t)
for(auto ch: t)
{
a[ch]++;
a[ch]++;
}
int p = 0;
int p = 0;
int mn = INT_MAX;
int mn = INT_MAX;
string mxstr = "";
string mxstr = "";
int count=0;
int count=0;
for(int i =0;i<s.size();i++)
for(int i =0;i<s.size();i++)
{
watch(i);
watch(i);
watch(p);
watch(p);
b[s[i]]++;
b[s[i]]++;
int flag=0;
int flag=0;
if(b[s[i]]<=a[s[i]])
if(b[s[i]]<=a[s[i]])
{
count++;
count++;
}
if(count >= t.size())
if(count >= t.size())
{
while(pa[s[p]])
while(pa[s[p]])
{
b[s[p]]--;
b[s[p]]--;
p++;
p++;
}
// mn = min(mx, i-p+1);
// mn = min(mx, i-p+1);
if(mn > i-p+1)
if(mn > i-p+1)
{
mn = i-p+1;
mn = i-p+1;
mxstr = s.substr(p,i-p+1);
mxstr = s.substr(p,i-p+1);
}
}
}
return mxstr;
return mxstr;
}
};
269. If the head of a linked list contains a cycle, then determine whether the list has one. It is possible to create a cycle in a linked list by including nodes that are reachable again by following the next pointer.
如果链表的头部包含一个环,则确定该链表是否有环。可以通过包含那些通过跟随下一个指针可以再次到达的节点来在链表中创建一个环。
- 知识点: 算法与数据结构 (标签: interviewbit, maq, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: MAQ Software
- id: 69b37bc758d557c902bb455d | 官方: 否 | 付费: 否
答案:
The index of the node to which the tail of the next pointer is connected is used to determine whether there is a cycle. If there is not a cycle, then return true. Otherwise, return false.
下一个指针尾部所连接节点的索引用于判断是否存在环。如果不存在环,则返回 true。否则返回 false。
Example 1:
示例1:
- Input: head = [3,2,0,-4], pos = 1
- Output: true
- Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
示例2:
- Input: head = [1,2], pos = 0
- Output: true
- Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:
示例3:
- Input: head = [1], pos = -1
- Output: false
- Explanation: There is no cycle in the linked list.
Solution:
解决方案:
Using only two pointers, Floyd's cycle-moving algorithm traverses a sequence at different speeds. It determines whether a linked list has a cycle or not. First, we keep two pointers to the leading node, one that moves slowly and one that moves quickly. We scan the linked list in two steps and one step each, starting with the slow pointer and ending with the fast pointer. This procedure produces two-pointers and one pointer, which we call the tortoise and the hare. If the fast pointer reaches the tail of the list (or null), there is no cycle (i.e. if the fast pointer meets the slow pointer, there is a cycle). If the fast pointer meets the slow pointer, then there is a cycle (i.e. if the fast pointer and slow pointer meet).
仅使用两个指针,弗洛伊德循环移动算法以不同速度遍历序列。它判断链表是否有环。首先,我们保留两个指向首节点的指针,一个移动慢,一个移动快。我们以两步和一步的步长扫描链表,慢指针在前,快指针在后。此过程产生两个指针和一个指针,我们称之为龟兔指针。如果快指针到达链表尾部(或 null),则无环(即如果快指针遇到慢指针,则有环)。如果快指针遇到慢指针,则有环(即快指针和慢指针相遇)。
We can see that Car M is a slow pointer and Car B is a fast pointer in the below example.
在下面的示例中,我们可以看到 Car M 是慢指针,Car B 是快指针。
public boolean hasCycle(ListNode head) {
public boolean hasCycle(ListNode head) {
ListNode slowPointer = head;
ListNode slowPointer = head;
ListNode fastPointer = head;
ListNode fastPointer = head;
do {
do {
if (slowPointer == null || fastPointer == null || fastPointer.next == null) {
if (slowPointer == null || fastPointer == null || fastPointer.next == null) {
return false;
返回 false;
}
slowPointer = slowPointer.next;
slowPointer = slowPointer.next;
fastPointer = fastPointer.next.next;
fastPointer = fastPointer.next.next;
} while (slowPointer != fastPointer);
} while (slowPointer != fastPointer);
return true;
返回 true;
}
270. Imagine a normal queue (push, peek, pop, and empty) but only need two stacks to implement it. The MyQueue class must support all queue functions (push, peek, pop, and empty). The push() method pushes element x to the front of the queue.
想象一个普通的队列(支持 push、peek、pop 和 empty),但只需用两个栈来实现它。MyQueue 类必须支持所有队列函数(push、peek、pop 和 empty)。push() 方法将元素 x 推入队列的前端。
- 知识点: 算法与数据结构 (标签: interviewbit, maq, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: MAQ Software
- id: 69b37bc758d557c902bb4579 | 官方: 否 | 付费: 否
答案:
The pop() method returns the front element. The peek() method checks to see if the queue is empty. If it is, the empty() method returns true. If not, the method returns false. The queue is empty if it is not.
pop() 方法返回前端元素。peek() 方法检查队列是否为空。如果为空,则 empty() 方法返回 true。如果不为空,则该方法返回 false。如果队列不为空,则返回 false。
Input:
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output :
输出:
[null, null, null, 1, 1, false]
[null, null, null, 1, 1, false]
Explanation:
说明:
MyQueue myQueue = new MyQueue();
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(1); // 队列为:[1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.push(2); // 队列为:[1, 2](最左边是队列的前端)
myQueue.peek(); // return 1
myQueue.peek(); // 返回 1
myQueue.pop(); // return 1, queue is [2]
myQueue.pop(); // 返回 1,队列为 [2]
myQueue.empty(); // return false
myQueue.empty(); // 返回 false
Solution:
解决方案:
We will implement the push function inside the push function, in which we will first pop the top element off of the main stack and store it in the "temp" variable before calling push2 recursively. Then we will call push2 repeatedly until the main stack becomes empty, at which point we will push the element "x" into it. We will also add the "temp" variable to the main stack while backtracking in the push2 function.
我们将在 push 函数内部实现 push 函数,在递归调用 push2 之前,先弹出主栈的顶部元素并将其存储在“temp”变量中。然后,我们将重复调用 push2,直到主栈变为空,此时将元素“x”推入其中。我们还会在 push2 函数的回溯过程中将“temp”变量添加到主栈中。
class MyQueue {
class MyQueue {
public static StackmainStack;
public static StackmainStack;
public MyQueue() {
public MyQueue() {
mainStack=new Stack<>();
mainStack=new Stack<>();
}
public void push2(int x,Stack
public void push2(int x,StackmainStack)
{
if(mainStack.size()==0)
if(mainStack.size()==0)
{
mainStack.push(x);
mainStack.push(x);
return;
return;
}
int temp=mainStack.pop();
int temp=mainStack.pop();
push2(x,mainStack);
push2(x,mainStack);
mainStack.push(temp);
mainStack.push(temp);
}
public void push(int x) {
public void push(int x) {
push2(x,mainStack);
push2(x,mainStack);
}
public int pop() {
public int pop() {
return mainStack.pop();
return mainStack.pop();
}
public int peek() {
public int peek() {
return mainStack.peek();
返回 mainStack.peek();
}
public boolean empty() {
public boolean empty() {
if(mainStack.size()>0)
如果(mainStack.size()>0)
return false;
返回 false;
else
else
return true;
返回 true;
}
}
271. Given the head of a linked list, return the list sorted in ascending order.
给定一个链表的头节点,返回按升序排序后的链表。
- 知识点: 算法与数据结构 (标签: interviewbit, maq, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: MAQ Software
- id: 69b37bc758d557c902bb457c | 官方: 否 | 付费: 否
答案:
Example 1:
示例1:
- Input: head = [4,2,1,3]
- Output: [1,2,3,4]
Example 2:
示例2:
- Input: head = [-1,5,3,4,0]
- Output: [-1,0,3,4,5]
Example 3:
示例3:
- Input: head = []
- Output: []
Solution-
解决方案-
Divide the list into two sublists by using two pointers: fast and slow. Assure that list 1 is equal to or longer than list 2. The condition of a while loop is whether fast is next and whether fast is next. After this while loop, slow will be at the end of list 1.sort list 1 and 2. Merge list 1 and 2.
使用两个指针将列表分成两个子列表:fast 和 slow。确保列表1的长度大于或等于列表2的长度。while循环的条件是fast是否有下一个节点以及fast的next是否有下一个节点。这个while循环结束后,slow将位于列表1的末尾。排序列表1和列表2。合并列表1和列表2。
public class Solution {
public class Solution {
public ListNode sortList(ListNode head){
public ListNode sortList(ListNode head){
if(head==null || head.next==null)
如果(head==null || head.next==null)
return head;
return head;
ListNode h1=head;
ListNode h1=head;
ListNode fast=head;
ListNode fast=head;
ListNode slow=head;
ListNode slow=head;
while(fast.next!=null && fast.next.next!=null){
while(fast.next!=null && fast.next.next!=null){
fast=fast.next.next;
fast=fast.next.next;
slow=slow.next;
slow=slow.next;
}
ListNode h2=slow.next;
ListNode h2=slow.next;
slow.next=null;
slow.next=null;
h1=sortList(h1);
h1=sortList(h1);
h2=sortList(h2);
h2=sortList(h2);
return merge(h1,h2);
return merge(h1,h2);
}
public ListNode merge(ListNode h1, ListNode h2){
public ListNode merge(ListNode h1, ListNode h2){
ListNode fakeHead = new ListNode(9);
ListNode fakeHead = new ListNode(9);
ListNode cur = fakeHead;
ListNode cur = fakeHead;
while(h1!=null && h2!=null){
while(h1!=null && h2!=null){
if(h1.val<h2.val){
if(h1.val<h2.val){
cur.next=h1;
cur.next=h1;
cur=h1;
cur=h1;
h1=h1.next;
h1=h1.next;
}else{
}否则{
cur.next=h2;
cur.next=h2;
cur=h2;
cur=h2;
h2=h2.next;
h2=h2.next;
}
}
cur.next=h1==null?h2:h1;
cur.next=h1==null?h2:h1;
return fakeHead.next;
return fakeHead.next;
}
}
272. Write a program to sort a given array of numbers. The sorting algorithm should give best performance in every case (best, worst and average). Example : Input : arr = {3, 5, 7, 1, 2, 4, 6} Output : {1, 2, 3, 4, 5, 6, 7}
编写一个程序,对给定的数字数组进行排序。排序算法应该在每种情况下(最好、最坏和平均)都提供最佳性能。示例:输入:arr = {3, 5, 7, 1, 2, 4, 6} 输出:{1, 2, 3, 4, 5, 6, 7}
- 知识点: 算法与数据结构 (标签: interviewbit, mindtree, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Mindtree
- id: 69b37bd358d557c902bb4bec | 官方: 否 | 付费: 否
答案:
Example: Input : arr = {3, 5, 7, 1, 2, 4, 6} Output : {1, 2, 3, 4, 5, 6, 7}
示例:输入:arr = {3, 5, 7, 1, 2, 4, 6} 输出:{1, 2, 3, 4, 5, 6, 7}
Approach:
方法:
Since we want the sorting algorithm to give the best time complexity in all three cases (that is, best, worst and average), we will implement merge sort to sort the given array of numbers. In merge sort, we divide an array into two halves recursively, sort each half and then merge them.
由于我们希望排序算法在三种情况下(即最好、最坏和平均)都提供最佳时间复杂度,我们将实现归并排序来对给定的数字数组进行排序。在归并排序中,我们递归地将数组分成两半,对每一半进行排序,然后将它们合并。
Code:
代码:
include<bits/stdc++.h>
using namespace std;
using namespace std;
//function to merge the two sorted halves of the array
//函数用于合并数组的两个已排序半部分
void merge(int *arr, int start, int mid, int end) {
void merge(int *arr, int start, int mid, int end) {
int temp[end - start + 1];// creating a temporary array to store the sorted array
int temp[end - start + 1];// 创建一个临时数组来存储排序后的数组
int i = start;
int i = start;
int j = mid+1;
int j = mid+1;
int k = 0;
int k = 0;
while(i <= mid && j <= end) {
while(i <= mid && j <= end) {
if(arr[i] <= arr[j]) {
if(arr[i] <= arr[j]) {
temp[k] = arr[i];
temp[k] = arr[i];
i = i + 1;
i = i + 1;
}
else {
否则 {
temp[k] = arr[j];
temp[k] = arr[j];
j = j + 1;
j = j + 1;
}
k = k + 1;
k = k + 1;
}
//If the first half still has elements, we add them to the temporary array
//如果前半部分仍有元素,我们将它们添加到临时数组中
while(i <= mid) {
while(i <= mid) {
temp[k ++] = arr[i ++];
temp[k ++] = arr[i ++];
}
//If the second half still has elements, we add them to the temporary array
//如果后半部分仍有元素,我们将它们添加到临时数组中
while(j <= end) {
while(j <= end) {
temp[k ++] = arr[j ++];
temp[k ++] = arr[j ++];
}
// We store the sorted order of elements in the original array
//我们将元素的有序顺序存储回原数组中
for(i = start; i <= end; i ++) {
for(i = start; i <= end; i ++) {
arr[i] = temp[i - start]
arr[i] = temp[i - start]
}
}
// function to sort an array of elements
//对元素数组进行排序的函数
void mergeSort(int *arr, int start, int end) {
void mergeSort(int *arr, int start, int end) {
if(start < end) {
if(start < end) {
int mid = (start + end) / 2;// finding the mid index
int mid = (start + end) / 2;// 计算中间索引
mergeSort(arr, start, mid);// sorting the left side of the array
mergeSort(arr, start, mid);// 对数组左侧进行排序
mergeSort(arr, mid+1, end);// sorting the right side of the array
mergeSort(arr, mid+1, end);// 对数组右侧进行排序
merge(arr, start, mid, end);// merging the left and right halves of the array
merge(arr, start, mid, end);// 合并数组的左右两半
}
}
int main()
int main()
{
int arr[] = {3, 5, 7, 1, 2, 4, 6};
int arr[] = {3, 5, 7, 1, 2, 4, 6};
int n = sizeof(arr)/ sizeof(arr[0]);
int n = sizeof(arr)/ sizeof(arr[0]);
mergeSort(arr, 0, n);
mergeSort(arr, 0, n);
cout << "The sorted array is : ";
cout << “排序后的数组是: ”;
for(int i = 0; i < n; i ++)
for(int i = 0; i < n; i ++)
cout << arr[i];
cout << arr[i];
cout << "\n";
cout << “\n”;
return 0;
return 0;
}
Output:
输出:
The sorted array is : 1 2 3 4 5 6 7
排序后的数组是: 1 2 3 4 5 6 7
Explanation:
说明:
In the above code, the function merge() merges the two sorted halves of the array. The function mergeSort() recursively breaks the problem into subproblems, sorts each half and then merges the sorted halves by calling the merge() function.
在上述代码中,merge() 函数用于合并数组的两个已排序部分。mergeSort() 函数递归地将问题分解为子问题,对每个半部分进行排序,然后通过调用 merge() 函数合并已排序的半部分。
273. Given two unsorted arrays. Check if the second array is a subarray of the first array.
给定两个未排序的数组。检查第二个数组是否为第一个数组的子数组。
- 知识点: 算法与数据结构 (标签: interviewbit, mindtree, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Mindtree
- id: 69b37bd358d557c902bb4c18 | 官方: 否 | 付费: 否
答案:
Example: Input : arr1 = {2, 3, 0, 5, 1, 1, 2} arr2 = {3, 0, 5, 1} Output : True
示例:输入:arr1 = {2, 3, 0, 5, 1, 1, 2} arr2 = {3, 0, 5, 1} 输出:True
Input : arr1 = {3, 4, 5, 1, 2, 7} arr2 = {4, 1, 2} Output : False
输入:arr1 = {3, 4, 5, 1, 2, 7} arr2 = {4, 1, 2} 输出:False
Approach:
方法:
We use two pointers to explore both the array and the subarray. We maintain the pointer of array arr2[] and increase the pointer of both arrays if any element of arr1[] matches the first element of arr2[], otherwise set the pointer of arr1 to the next element of the previous starting point and reset the pointer of arr2 to 0. If all of arr2's elements match, print True; otherwise, print False.
我们使用两个指针来遍历数组和子数组。我们维护数组 arr2[] 的指针,如果 arr1[] 的任何元素与 arr2[] 的第一个元素匹配,则同时增加两个数组的指针;否则,将 arr1 的指针设置为上一个起始点的下一个元素,并将 arr2 的指针重置为 0。如果 arr2 的所有元素都匹配,则打印 True;否则,打印 False。
The following is how the above strategy is put into action:
以下是上述策略的实现方式:
Code:
代码:
include <bits/stdc++.h>
using namespace std;
using namespace std;
//function to check if the second array is a subarray of the first array
//用于检查第二个数组是否为第一个数组的子数组的函数
bool checkSubArray(int arr1[], int arr2[], int n, int m)
bool checkSubArray(int arr1[], int arr2[], int n, int m)
{
int i = 0, j = 0;
int i = 0, j = 0;
while (i < n && j < m) {
while (i < n && j < m) {
// If element matches
// 如果元素匹配
// increment both pointers
// 则同时递增两个指针
if (arr1[i] == arr2[j]) {
if (arr1[i] == arr2[j]) {
i++;
i++;
j++;
j++;
// checking if we have reached the end of the second array
// 检查是否已到达第二个数组的末尾
if (j == m)
if (j == m)
return true;
返回 true;
}
else {
否则 {
i = i - j + 1;// setting the pointer of the first array to the next element of the previous starting point
i = i - j + 1;//将第一个数组的指针设置到之前起始点的下一个元素
j = 0; // resetting the pointer of the second array to 0.
j = 0; // 将第二个数组的指针重置为 0。
}
}
return false;
返回 false;
}
int main()
int main()
{
int arr1[] = { 2, 3, 0, 5, 1, 1, 2 };
int arr1[] = { 2, 3, 0, 5, 1, 1, 2 };
int arr2[] = { 3, 0, 5, 1 };
int arr2[] = { 3, 0, 5, 1 };
int n = sizeof(arr1) / sizeof(arr1[0]);
int n = sizeof(arr1) / sizeof(arr1[0]);
int m = sizeof(arr2) / sizeof(arr2[0]);
int m = sizeof(arr2) / sizeof(arr2[0]);
bool res = checkSubArray(arr1, arr2, n, m);
bool res = checkSubArray(arr1, arr2, n, m);
if (res)
if (res)
cout << "True\n";
cout << "True\n";
else
else
cout << "False\n";
cout << "False\n";
return 0;
return 0;
}
Explanation:
说明:
In the above code, the function checkSubArray checks whether the second array is a sub array of the first array or not and returns the output correspondingly. We maintain two pointers, one for the first array and the other for the second array. If the elements match, we increment both the pointers; otherwise, we reset the pointers.
在上述代码中,函数 checkSubArray 检查第二个数组是否为第一个数组的子数组,并相应地返回输出。我们维护两个指针,一个指向第一个数组,另一个指向第二个数组。如果元素匹配,则同时递增两个指针;否则,重置指针。
274. Explain stable vs unstable sorting algorithms.
解释稳定与非稳定排序算法的区别。
- 知识点: 算法与数据结构 (标签: interviewbit, mphasis, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Mphasis
- id: 69b37bd658d557c902bb4da9 | 官方: 否 | 付费: 否
答案:
A sorting algorithm's stability is determined by how it handles equal (or repeating) elements. In contrast to stable sorting algorithms, unstable sorting algorithms do not maintain the relative positions of equal elements. In other terms, stable sorting preserves the relative positions of two equal elements.
排序算法的稳定性取决于其如何处理相等(或重复)元素。与稳定排序算法相比,不稳定排序算法不保持相等元素的相对位置。换句话说,稳定排序保持两个相等元素的相对位置不变。
The sort key is used by all sorting algorithms to establish the ordering of the entries in the collection. Equal elements, such as numbers or texts, are indistinguishable if the sort key is the (entire) element itself. Equal elements, on the other hand, can be distinguished if the sort key contains one or several, but not all, of the element's attributes, such as age in the Employee class.
排序键被所有排序算法用于确定集合中条目的排列顺序。如果排序键是(整个)元素本身,则相等元素(如数字或文本)无法区分。另一方面,如果排序键包含元素的一个或多个属性(但不是全部),例如 Employee 类中的年龄,则相等元素可以区分。
Stable sorting isn't always required. If equal items are indistinguishable or all of the elements in the group are distinct, stability is not really a problem. Stability is essential when equal elements may be distinguished. Merge Sort, Timsort, Counting Sort, Insertion Sort, and Bubble Sort are examples of frequent sorting algorithms that are naturally stable. Others, like Quicksort, Heapsort, and Selection Sort, are unstable. We can make unstable sorting algorithms stable by modifying them. In Quicksort, for example, we can employ extra space to preserve stability.
稳定排序并非总是必需的。如果相等条目不可区分或组中所有元素都是唯一的,则稳定性并不是真正的问题。当相等元素可以被区分时,稳定性至关重要。归并排序、Timsort、计数排序、插入排序和冒泡排序是常见自然稳定的排序算法示例。其他算法,如快速排序、堆排序和选择排序,则不稳定。我们可以通过修改使不稳定的排序算法变得稳定。例如,在快速排序中,我们可以使用额外空间来保持稳定性。
275. Is Dijkstra's algorithm Greedy Programming or Dynamic Programming? What are the benefits of utilising Bellman-Ford instead of Dijkstra?
Dijkstra 算法是贪心编程还是动态规划?使用 Bellman-Ford 代替 Dijkstra 有什么好处?
- 知识点: 算法与数据结构 (标签: interviewbit, mphasis, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Mphasis
- id: 69b37bd658d557c902bb4dac | 官方: 否 | 付费: 否
答案:
Let's see if you can say both. Since we always mark the nearest vertex, it's greedy. Because distances are adjusted using previously determined values, it is dynamic. However, I'd say it's more akin to dynamic programming than a greedy algorithm. It does not pick which route to walk step by step to get the shortest distance between A and B. Instead, it determines all possible routes from point A to point B. The best selections are made not by being greedy, but by exhausting all available routes that can shorten a distance. As a result, it's a dynamic programming algorithm, with the only difference being that the stages are dynamically chosen throughout the procedure rather than being known in advance.
让我们看看你两者是否都能说出来。因为我们总是标记最近的顶点,所以它是贪心的。因为距离是使用先前确定的值进行调整的,所以它是动态的。然而,我会说它更类似于动态规划而不是贪心算法。它不会逐步选择路径来获得 A 到 B 之间的最短距离。相反,它确定从点 A 到点 B 的所有可能路线。最佳选择不是通过贪心做出的,而是通过穷尽所有可以缩短距离的可用路线。因此,它是一个动态规划算法,唯一的区别在于阶段是在过程中动态选择的,而不是预先已知的。
By constantly relaxing distances till there are no more distances to relax, the Bellman-Ford method finds single-source shortest pathways. Relaxing distances are accomplished by determining whether an intermediate point offers a better path than the one currently selected. This algorithm outperforms Dijkstra in that it can manage graphs with negative edges, whereas Dijkstra can only handle non-negative ones. Its main constraint is graphing with loops that provide an overall negative route; however, this simply means that no finite solution exists.
通过不断松弛距离直到没有更多距离需要松弛,Bellman-Ford 算法找到单源最短路径。松弛距离是通过确定中间点是否提供比当前所选路径更好的路径来实现的。该算法优于 Dijkstra 之处在于它可以处理具有负边的图,而 Dijkstra 只能处理非负边。其主要限制是存在提供整体负路径的环的图;然而,这仅仅意味着不存在有限解。
276. Explain Binary Search Trees?
解释二叉搜索树?
- 知识点: 算法与数据结构 (标签: interviewbit, nagarro, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Nagarro
- id: 69b37bf958d557c902bb6170 | 官方: 否 | 付费: 否
答案:
A binary search tree (also known as Binary Search Tree or BST) is a data structure that organizes data into two different types of nodes, which are leaves and internal nodes. Each node has a key value that uniquely identifies it. The purpose of a binary search tree is to organize data so that it can be accessed efficiently by keywords. In order to access the data, you must always start at the root node and then follow the path down the tree until you reach an internal node that contains the value you’re looking for. Each internal node will have one or more child nodes, which will also have keys that identify them. As you continue to traverse the tree, you will keep on finding higher-level nodes (which are more deeply nested) until you eventually reach a leaf node that contains your desired data.
二叉搜索树(也称为 Binary Search Tree 或 BST)是一种将数据组织为两种不同类型节点(叶节点和内部节点)的数据结构。每个节点都有一个唯一标识它的键值。二叉搜索树的目的是组织数据,以便可以通过关键字高效访问。要访问数据,必须始终从根节点开始,然后沿着树向下路径前进,直到到达包含所需值的内部节点。每个内部节点将有一个或多个子节点,这些子节点也有标识它们的键。随着你继续遍历树,你将继续找到更高级别的节点(嵌套更深),直到最终到达包含所需数据的叶节点。
Binary Search tree inherits the property of Binary Tress. But in addition to this, it also has its own property that - - For every root node, values less than the root node will exist on the right subtree.
二叉搜索树继承了二叉树的性质。但除此之外,它还有自己的性质——对于每个根节点,小于根节点的值将存在于右子树中。
For every root node, values greater than the root node will exist in the left subtree.
And this follows for every individual node in the tree. Consider the below image for a better understanding.并且这个性质适用于树中的每个节点。参考下图以便更好地理解。
In addition to organizing data in a structured way, binary search trees also provide additional functionality such as efficient searching and sorting because of the two properties of the binary search tree.
除了以结构化方式组织数据外,二叉搜索树还提供了附加功能,如高效的搜索和排序,这得益于二叉搜索树的这两个性质。
Binary search trees are commonly used in computer science applications such as databases and networking systems because they allow for fast retrieval of the most important information from large sets of data.
二叉搜索树常用于计算机科学应用,如数据库和网络系统,因为它们能快速从大量数据中检索最重要信息。
277. Explain Stack as Data Structure. Also, explain what are the real-time applications of Stack.
解释栈作为数据结构是什么。同时,说明栈的实时应用有哪些。
- 知识点: 算法与数据结构 (标签: interviewbit, nagarro, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Nagarro
- id: 69b37bf958d557c902bb618b | 官方: 否 | 付费: 否
答案:
The Stack is a collection of data that are stored one on top of another. Stacks can be used to make sure that data is kept in order and has a constant backup in case of an incident. It can also be used to optimize the organization of your data by storing it in the most efficient way possible.
栈是一种数据集合,数据一个接一个地存储。栈可用于确保数据有序,并在发生事故时提供持续备份。它还可以通过以尽可能高效的方式存储数据来优化数据组织。
For example, if you have a lot of data about your customers that you would like to organize, you could store all your customer records on one big stack. Then, when you need information about a particular customer, you can just pull out their record from the stack. This makes finding information much easier.
例如,如果你有大量关于客户的数据想组织起来,你可以将所有客户记录存储在一个大栈中。然后,当需要特定客户的信息时,只需从栈中取出他们的记录。这使查找信息变得容易得多。
Stack data structures are widely used in programming. They are the most commonly used data structure in the world of computers. This is because it simplifies the process of storing and retrieving data.
栈数据结构在编程中被广泛使用。它们是计算机世界中最常用的数据结构。这是因为它们简化了存储和检索数据的过程。
It is also useful for storing several values of the same type. For example, you can use a stack to store passwords. The stack will keep track of which password you have already entered. When you enter a new password, it will be pushed onto the stack. When it reaches the top, it is removed from the stack, and you will be prompted to enter a new password.
它也适用于存储同类型的多个值。例如,你可以使用栈来存储密码。栈会跟踪你已经输入过的密码。当你输入新密码时,它会被压入栈中。当它到达栈顶时,会从栈中移除,然后系统会提示你输入新密码。
The other main advantage of using a stack is that it makes it easier to build algorithms that perform array operations. This is because there are no arrays involved. Instead, it takes just one value at a time and pushes it onto the top of the stack until it reaches the bottom again. This makes things much simpler than using an array when performing certain operations like addition, subtraction, and comparing items in an array.
使用栈的另一个主要优点是它更容易构建执行数组操作的算法。这是因为不涉及数组。相反,它一次只取一个值并将其压入栈顶,直到再次到达栈底。在执行加法、减法和比较数组元素等操作时,这比使用数组简单得多。
Nagarro Interview Preparation
278. What exactly is merge sort, and how does it work?
归并排序到底是什么,它是如何工作的?
- 知识点: 算法与数据结构 (标签: interviewbit, ntt-data, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: NTT DATA
- id: 69b37bff58d557c902bb6612 | 官方: 否 | 付费: 否
答案:
Merge sort is an efficient, general-purpose, comparison-based sorting algorithm that works by dividing an array into two halves, sorting each half, and then merging them back together.
归并排序是一种高效、通用的基于比较的排序算法,工作原理是将数组分成两半,对每半进行排序,然后合并回一起。
Here is an example of how merge sort works:
以下是一个归并排序如何工作的示例:
Divide the input array into two halves. 2. Recursively sort each half. 3. Merge the sorted halves back together.
- 将输入数组分成两半。 2. 递归地对每半部分排序。 3. 将排序后的两半合并回一起。
The key idea behind merge sort is that it is a "divide and conquer" algorithm, which means that it breaks down a problem into smaller subproblems, solves each subproblem separately, and then combines the solutions to the subproblems to get the solution to the original problem.
归并排序的关键思想是它是一种“分而治之”的算法,这意味着它将问题分解为更小的子问题,分别解决每个子问题,然后将子问题的解决方案组合起来得到原问题的解决方案。
To merge the sorted halves back together, merge sort uses a "merge" function that compares the elements at the beginning of each half and adds the smaller element to the result array. This process is repeated until one of the halves is empty, at which point the remaining elements from the other half are added to the result array.
为了将排序后的两半合并回一起,归并排序使用一个“合并”函数,该函数比较每半部分开头的元素,并将较小的元素添加到结果数组中。此过程重复进行,直到其中一半为空,此时将另一半中的剩余元素添加到结果数组中。
Here is an example of the merge function in Python:
以下是一个 Python 中合并函数的示例:
def merge(left, right):
def merge(left, right):
result = []
result = []
while left and right:
while left and right:
if left[0] <= right[0]:
if left[0] <= right[0]:
result.append(left.pop(0))
result.append(left.pop(0))
else:
否则:
result.append(right.pop(0))
result.append(right.pop(0))
result.extend(left)
result.extend(left)
result.extend(right)
result.extend(right)
return result
return result
Merge sort has a time complexity of O(n*log(n)), which means that it is very efficient for sorting large arrays. It is a stable sort, which means that it preserves the relative order of elements with equal keys.
归并排序的时间复杂度为 O(n*log(n)),这意味着它对大型数组的排序非常高效。它是一种稳定排序,这意味着它保留了相等键元素的相对顺序。
279. What is a DLL (Doubly-Linked-List)? What applications does it have?
什么是 DLL(双向链表)?它有哪些应用?
- 知识点: 算法与数据结构 (标签: interviewbit, ntt-data, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: NTT DATA
- id: 69b37bff58d557c902bb6618 | 官方: 否 | 付费: 否
答案:
A doubly-linked list (DLL) is a type of data structure that consists of a sequence of nodes, each of which contains a value and pointers to the previous and next nodes in the sequence.
双向链表(DLL)是一种数据结构类型,由一系列节点组成,每个节点包含一个值以及指向序列中前一个和下一个节点的指针。
Doubly-linked lists are similar to singly-linked lists, which are lists that only have pointers to the next node in the sequence. However, doubly-linked lists have the additional benefit of being able to be traversed in both directions, which makes them more flexible and efficient for certain operations.
双向链表类似于单向链表,单向链表仅具有指向序列中下一个节点的指针。然而,双向链表具有额外的好处,即可以双向遍历,这使得它在某些操作上更加灵活和高效。
Here is an example of a simple doubly-linked list in Python:
以下是一个简单的 Python 双向链表示例:
class Node:
class Node:
def __init__(self, val):
def __init__(self, val):
self.val = val
self.val = val
self.prev = None
self.prev = None
self.next = None
self.next = None
class DoublyLinkedList:
class DoublyLinkedList:
def __init__(self):
def __init__(self):
self.head = None
self.head = None
self.tail = None
self.tail = None
self.size = 0
self.size = 0
def append(self, val):
def append(self, val):
new_node = Node(val)
new_node = Node(val)
if self.head is None:
if self.head is None:
self.head = new_node
self.head = new_node
self.tail = new_node
self.tail = new_node
else:
否则:
self.tail.next = new_node
self.tail.next = new_node
new_node.prev = self.tail
new_node.prev = self.tail
self.tail = new_node
self.tail = new_node
self.size += 1
self.size += 1
Doubly-linked lists have a number of applications, including: - Implementing stacks and queues
双向链表有许多应用,包括:- 实现栈和队列
- Implementing memory pools
- Implementing undirected graphs
- Implementing associative arrays
280. What is Banker's algorithm?
什么是银行家算法?
- 知识点: 算法与数据结构 (标签: interviewbit, ntt-data, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: NTT DATA
- id: 69b37bff58d557c902bb6623 | 官方: 否 | 付费: 否
答案:
The Banker's algorithm is an algorithm used to manage the allocation of resources in a computer system. It is a deadlock avoidance algorithm that is used to prevent a system from entering a deadlock state, which is a situation where a system is unable to make progress because all of its resources are being used and none are available for new requests.
银行家算法是一种用于管理计算机系统中资源分配的算法。它是一种死锁避免算法,用于防止系统进入死锁状态,死锁状态是指系统因所有资源都被占用而没有资源可供新请求使用而无法继续推进的情况。
The Banker's algorithm works by maintaining a table of the resources that are available in the system, as well as the resources that are currently allocated to each process. It uses this information to determine whether a request for resources from a process can be granted without causing the system to enter a deadlock state.
银行家算法通过维护系统中可用资源的表格以及当前分配给每个进程的资源来工作。它利用这些信息来确定进程的资源请求是否可以在不使系统进入死锁状态的情况下得到批准。
To do this, the Banker's algorithm compares the resources requested by a process with the resources currently available in the system. If the resources are available, the request is granted, and the resources are allocated to the process. If the resources are not available, the request is denied, and the process must wait until the resources become available.
为此,银行家算法将进程请求的资源与系统中当前可用的资源进行比较。如果资源可用,则批准请求,并将资源分配给该进程。如果资源不可用,则拒绝请求,进程必须等到资源变得可用。
The Banker's algorithm is used in resource allocation systems to ensure that resources are used efficiently and to prevent deadlocks from occurring. It is an important algorithm in the field of computer science and is widely used in operating systems and other resource allocation systems.
银行家算法在资源分配系统中用于确保资源得到高效利用并防止死锁的发生。它是计算机科学领域中的一个重要算法,广泛应用于操作系统和其他资源分配系统中。
281. What data structure underlies a Python list?
Python 列表底层的数据结构是什么?
- 知识点: 算法与数据结构 / 编程语言基础 (标签: interviewbit, ntt-data, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: NTT DATA
- id: 69b37bff58d557c902bb662f | 官方: 否 | 付费: 否
答案:
The underlying data structure of a Python list is an array. Specifically, it is a dynamic array that can resize itself as needed to accommodate new elements. The elements of a list can be of any data type, including other lists, and they can be added, removed, and modified using various built-in methods and operations. The array data structure allows for fast indexing and efficient memory usage, making lists a versatile and powerful tool in Python programming.
Python 列表的底层数据结构是数组。具体来说,它是一个动态数组,可以根据需要自动调整大小以容纳新元素。列表的元素可以是任何数据类型,包括其他列表,并且可以通过各种内置方法和操作进行添加、删除和修改。数组数据结构支持快速索引和高效的内存使用,使列表成为 Python 编程中通用且强大的工具。
282. Implement a "min-stack" (a data structure that behaves just like a stack in terms of push and pop but also supports a function min that returns (but does not pop) the minimum number currently on the stack)?
实现一个“最小栈”(一个数据结构,在 push 和 pop 行为上与栈完全相同,但还支持一个 min 函数,该函数返回(但不弹出)当前栈中的最小数)?
- 知识点: 算法与数据结构 (标签: interviewbit, ntt-data, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: NTT DATA
- id: 69b37bff58d557c902bb6647 | 官方: 否 | 付费: 否
答案:
Here is an implementation of a "min-stack" in Python:
以下是一个在 Python 中的“最小栈”实现:
class MinStack:
class MinStack:
def __init__(self):
def __init__(self):
self.stack = []
self.stack = []
self.min_stack = []
self.min_stack = []
def push(self, value):
def push(self, value):
self.stack.append(value)
self.stack.append(value)
if not self.min_stack or value <= self.min_stack[-1]:
if not self.min_stack or value <= self.min_stack[-1]:
self.min_stack.append(value)
self.min_stack.append(value)
def pop(self):
def pop(self):
if not self.stack:
if not self.stack:
return None
return None
value = self.stack.pop()
value = self.stack.pop()
if value == self.min_stack[-1]:
if value == self.min_stack[-1]:
self.min_stack.pop()
self.min_stack.pop()
return value
返回 value
def min(self):
def min(self):
if not self.min_stack:
if not self.min_stack:
return None
return None
return self.min_stack[-1]
返回 self.min_stack[-1]
The MinStack class has two internal stacks: stack and min_stack. The stack stack behaves just like a normal stack and is used to store values pushed onto the stack. The min_stack stack is used to store the minimum values seen so far.
MinStack 类有两个内部栈:stack 和 min_stack。stack 栈的行为类似于普通栈,用于存储推入栈中的值。min_stack 栈用于存储到目前为止所见到的最小值。
When a value is pushed onto the stack using the push method, it is added to the stack stack. If the min_stack stack is empty or the value is less than or equal to the current minimum value, the value is also added to the min_stack stack.
当使用 push 方法将值推入栈中时,该值会被添加到 stack 栈中。如果 min_stack 栈为空,或该值小于或等于当前最小值,则该值也会被添加到 min_stack 栈中。
When a value is popped off the stack using the pop method, it is removed from the stack stack. If the popped value is the same as the current minimum value (i.e., the value at the top of the min_stack stack), it is also removed from the min_stack stack.
当使用 pop 方法将值从栈中弹出时,该值会从 stack 栈中移除。如果弹出的值与当前最小值(即 min_stack 栈顶的值)相同,则该值也会从 min_stack 栈中移除。
Finally, the min method returns the current minimum value on the stack (i.e., the value at the top of the min_stack stack). If the min_stack stack is empty, the method returns None.
最后,min 方法返回栈中的当前最小值(即 min_stack 栈顶的值)。如果 min_stack 栈为空,该方法返回 None。
With this implementation, we can create a MinStack object and use it just like a regular stack, but we also have access to the minimum value on the stack using the min method. For example:
通过这种实现,我们可以创建 MinStack 对象,并像使用普通栈一样使用它,但还可以通过 min 方法访问栈中的最小值。例如:
stack = MinStack()
stack = MinStack()
stack.push(3)
stack.push(3)
stack.push(1)
stack.push(1)
stack.push(4)
stack.push(4)
stack.push(2)
stack.push(2)
print(stack.min()) # Output: 1
print(stack.min()) # 输出: 1
stack.pop()
stack.pop()
stack.pop()
stack.pop()
print(stack.min()) # Output: 3
print(stack.min()) # 输出: 3
Useful Resources
有用资源
- Data Science Interview Questions
- Java Interview Questions
- Data Engineer Interview Questions
- Software Engineering Interview Questions
- Front End Developer Interview Questions
- Technical Interview Questions
- Coding Interview Questions
283. Find the smallest window in array sorting which will make the entire array sorted?
找到数组中最小的窗口,对该窗口排序后能使整个数组有序?
- 知识点: 算法与数据结构 (标签: interviewbit, ntt-data, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: NTT DATA
- id: 69b37bff58d557c902bb6651 | 官方: 否 | 付费: 否
答案:
To find the smallest window in an array that, when sorted, will make the entire array sorted, you can use a sliding window approach. Here is an outline of the algorithm:
要找到数组中最小的窗口,对该窗口排序后能使整个数组有序,可以使用滑动窗口方法。以下是算法概述:
Initialize two pointers, left and right, to the first and last element of the array, respectively. 2. While the left pointer is less than the right pointer: Find the minimum value in the array between the left and right pointers. Find the maximum value in the array between the left and right pointers. If the minimum value is greater than or equal to the value at the left pointer, increment the left pointer. If the maximum value is less than or equal to the value at the right pointer, decrement the right pointer. 3. Return the window between the left and right pointers as the smallest window that, when sorted, will make the entire array sorted.
- 初始化两个指针,左指针和右指针,分别指向数组的第一个和最后一个元素。 2. 当左指针小于右指针时:在左右指针之间找到数组中的最小值。在左右指针之间找到数组中的最大值。如果最小值大于或等于左指针位置的值,则左指针递增。如果最大值小于或等于右指针位置的值,则右指针递减。 3. 返回左右指针之间的窗口,该窗口排序后能使整个数组有序。
Here is an example of how this algorithm could be implemented in Java:
以下是该算法在Java中实现的一个示例:
int[] array = {4, 5, 6, 1, 2, 3};
int[] array = {4, 5, 6, 1, 2, 3};
int left = 0;
int left = 0;
int right = array.length - 1;
int right = array.length - 1;
while (left < right) {
while (left < right) {
int min = Integer.MAX_VALUE;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int max = Integer.MIN_VALUE;
for (int i = left; i <= right; i++) {
for (int i = left; i <= right; i++) {
min = Math.min(min, array[i]);
min = Math.min(min, array[i]);
max = Math.max(max, array[i]);
max = Math.max(max, array[i]);
}
if (min >= array[left]) {
if (min >= array[left]) {
left++;
left++;
}
if (max <= array[right]) {
if (max <= array[right]) {
right--;
right--;
}
}
int[] window = Arrays.copyOfRange(array, left, right + 1);
int[] window = Arrays.copyOfRange(array, left, right + 1);
System.out.println(Arrays.toString(window));
System.out.println(Arrays.toString(window));
This will print out the smallest window in the array that, when sorted, will make the entire array sorted, which in this case is [1, 2, 3].
这将打印出数组中最小子数组,当对其进行排序后,会使整个数组变得有序,在此例中为 [1, 2, 3]。
284. Give an example of binary search in real life?
举一个二分查找在现实生活中的例子?
- 知识点: 算法与数据结构 (标签: interviewbit, ntt-data, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: NTT DATA
- id: 69b37bff58d557c902bb6657 | 官方: 否 | 付费: 否
答案:
Binary search is a search algorithm that is used to find a specific element in a sorted list or array. It works by dividing the list or array in half at each iteration and searching only in the half that is likely to contain the target element. This makes it an efficient algorithm for finding a specific element in large lists or arrays.
二分查找是一种搜索算法,用于在已排序的列表或数组中查找特定元素。它通过在每次迭代时将列表或数组分成两半,并仅在可能包含目标元素的那一半中进行搜索来实现。这使得它成为在大型列表或数组中查找特定元素的高效算法。
One example of binary search in real life is finding a specific book in a library. Imagine you are looking for a book in a library with thousands of books arranged in alphabetical order by the author's last name. Instead of starting at the beginning of the library and looking at every book until you find the one you are looking for, you could use binary search to quickly find the book. Here is how the process might work:
二分查找在现实生活中的一个例子是在图书馆中查找特定书籍。假设你在一个图书馆中寻找一本书,馆内有成千上万本书,按作者的姓氏按字母顺序排列。你可以不用从图书馆开头开始,逐一查看每本书直到找到你要找的那本,而可以使用二分查找快速找到它。以下是过程可能的样子:
First, you would look at the middle book on the shelf and check the author's last name. 2. If the last name of the author of the book you are looking for is alphabetically before the last name of the author of the middle book, you would know that the book you are looking for is on the first half of the shelf. You would then look at the middle book on the first half of the shelf and repeat the process. 3. If the last name of the author of the book you are looking for is alphabetically after the last name of the author of the middle book, you would know that the book you are looking for is on the second half of the shelf. You would then look at the middle book on the second half of the shelf and repeat the process. 4. If the last name of the author of the book you are looking for is the same as the last name of the author of the middle book, you would have found the book and you could stop the search.
- 首先,你会查看书架上中间的书,并检查作者的姓氏。 2. 如果你要找的书的作者姓氏在字母顺序上位于中间那本书的作者姓氏之前,你就会知道你要找的书在书架的前半部分。然后你会查看前半部分中间的书并重复该过程。 3. 如果你要找的书的作者姓氏在字母顺序上位于中间那本书的作者姓氏之后,你就会知道你要找的书在书架的后半部分。然后你会查看后半部分中间的书并重复该过程。 4. 如果你要找的书的作者姓氏与中间那本书的作者姓氏相同,你就找到了这本书,可以停止搜索。
By repeating this process, you can quickly narrow down the search to a small section of the library and find the book you are looking for in a fraction of the time it would take to look at every book on the shelf.
通过重复这个过程,你可以快速将搜索范围缩小到图书馆的一小部分,并在比逐本查看书架上每本书所需时间少得多的时间内找到你要找的书。
285. Given a matrix of integers, find the length of the longest path in the matrix such that all the elements in the path are increasing in value.
给定一个整数矩阵,找出矩阵中最长路径的长度,使得路径中的所有元素值递增。
- 知识点: 算法与数据结构 (标签: interviewbit, ntt-data, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: NTT DATA
- id: 69b37bff58d557c902bb665a | 官方: 否 | 付费: 否
答案:
To find the longest path in a matrix in Java, you can use a dynamic programming approach. Here is an outline of the algorithm:
要在Java中找出矩阵中的最长路径,你可以使用动态规划方法。以下是算法的概述:
Initialize a 2D array dp to store the longest path from each cell to the end of the matrix. Initialize all values in dp to -1. 2. For each cell (i, j) in the matrix: If dpi is not -1, skip it (we have already processed it). If (i, j) is the last cell in the matrix, set dpi to 1. Otherwise, set dpi to the maximum of dpi + 1, dpi, and dpi + 1, plus 1. 3. Return the maximum value in dp.
- 初始化一个二维数组dp,用于存储从每个单元格到矩阵末尾的最长路径。将dp中的所有值初始化为-1。 2. 对于矩阵中的每个单元格(i, j):如果dpi不是-1,则跳过它(我们已经处理过它)。如果(i, j)是矩阵中的最后一个单元格,则将dpi设置为1。否则,将dpi设置为dpi + 1、dpi和dpi + 1中的最大值,再加上1。 3. 返回dp中的最大值。
Here is an example of how this algorithm could be implemented in Java:
以下是该算法在Java中实现的一个示例:
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int rows = matrix.length;
int rows = matrix.length;
int cols = matrix[0].length;
int cols = matrix[0].length;
int[][] dp = new introws;
int[][] dp = new introws;
for (int[] row : dp) {
for (int[] row : dp) {
Arrays.fill(row, -1);
Arrays.fill(row, -1);
}
int longestPath = findLongestPath(matrix, dp, rows - 1, cols - 1);
int longestPath = findLongestPath(matrix, dp, rows - 1, cols - 1);
System.out.println(longestPath);
System.out.println(longestPath);
public static int findLongestPath(int[][] matrix, int[][] dp, int i, int j) {
public static int findLongestPath(int[][] matrix, int[][] dp, int i, int j) {
if (dpi != -1) {
if (dpi != -1) {
return dpi;
return dpi;
}
if (i == rows - 1 && j == cols - 1) {
if (i == rows - 1 && j == cols - 1) {
dpi = 1;
dpi = 1;
} else {
} else {
int right = 0;
int right = 0;
int down = 0;
int down = 0;
int diagonal = 0;
int diagonal = 0;
if (i < rows - 1) {
if (i < rows - 1) {
down = findLongestPath(matrix, dp, i + 1, j);
down = findLongestPath(matrix, dp, i + 1, j);
}
if (j < cols - 1) {
if (j < cols - 1) {
right = findLongestPath(matrix, dp, i, j + 1);
right = findLongestPath(matrix, dp, i, j + 1);
}
if (i < rows - 1 && j < cols - 1) {
if (i < rows - 1 && j < cols - 1) {
diagonal = findLongestPath(matrix, dp, i + 1, j + 1);
diagonal = findLongestPath(matrix, dp, i + 1, j + 1);
}
dpi = Math.max(Math.max(right, down), diagonal) + 1;
dpi = Math.max(Math.max(right, down), diagonal) + 1;
}
return dpi;
return dpi;
}
This will print out the length of the longest path in the matrix, which in this case is 3.
这将打印出矩阵中最长路径的长度,在本例中为3。
286. What is a quick sort?
什么是快速排序?
- 知识点: 算法与数据结构 (标签: interviewbit, ntt-data, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: NTT DATA
- id: 69b37bff58d557c902bb665d | 官方: 否 | 付费: 否
答案:
Quick sort is a sorting algorithm that is used to sort an array or list of items in ascending or descending order. It is a divide-and-conquer algorithm that works by partitioning the array into two halves, sorting each half, and then merging the sorted halves back together.
快速排序是一种排序算法,用于按升序或降序对数组或项目列表进行排序。它是一种分治算法,通过将数组分成两半,对每一半进行排序,然后将排序好的两半合并回来。
Here are the steps of the quick sort algorithm:
以下是快速排序算法的步骤:
Choose a pivot element from the array. This is typically the first element, but it can be any element in the array. 2. Divide the array into two halves: a left half containing all elements that are less than the pivot, and a right half containing all elements that are greater than or equal to the pivot. 3. Recursively sort the left and right halves. 4. Merge the sorted left and right halves back together, with the pivot element in between.
- 从数组中选择一个基准元素。这通常是第一个元素,但也可以是数组中的任意元素。 2. 将数组分成两半:左半部分包含所有小于基准的元素,右半部分包含所有大于或等于基准的元素。 3. 递归地对左半部分和右半部分进行排序。 4. 将排序好的左半部分和右半部分合并回来,并将基准元素放在中间。
Quick sort is a highly efficient sorting algorithm, with time complexity of O(n log n) on average. It is also an in-place algorithm, meaning it does not require additional memory to sort the array.
快速排序是一种高效的排序算法,平均时间复杂度为O(n log n)。它也是一种原地算法,意味着不需要额外的内存来排序数组。
Here is an example of how quick sort could be implemented in Java:
以下是一个如何在Java中实现快速排序的示例:
int[] array = {3, 5, 1, 2, 4};
int[] array = {3, 5, 1, 2, 4};
quicksort(array, 0, array.length - 1);
quicksort(array, 0, array.length - 1);
public static void quicksort(int[] array, int left, int right) {
public static void quicksort(int[] array, int left, int right) {
if (left < right) {
if (left < right) {
int pivot = partition(array, left, right);
int pivot = partition(array, left, right);
quicksort(array, left, pivot - 1);
quicksort(array, left, pivot - 1);
quicksort(array, pivot + 1, right);
quicksort(array, pivot + 1, right);
}
}
public static int partition(int[] array, int left, int right) {
public static int partition(int[] array, int left, int right) {
int pivot = array[right];
int pivot = array[right];
int i = left - 1;
int i = left - 1;
for (int j = left; j < right; j++) {
for (int j = left; j < right; j++) {
if (array[j] < pivot) {
if (array[j] < pivot) {
i++;
i++;
int temp = array[i];
int temp = array[i];
array[i] = array[j];
array[i] = array[j];
array[j] = temp;
array[j] = temp;
}
}
int temp = array[i + 1];
int temp = array[i + 1];
array[i + 1] = array[right];
array[i + 1] = array[right];
array[right] = temp;
array[right] = temp;
return i + 1;
return i + 1;
}
The partition() function is responsible for dividing the array into two halves based on the pivot element. It does this by using a two-pointer approach, with one pointer (i) starting at the left side of the array and the other pointer (j) starting at the left + 1. The partition() function then iterates through the array, swapping elements that are less than the pivot with elements on the left side of the pivot. When the iteration is complete, the pivot element is placed in its correct position in the array and the function returns the pivot's index.
partition() 函数负责根据基准元素将数组分成两部分。它通过使用双指针方法来实现,其中一个指针(i)从数组左侧开始,另一个指针(j)从左侧+1开始。然后partition()函数遍历数组,将小于基准的元素与基准左侧的元素进行交换。当遍历完成后,基准元素被放置在数组中的正确位置,函数返回基准的索引。
287. What are some of the most common data-structure operations?
一些最常见的数据结构操作有哪些?
- 知识点: 算法与数据结构 (标签: interviewbit, ntt-data, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: NTT DATA
- id: 69b37c0058d557c902bb6693 | 官方: 否 | 付费: 否
答案:
Here are some common data-structure operations that are frequently used in programming and computer science:
以下是一些在编程和计算机科学中常用的数据结构操作:
Insertion: Adding a new element to a data structure. 2. Deletion: Removing an element from a data structure. 3. Searching: Finding an element in a data structure based on a given key or value. 4. Sorting: Arranging the elements of a data structure in a specific order. 5. Traversal: Visiting each element in a data structure and performing some operation on it. 6. Merging: Combining two or more data structures into a single data structure. 7. Splitting: Dividing a data structure into two or more smaller data structures.
- 插入:向数据结构中添加一个新元素。2. 删除:从数据结构中移除一个元素。3. 搜索:根据给定的键或值在数据结构中查找元素。4. 排序:按特定顺序排列数据结构的元素。5. 遍历:访问数据结构中的每个元素并对其执行某些操作。6. 合并:将两个或多个数据结构组合成一个单独的数据结构。7. 拆分:将数据结构分成两个或多个较小的数据结构。
These operations can be performed on various types of data structures, such as arrays, linked lists, stacks, queues, trees, and graphs. The specific operations and algorithms used to perform these operations will depend on the type of data structure and the specific requirements of the application.
这些操作可以应用于各种类型的数据结构,如数组、链表、栈、队列、树和图。用于执行这些操作的具体算法和操作方式将取决于数据结构的类型和应用程序的具体需求。
288. Create an algorithm to assess if a number n has content. A happy number is one that is defined by the following procedure: Begin with any positive integer and replace it with the sum of its digit squares.
创建一个算法来评估数字n是否有内容。快乐数是通过以下过程定义的一个数:以任意正整数开始,将其替换为其各位数字的平方和。
- 知识点: 算法与数据结构 (标签: interviewbit, optum, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Optum
- id: 69b37c0758d557c902bb6ac0 | 官方: 否 | 付费: 否
答案:
Repeat the procedure until the number equals 1 (where it will remain), at which point it will run indefinitely in a cycle that does not contain 1. Those numbers whose procedure results in a 1 are content. If n is a happy number, return true; otherwise, return false.
重复该过程,直到数字等于1(此时它将保持不变),而在这个点上,它将在不包含1的循环中无限运行。那些过程结果为1的数字是有内容的。如果n是快乐数,则返回true;否则返回false。
Example 1: - Input: n = 19
示例1:- 输入:n = 19
- Output: true
Explanation:1^2 + 9^2 = 828^2 + 2^2 = 686^2 + 8^2 = 1001^2 + 0^2 + 0^2 = 1
Example 2: - Input: n = 2示例2:- 输入:n = 2
Output: false
We can keep track of the numbers using a map. This is analogous to identifying a loop. if a number has previously been computed It suggests we're stuck in a rut. I used a string to make it easier to handle the numbers (the number has a limit of 231). If the number has already been discovered, we return false; otherwise, we generate a new number. Using the string We interrupt the loop and return true when the number is 1.我们可以使用map来跟踪数字。这类似于识别循环。如果某个数字之前已经被计算过,则表明我们陷入了一个循环。我使用字符串来更方便地处理数字(该数字有231的限制)。如果该数字已经被发现,我们返回false;否则,我们生成一个新数字。使用字符串当我们得到数字1时,中断循环并返回true。
unordered_map<int,bool>map;
unordered_map<int,bool>map;
bool isHappy(int n) {
bool isHappy(int n) {
while(n!=1)
而while(n!=1)
{
string s = to_string(n);
string s = to_string(n);
if(map[n]==true)
if(map[n]==true)
{
return false;
返回 false;
}
else{
否则{
map[n] = true;
map[n] = true;
n=0;
n=0;
for(auto i:s)
对于(auto i:s)
n+=(i-'0')*(i-'0');
n+=(i-'0')*(i-'0');
}
}
return n==1;
返回 n==1;
}
289. To determine whether an integer x is a palindrome, simple return true or false, if it is. A palindrome is an integer that reads the same backwards as forwards. For example, 121 is a palindrome while 123 is not.
要判断整数 x 是否为回文数,如果是,则直接返回 true 或 false。回文数是指正着读和倒着读都相同的整数。例如,121 是回文数,而 123 不是。
- 知识点: 算法与数据结构 (标签: interviewbit, optum, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Optum
- id: 69b37c0758d557c902bb6b0a | 官方: 否 | 付费: 否
答案:
Example 1: - Input: x = 121
示例 1: - 输入:x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.解释:121 从左到右和从右到左读都是 121。
Example 2: - Input: x = -121
示例 2: - 输入:x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore, it is not a palindrome.解释:从左到右读是 -121。从右到左读变成了 121-。因此,它不是回文数。
Example 3: - Input: x = 10
示例 3: - 输入:x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore, it is not a palindrome.解释:从右到左读是 01。因此,它不是回文数。
We want to see whether the lower half of x equals the higher half of x, for example, when x = 1234321, we wish to ascertain whether 123 equals 123, The only pertinent situation is where x is unspecified, as can be seen by the examples. If x is, for example, 0, then it's very evident that it is not a Palindrome, so we may simply return true.
我们希望判断 x 的下半部分是否等于 x 的上半部分,例如,当 x = 1234321 时,我们希望确认 123 是否等于 123。唯一相关的情况是 x 未指定,如示例所示。如果 x 是,例如,0,那么很明显它不是回文数,因此我们可以直接返回 true。
public class Solution {
public class Solution {
public boolean isPalindrome(int x) {
public boolean isPalindrome(int x) {
if(x == 0)
if(x == 0)
return true;
返回 true;
if(x < 0 || x % 10 == 0)
if(x < 0 || x % 10 == 0)
return false;
返回 false;
int v = 0;
int v = 0;
while(x > v) {
while(x > v) {
v = x % 10 + v * 10;
v = x % 10 + v * 10;
x = x / 10;
x = x / 10;
}
return x == v || v / 10 == x;
return x == v || v / 10 == x;
}
}
290. A simple algorithm can be developed to detect whether or not a given integer fits into a sorted array of distinct values. If the target value is not found, then return the index at which it would be inserted in order.
可以开发一个简单的算法来检测给定整数是否适合放入一个由不同值组成的有序数组中。如果未找到目标值,则返回按顺序插入该值时应插入的索引。
- 知识点: 算法与数据结构 (标签: interviewbit, optum, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Optum
- id: 69b37c0758d557c902bb6b10 | 官方: 否 | 付费: 否
答案:
You must design an algorithm with a Log(n) runtime complexity.
你必须设计一种时间复杂度为 Log(n) 的算法。
Example 1: - Input: nums = [1,3,5,6], target = 5
示例 1:- 输入:nums = [1,3,5,6],目标值 = 5
Output: 2
Example 2: - Input: nums = [1,3,5,6], target = 2示例 2:- 输入:nums = [1,3,5,6],目标值 = 2
Output: 1
Example 3: - Input: nums = [1,3,5,6], target = 7示例 3:- 输入:nums = [1,3,5,6],目标值 = 7
At the start of the binary search, the array is checked to see if its edges include the target, and the rest of the process follows the same steps as the binary search. However, binary search also checks to see if the target is between the value lower and higher than the mid in order to ensure that the target is found.
二分搜索开始时,会检查数组的边缘是否包含目标值,其余过程与二分搜索相同。然而,二分搜索还会检查目标值是否位于比中间值低和高的值之间,以确保找到目标值。
class Solution {
class Solution {
public:
public:
int searchInsert(vector& nums, int target) {
int searchInsert(vector& nums, int target) {
if(nums.front() >= target) return 0;
if(nums.front() >= target) return 0;
if(nums.back() == target) return nums.size()-1;
if(nums.back() == target) return nums.size()-1;
if(nums.back() < target) return nums.size();
if(nums.back() < target) return nums.size();
int low = 0;
int low = 0;
int high = nums.size();
int high = nums.size();
int mid = 0;
int mid = 0;
while(low < high) {
while(low < high) {
mid = (low + high) / 2;
mid = (low + high) / 2;
if(nums[mid] == target) return mid;
if(nums[mid] == target) return mid;
if(nums[mid-1] < target && nums[mid] > target) return mid;
if(nums[mid-1] < target && nums[mid] > target) return mid;
else if(nums[mid] < target) low = mid;
else if(nums[mid] < target) low = mid;
else high = mid;
else high = mid;
}
return mid;
返回 mid;
}
291. A statement is considered a palindrome if it reads the same both forward and backwards after all uppercase letters have been changed to lowercase and all non-alphanumeric characters have been eliminated.
如果一个语句在将所有大写字母改为小写并删除所有非字母数字字符后,正向和反向读起来相同,则该语句被视为回文。
- 知识点: 算法与数据结构 (标签: interviewbit, optum, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Optum
- id: 69b37c0858d557c902bb6b43 | 官方: 否 | 付费: 否
答案:
There are letters and numbers among alphanumeric characters. Return true or false depending on if the string s is a palindrome when one is provided.
字母数字字符中包含字母和数字。当给定字符串 s 时,根据其是否为回文返回 true 或 false。
Example 1: - Input: s = "Do geese see God"
示例 1:- 输入:s = "Do geese see God"
Output: true
Explanation: "dogeeseseegod" is a palindrome.解释:"dogeeseseegod" 是一个回文。
Example 2: - Input: s = "hello world"
示例 2:- 输入:s = "hello world"
Output: false
Explanation: "helloworld" is not a palindrome.解释:"helloworld" 不是一个回文。
Example 3: - Input: s = " "
示例 3:- 输入:s = " "
Output: true
Explanation: After deleting all of the characters that are not alphanumeric, s is left as an empty string "". A palindrome is a string that may be read either forward or backwards and yet produce the same meaning.解释:删除所有非字母数字字符后,s 剩下一个空字符串 ""。回文是一种无论正向还是反向读取都能产生相同含义的字符串。
We first created a string in which we could store the alphanumeric characters(e.g 0 to 9, a, b, c, etc). We separated the alphanumeric characters using the characters from the specific ASCII value range. Then we used the palindrome function(two pointers) to obtain them back again.
我们首先创建了一个字符串,用于存储字母数字字符(例如 0 到 9、a、b、c 等)。我们使用特定 ASCII 值范围内的字符来分隔字母数字字符。然后我们使用回文函数(双指针)将它们重新取回。
bool isPalindrome(string s) {
bool isPalindrome(string s) {
string b;
string b;
for(int i=0;i<s.length();i++){
for(int i=0;i<s.length();i++){
if((s[i]>=65 && s[i]<=90))
if((s[i]>=65 && s[i]<=90))
b.push_back(s[i]+32);
b.push_back(s[i]+32);
else if(s[i]>=97 && s[i]<=122)
else if(s[i]>=97 && s[i]<=122)
b.push_back(s[i]);
b.push_back(s[i]);
else if(s[i]>=48 && s[i]<=57)
否则如果(s[i]>=48 && s[i]<=57)
b.push_back(s[i]);
b.push_back(s[i]);
}
int i=0,j=b.length()-1;
整数 i=0,j=b.length()-1;
while(i<=j){
当(i<=j)时{
if(b[i]!=b[j]){
如果(b[i]!=b[j]){
return false;
返回 false;
}
i++;
i++;
j--;
j--;
}
return true;
返回 true;
}
292. How would you print the nodes in a circular linked list?
你将如何打印循环链表中的节点?
- 知识点: 算法与数据结构 (标签: interviewbit, paypal, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: PayPal
- id: 69b37c0f58d557c902bb6f23 | 官方: 否 | 付费: 否
答案:
def circularList(self):
定义circularList(self):
temp = self.head
临时变量 = self.head
if self.head is not None:
如果 self.head 不是 None:
while(True):
当(True)时:
To print the nodes till we reach 1st node
print(temp.data, end = " ")
打印(temp.data, 结束 = " ")
temp = temp.next
temp = temp.next
if (temp == self.head):
如果 (temp == self.head):
break
中断
Additional Useful Interview Resources:
更多有用的面试资源:
- Data Structure
- Algorithm
- DSA Problems
293. How do you find the depth of a binary tree?
你如何找到二叉树的深度?
- 知识点: 算法与数据结构 (标签: interviewbit, paypal, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: PayPal
- id: 69b37c0f58d557c902bb6f26 | 官方: 否 | 付费: 否
答案:
Code to find the depth of a binary tree:
查找二叉树深度的代码:
To find out the max depth of a tree
class Node:
class Node:
To create a new node
def __init__(self, data):
def __init__(self, data):
self.data = data
self.data = data
self.left = None
self.left = None
self.right = None
self.right = None
Find the maxDepth of a tree i.e. the no. of nodes on the longest path from root node down to leaf node
def maxDepth(node):
定义最大深度(节点):
if node is None:
如果节点为空:
return -1 ;
返回 -1 ;
else :
否则 :
Compute the depth of each subtree
lDepth = maxDepth(node.left)
左深度 = 最大深度(节点.左节点)
rDepth = maxDepth(node.right)
右深度 = 最大深度(节点.右节点)
Use the larger one
if (lDepth > rDepth):
如果(lDepth > rDepth):
return lDepth+1
返回 lDepth+1
else:
否则:
return rDepth+1
返回 rDepth+1
Driver program to test above function
root = Node(1)
root = Node(1)
root.left = Node(2)
root.left = Node(2)
root.right = Node(3)
root.right = Node(3)
root.left.left = Node(4)
root.left.left = Node(4)
root.left.right = Node(5)
root.left.right = Node(5)
print ("The height of the tree is %d" %(maxDepth(root)))
打印("树的高度为 %d" %(maxDepth(root)))
- Data Science
- All Events
- My Events
294. What is binary search?
什么是二分查找?
- 知识点: 算法与数据结构 (标签: interviewbit, paypal, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: PayPal
- id: 69b37c0f58d557c902bb6f30 | 官方: 否 | 付费: 否
答案:
Sorted lists or arrays can be searched with a binary search. This search chooses the midway, dividing the full list into two sections. The centre is compared first.
排序列表或数组可以通过二分查找进行搜索。这种搜索选择中点,将整个列表分成两个部分。首先比较中心元素。
The target value is initially compared to the middle of the list in this search. If it is not located, it makes a judgement on whether to proceed.
在此搜索中,目标值最初与列表的中间元素进行比较。如果未找到,它会判断是否继续。
295. When given a string str, how can you calculate its longest palindromic substring?
当给定一个字符串str时,你如何计算它的最长回文子串?
- 知识点: 算法与数据结构 (标签: interviewbit, paypay, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: PayPay
- id: 69b37c1158d557c902bb701f | 官方: 否 | 付费: 否
答案:
Given a string s, we need to identify the longest palidrome substring.
给定一个字符串s,我们需要找出最长的回文子串。
Code:
代码:
import java.util.*;
import java.util.*;
import java.lang.*;
import java.lang.*;
import java.io.*;
import java.io.*;
class Main
class Main
{
static void printSubStr(String s, int low, int high)
static void printSubStr(String s, int low, int high)
{
for (int i = low; i <= high; ++i)
for (int i = low; i <= high; ++i)
System.out.print(s.charAt(i));
System.out.print(s.charAt(i));
}
public static int longPalindromeSubstr(String s)
public static int longPalindromeSubstr(String s)
{
int l = s.length();
int l = s.length();
// Every subString of length 1 is a palindrome
// 每个长度为1的子字符串都是回文
int maxLength = 1, start = 0;
int maxLength = 1, start = 0;
// Mark start and end index with nested loop
// 使用嵌套循环标记开始和结束索引
for (int i = 0; i < s.length(); i++)
for (int i = 0; i < s.length(); i++)
{
for (int j = i; j < s.length(); j++)
for (int j = i; j < s.length(); j++)
{
int flag = 1;
int flag = 1;
// Check for palindrome
// 检查是否为回文
for (int n = 0; n < (j - i + 1) / 2; n++)
for (int n = 0; n < (j - i + 1) / 2; n++)
if (s.charAt(i + n) != s.charAt(j - n))
if (s.charAt(i + n) != s.charAt(j - n))
flag = 0;
flag = 0;
// Palindrome
// 回文
if (flag!=0 && (j - i + 1) > maxLength)
if (flag!=0 && (j - i + 1) > maxLength)
{
start = i;
start = i;
maxLength = j - i + 1;
maxLength = j - i + 1;
}
}
}
System.out.print("Longest palindromic substring in given string is: ");
System.out.print("给定字符串中的最长回文子串为:");
printSubStr(s, start, start + maxLength - 1);
printSubStr(s, start, start + maxLength - 1);
return maxLength;
return maxLength;
}
public static void main(String args[])
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string: ");
System.out.println("输入一个字符串:");
String s= sc.nextLine();
String s= sc.nextLine();
System.out.println("\nLength: " + longPalindromeSubstr(s));
System.out.println("\n长度: " + longPalindromeSubstr(s));
}
}
Output:
输出:
Enter a string:
输入一个字符串:
Bananas
Bananas
Longest palindromic substring in given string is: anana
给定字符串中的最长回文子串为:anana
Length: 5
长度: 5
Useful Resources
有用资源
- Java Interview Questions
- Software Engineering Interview Questions
- Front End Developer Interview Questions
- Technical Interview Questions
- Coding Interview Questions
- Interview Resources
296. Write a program to check if a given string is a palindrome?
编写一个程序,检查给定字符串是否为回文?
- 知识点: 算法与数据结构 (标签: interviewbit, paypay, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: PayPay
- id: 69b37c1158d557c902bb7022 | 官方: 否 | 付费: 否
答案:
A palindrome string is one that will be the same whether it is read from left to right or right to left.
回文字符串是指从左到右和从右到左读都相同的字符串。
Code:
代码:
// Java program to determine if a string is palindrome
// Java程序,确定字符串是否为回文
import java.util.*;
import java.util.*;
public class Main
public class Main
{
// Returns true if string is palindrome
// 如果字符串是回文,则返回true
static boolean checkPalindrome(String s)
static boolean checkPalindrome(String s) {
{
int i = 0, j = s.length() - 1;
int i = 0, j = s.length() - 1;
while (i < j)
while (i < j) {
{
if (s.charAt(i) != s.charAt(j))
if (s.charAt(i) != s.charAt(j))
return false;
返回 false;
i++;
i++;
j--;
j--;
}
// Given string is a palindrome
// 给定字符串是回文
return true;
返回 true;
}
//Driver method
//驱动方法
public static void main(String[] args)
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string: ");
System.out.println("输入一个字符串:");
String s= sc.nextLine();
String s= sc.nextLine();
//Convert the string to lowercase
//将字符串转换为小写
s = s.toLowerCase();
s = s.toLowerCase();
if (checkPalindrome(s))
if (checkPalindrome(s))
System.out.print("Yes, the given string is a Palindrome!");
System.out.print("是,给定的字符串是回文!");
else
else
System.out.print("No, the given string is not a Palindrome!");
System.out.print("否,给定的字符串不是回文!");
}
}
Sample Output 1:
样本输出 1:
Enter a string:
输入一个字符串:
Level
级别
Yes, the given string is a Palindrome!
是,给定的字符串是回文!
Sample Output 2:
样本输出 2:
Enter a string:
输入一个字符串:
Scaler
Scaler
No, the given string is not a Palindrome!
不,给定的字符串不是回文!
- Data Science
- All Events
- My Events
297. Write a program to check if a given Binary Tree is SumTree or not.
编写一个程序来检查给定的二叉树是否为 SumTree(求和树)。
- 知识点: 算法与数据结构 (标签: interviewbit, paypay, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: PayPay
- id: 69b37c1158d557c902bb7025 | 官方: 否 | 付费: 否
答案:
In a sum tree, the value of each non-leaf node is equal to the sum of its left and right subtrees. A leaf node may have any value, while an empty child node has a value of 0.
在求和树中,每个非叶子节点的值等于其左右子树的和。叶子节点可以具有任意值,而空子节点的值为 0。
Example: Consider the following example of Binary Tree:
示例:考虑以下二叉树示例:
40
/ \
15 5
/ \ \
9 6 5
Now, for each non-leaf node, determine if the node's value is equal to the sum of all elements in its left and right subtrees. The given binary tree cannot be a sum tree if this relation does not hold for any of the nodes.
现在,对于每个非叶子节点,判断该节点的值是否等于其左右子树中所有元素的和。如果该关系对任一节点不成立,则给定的二叉树不能是求和树。
Code:
代码:
// Java program to determine if Binary tree is a sum tree
// Java 程序,用于判断二叉树是否为求和树
import java.io.*;
import java.io.*;
class Node
class Node
{
int val;
int val;
Node left, right, nextRight;
Node left, right, nextRight;
Node(int item)
Node(int item)
{
val = item;
val = item;
left = right = null;
left = right = null;
}
}
class Main
class Main
{
public static Node root;
public static Node root;
static int sum(Node node)
static int sum(Node node)
{
if(node == null)
if(node == null)
{
return 0;
return 0;
}
return (sum(node.left) + node.val+sum(node.right));
return (sum(node.left) + node.val+sum(node.right));
}
static int checkTree(Node node)
static int checkTree(Node node)
{
int sumleft, sumright;
int sumleft, sumright;
//Return true if node is NULL or a leaf node
//如果节点为NULL或叶子节点,则返回true
if(node == null || (node.left == null && node.right == null))
if(node == null || (node.left == null && node.right == null))
{
return 1;
return 1;
}
// Add up nodes in left and right subtrees
//累加左右子树中的节点值
sumleft = sum(node.left);
sumleft = sum(node.left);
sumright = sum(node.right);
sumright = sum(node.right);
if((node.val == sumleft + sumright) && checkTree(node.left) != 0 && checkTree(node.right) != 0)
如果((node.val == sumleft + sumright) && checkTree(node.left) != 0 && checkTree(node.right) != 0)
{
return 1;
return 1;
}
return 0;
return 0;
}
// Driver code
// 驱动代码
public static void main (String[] args)
public static void main (String[] args)
{
Main tree=new Main();
Main tree=new Main();
tree.root = new Node(40);
tree.root = new Node(40);
tree.root.left = new Node(15);
tree.root.left = new Node(15);
tree.root.right = new Node(5);
tree.root.right = new Node(5);
tree.root.left.left = new Node(9);
tree.root.left.left = new Node(9);
tree.root.left.right = new Node(6);
tree.root.left.right = new Node(6);
tree.root.right.right = new Node(5);
tree.root.right.right = new Node(5);
if(checkTree(root) != 0)
如果(checkTree(root) != 0)
{
System.out.println("This is a SumTree!");
System.out.println("这是一个和树!");
}
else
else
{
System.out.println("This is not a SumTree!");
System.out.println("This is not a SumTree!");
}
}
}
Output:
输出:
This is a SumTree!
这是一个 SumTree!
298. What is a Linked list?
什么是链表?
- 知识点: 算法与数据结构 (标签: interviewbit, persistent, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Persistent Systems
- id: 69b37c1858d557c902bb7440 | 官方: 否 | 付费: 否
答案:
Linked lists are linear data structures made up of a series of connected nodes. In Linked lists, each node contains both a data field and the address (reference link) of the next node in the list. You can visualize a linked list as a chain of nodes, each of which points to the next node.
链表是由一系列相互连接的节点组成的线性数据结构。在链表中,每个节点既包含数据字段,又包含链表中下一个节点的地址(引用链接)。你可以将链表想象成一系列节点的链,每个节点都指向下一个节点。
Advantages: - As linked list size increases and decreases at run time, there is no memory wastage and pre-allocating memory is not required.
优点:- 由于链表的大小在运行时增减,因此不会造成内存浪费,也无需预先分配内存。
- It is often possible to implement linear data structures, such as stacks and queues, using linked lists.
- It is quite easy to insert and delete items in a linked list.
Linked lists are dynamic in nature, so they can grow and shrink by allocating and releasing memory at runtime. As such, no initial size for the linked list is required.
Disadvantages: - A linked list traversal takes longer than an array. A linked list does not offer direct access to an element as an array does.缺点:- 链表的遍历比数组耗时更长。链表不像数组那样支持对元素的直接访问。
- Reverse traversal can be done in doubly-linked lists since each node contains a pointer to the previous nodes. As additional memory is required for the back pointer, there is a loss in memory.
- A linked list requires more memory than an array. Since a linked list requires a pointer to store the address of the next element, it consumes extra memory.
- A linked list has a dynamic memory allocation, so random access is not possible.
299. Can you explain the difference between a recursive and an iterative algorithm?
你能解释一下递归算法和迭代算法之间的区别吗?
- 知识点: 算法与数据结构 (标签: interviewbit, publicis-sapient, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Publicis Sapient
- id: 69b37c2058d557c902bb7a44 | 官方: 否 | 付费: 否
答案:
A recursive algorithm is an algorithm that solves a problem by breaking it down into smaller subproblems and then solving each subproblem recursively. A recursive algorithm typically has a base case, which is a simple problem that can be solved without recursion, and a recursive case, which is a problem that is solved by breaking it down into smaller subproblems and solving them recursively.
递归算法是将问题分解为更小的子问题,然后递归地求解每个子问题的算法。递归算法通常有一个基本情况(即无需递归即可解决的简单问题)和一个递归情况(即通过分解为更小的子问题并递归求解来解决问题)。
An iterative algorithm, on the other hand, is an algorithm that solves a problem by repeatedly applying a set of steps until a certain condition is met. Iterative algorithms do not use recursion and instead rely on looping constructs, such as for loops and while loops, to repeatedly execute a set of steps.
另一方面,迭代算法是通过反复应用一组步骤直到满足特定条件来解决问题的算法。迭代算法不使用递归,而是依赖于循环结构(如 for 循环和 while 循环)来反复执行一组步骤。
Here is an example of a recursive function for calculating the factorial of a number:
下面是一个用于计算数字阶乘的递归函数示例:
def factorial(n):
def factorial(n):
if n == 0:
if n == 0:
return 1
return 1
else:
否则:
return n * factorial(n-1)
return n * factorial(n-1)
And here is an example of an iterative function for calculating the factorial of a number:
下面是一个用于计算数字阶乘的迭代函数示例:
def factorial(n):
def factorial(n):
result = 1
result = 1
for i in range(1, n+1):
for i in range(1, n+1):
result *= i
result *= i
return result
return result
Overall, recursive and iterative algorithms are two different approaches to solving problems, and the choice between them will depend on the specific requirements of the task at hand. Understanding the differences between these two types of algorithms can help you choose the right one for a given task.
总的来说,递归和迭代算法是解决问题的两种不同方法,选择哪一种将取决于手头任务的具体要求。理解这两类算法之间的差异有助于你为给定任务选择正确的算法。
Here is a comparison of recursive and iterative algorithms:
以下是递归和迭代算法的比较:
| Property 属性 | Recursive Algorithm 递归算法 | Iterative Algorithm 迭代算法 |
|---|---|---|
| Approach 方法 | Divide and conquer 分而治之 | Repeat a set of steps 重复一组步骤 |
| Data structure 数据结构 | Stack (implicit) 栈(隐式) | Loop variables 循环变量 |
| Time complexity 时间复杂度 | O(branching factor^depth) 复杂度可达分支因子^深度 | O(number of steps) 步骤数级别 |
| Space complexity 空间复杂度 | O(depth) 深度级别 | O(number of variables) 变量数级别 |
| Use case 使用场景 | Complex problem 复杂问题 | Simple problem 简单问题 |
| Example 示例 | Factorial 阶乘 | Fibonacci 斐波那契 |
| - Approach: Recursive algorithms solve a problem by dividing it into smaller subproblems and solving each subproblem recursively, while iterative algorithms solve a problem by repeating a set of steps until a certain condition is met. - 方法:递归算法通过将问题分解为更小的子问题并递归求解每个子问题来解决问题,而迭代算法通过重复一组步骤直到满足某个条件来解决问题。 |
- Data structure: Recursive algorithms use a stack data structure implicitly to store the function calls and variables for each recursive call, while iterative algorithms use loop variables to store the state of the algorithm as it progresses.
- Time complexity: The time complexity of a recursive algorithm is typically expressed in terms of the branching factor (i.e., the number of subproblems generated at each level) and the depth of the recursion (i.e., the number of levels of recursion), while the time complexity of an iterative algorithm is typically expressed in terms of the number of steps required to solve the problem.
- Space complexity: The space complexity of a recursive algorithm is typically O(depth), where depth is the maximum depth of the recursion, while the space complexity of an iterative algorithm is typically O(number of variables), where the number of variables is the number of variables used to store the state of the algorithm.
- Use case: Recursive algorithms are often used for complex problems that can be divided into smaller subproblems, while iterative algorithms are often used for simple problems that can be solved by repeating a set of steps.
Example: The factorial function is a good example of a recursive algorithm, while the Fibonacci function is a good example of an iterative algorithm.
Recursive and iterative algorithms are two different approaches to solving problems, and the choice between them will depend on the specific requirements of the task at hand. Understanding the differences between these two types of algorithms can help you choose the right one for a given task.递归和迭代算法是解决问题的两种不同方法,选择哪一种将取决于手头任务的具体要求。理解这两类算法之间的差异有助于你为给定任务选择正确的算法。
300. Can you explain the difference between a DFS and a BFS algorithm?
你能解释一下DFS和BFS算法的区别吗?
- 知识点: 算法与数据结构 (标签: interviewbit, publicis-sapient, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Publicis Sapient
- id: 69b37c2058d557c902bb7a47 | 官方: 否 | 付费: 否
答案:
Here is a comparison of the depth-first search (DFS) and breadth-first search (BFS) algorithms in tabular form:
以下是以表格形式给出的深度优先搜索(DFS)和广度优先搜索(BFS)算法的比较:
| Property 属性 | DFS | BFS |
|---|---|---|
| Order of exploration 探索顺序 | Depth-first 深度优先 | Breadth-first 广度优先 |
| Data structure 数据结构 | Stack 栈 | Queue 队列 |
| Time complexity 时间复杂度 | O(n+m) | O(n+m) |
| Space complexity 空间复杂度 | O(n) | O(n) |
| Use case 使用场景 | Backtracking 回溯 | Shortest path 最短路径 |
| - Order of exploration: DFS explores nodes by following a path down to the leaf nodes before backtracking and exploring other paths, while BFS explores nodes by visiting all the nodes at a given depth before moving on to the next depth. - 探索顺序:DFS通过沿着一条路径向下探索到叶节点,然后回溯并探索其他路径来探索节点,而BFS通过在进入下一深度之前访问给定深度的所有节点来探索节点。 |
- Data structure: DFS uses a stack data structure to store the nodes it needs to explore, while BFS uses a queue data structure.
- Time complexity: Both DFS and BFS have a time complexity of O(n+m), where n is the number of nodes and m is the number of edges in the graph.
- Space complexity: Both DFS and BFS have a space complexity of O(n), where n is the number of nodes in the graph.
Use case: DFS is often used for backtracking problems, such as finding a path through a maze, while BFS is often used for finding the shortest path between two nodes in a graph.
Overall, DFS and BFS are two different algorithms for traversing a graph, and the choice between them will depend on the specific requirements of the task at hand. Both algorithms have their own strengths and weaknesses, and understanding the differences between them can help you choose the right algorithm for a given task.总的来说,DFS和BFS是遍历图的两种不同算法,选择哪一种将取决于手头任务的具体要求。两种算法各有优缺点,理解它们之间的差异有助于你为给定任务选择正确的算法。
301. Can you explain the difference between a bubble sort and a quick sort?
你能解释一下冒泡排序和快速排序的区别吗?
- 知识点: 算法与数据结构 (标签: interviewbit, publicis-sapient, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Publicis Sapient
- id: 69b37c2058d557c902bb7a4a | 官方: 否 | 付费: 否
答案:
Bubble sort and quicksort are two algorithms for sorting a list of items. Both algorithms have their own strengths and weaknesses, and the choice of which algorithm to use will depend on the specific requirements of the task at hand.
冒泡排序和快速排序是对列表项进行排序的两种算法。这两种算法各有优缺点,选择使用哪种算法将取决于手头任务的具体要求。
Bubble sort is a simple and intuitive sorting algorithm that works by repeatedly iterating through the list and swapping adjacent elements if they are in the wrong order. It has a time complexity of O(n^2), which means that it takes longer to sort larger lists. However, it has a space complexity of O(1), which means that it only requires a constant amount of additional memory to perform the sort.
冒泡排序是一种简单直观的排序算法,它通过反复遍历列表并交换顺序错误的相邻元素来工作。它的时间复杂度为O(n^2),这意味着排序更大的列表需要更长时间。然而,它的空间复杂度为O(1),这意味着执行排序只需要恒定的额外内存量。
Here is an example of how bubble sort might be implemented in Python:
以下是一个用Python实现冒泡排序的示例:
def bubble_sort(lst):
def bubble_sort(lst):
n = len(lst)
n = len(lst)
for i in range(n):
for i in range(n):
for j in range(n - 1 - i):
for j in range(n - 1 - i):
if lst[j] > lst[j + 1]:
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
lst[j], lst[j + 1] = lst[j + 1], lst[j]
Quick sort is a more efficient sorting algorithm that works by partitioning the list into two sublists, sorting the sublists, and then merging the sorted sublists back together. It has a time complexity of O(n log n), which is significantly faster than bubble sort for larger lists. However, it has a space complexity of O(n), which means that it requires more memory to perform the sort.
快速排序是一种更高效的排序算法,它通过将列表分区为两个子列表,对子列表进行排序,然后将排序后的子列表合并在一起。它的时间复杂度为O(n log n),对于较大的列表,这比冒泡排序快得多。然而,它的空间复杂度为O(n),这意味着执行排序需要更多内存。
Here is an example of how quick sort might be implemented in Python:
以下是一个用Python实现快速排序的示例:
def quick_sort(lst):
def quick_sort(lst):
if len(lst) <= 1:
if len(lst) <= 1:
return lst
return lst
pivot = lst[0]
pivot = lst[0]
left = [x for x in lst[1:] if x < pivot]
left = [x for x in lst[1:] if x < pivot]
right = [x for x in lst[1:] if x >= pivot]
right = [x for x in lst[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
返回快速排序(左部分)+ 基准值 + 快速排序(右部分)
Overall, bubble sort is a simple and easy-to-understand sorting algorithm that is suitable for small lists, while quick sort is a more efficient algorithm that is suitable for larger lists. The choice between these two algorithms will depend on the specific requirements of the task at hand.
总体而言,冒泡排序是一种简单易懂的排序算法,适用于小列表;而快速排序是一种更高效的算法,适用于较大的列表。在这两种算法之间的选择将取决于具体任务的要求。
302. How do you implement a hash table in code?
你在代码中如何实现哈希表?
- 知识点: 算法与数据结构 (标签: interviewbit, publicis-sapient, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Publicis Sapient
- id: 69b37c2058d557c902bb7a4d | 官方: 否 | 付费: 否
答案:
A hash table is a data structure that is used to store and retrieve data in an efficient manner. It uses a hash function to map the data elements (keys) to indices in an array (the hash table), allowing for constant-time lookup and insertion of data.
哈希表是一种用于高效存储和检索数据的数据结构。它使用哈希函数将数据元素(键)映射到数组(哈希表)中的索引,从而实现数据的常数时间查找和插入。
The performance of a hash table can be affected by various factors, and while constant-time lookup and insertion are possible, they are not always guaranteed. Collisions can occur when two or more keys map to the same index in the array, and this can lead to longer lookup times and degraded performance.
哈希表的性能可能受到多种因素的影响,虽然常数时间的查找和插入是可能的,但并非总是得到保证。当两个或多个键映射到数组中的同一索引时,就会发生冲突,这可能导致更长的查找时间和性能下降。
To handle collisions, different techniques can be used. Chaining is one common approach where each index in the array is a pointer to a linked list of key-value pairs. When a collision occurs, the new key-value pair is added to the linked list at that index. Open addressing is another approach where if a collision occurs, the algorithm probes other indices in the array until it finds an empty slot.
为了处理冲突,可以使用不同的技术。链地址法是一种常见的方法,数组中的每个索引是指向键值对链表的指针。当发生冲突时,新的键值对会被添加到该索引处的链表中。开放寻址法是另一种方法,如果发生冲突,算法会探测数组中的其他索引,直到找到一个空槽位。
The quality of the hash function can also affect the performance of a hash table. A good hash function should evenly distribute the keys across the array to minimize collisions.
哈希函数的质量也会影响哈希表的性能。一个好的哈希函数应该将键均匀分布到数组中,以尽量减少冲突。
Finally, the size of the array is also important. If the array is too small relative to the number of keys, collisions can occur frequently, reducing performance. On the other hand, if the array is too large, it can waste memory and increase the time needed to initialize the hash table. Therefore, selecting an appropriate size for the array is important for good performance.
最后,数组的大小也很重要。如果相对于键的数量来说数组太小,冲突可能会频繁发生,从而降低性能。另一方面,如果数组太大,可能会浪费内存并增加初始化哈希表所需的时间。因此,选择合适的数组大小对于良好性能至关重要。
Here is an example of how you might implement a hash table in Python:
下面是一个用Python实现哈希表的示例:
class HashTable:
类哈希表:
def __init__(self, size):
定义初始化方法(自身,大小):
self.size = size
自身大小 = 大小
self.table = [None] * self.size
自身表 = [无] * 自身大小
def hash(self, key):
定义哈希方法(自身,键):
return sum(ord(c) for c in key) % self.size
返回键中各字符的Unicode码点之和对自身大小取模
def add(self, key, value):
定义添加方法(自身,键,值):
index = self.hash(key)
index = self.hash(key)
if self.table[index] is None:
if self.table[index] is None:
self.table[index] = []
self.table[index] = []
self.table[index].append((key, value))
self.table[index].append((key, value))
def get(self, key):
def get(self, key):
index = self.hash(key)
index = self.hash(key)
if self.table[index] is None:
if self.table[index] is None:
return None
return None
for k, v in self.table[index]:
for k, v in self.table[index]:
if k == key:
if k == key:
return v
return v
return None
return None
def delete(self, key):
def delete(self, key):
index = self.hash(key)
index = self.hash(key)
if self.table[index] is None:
if self.table[index] is None:
return
return
for i, (k, v) in enumerate(self.table[index]):
for i, (k, v) in enumerate(self.table[index]):
if k == key:
if k == key:
self.table[index].pop(i)
self.table[index].pop(i)
return
return
The HashTable class represents the hash table itself and contains an array of size to store the data, as well as a hash method to compute the index for a given key based on its hash value. The add, get, and delete methods are used to insert, retrieve, and remove data from the hash table, respectively.
HashTable 类表示哈希表本身,包含一个大小为 size 的数组来存储数据,以及一个哈希方法,用于根据键的哈希值计算给定键的索引。add、get 和 delete 方法分别用于向哈希表中插入、检索和删除数据。
“Size” in this context refers to the size of the array used to store data in the hash table. When a hash table is created, the size of the array is specified, and this size remains fixed for the lifetime of the hash table. The size is typically chosen based on factors such as the expected number of keys to be stored and the desired performance characteristics.
在这个上下文中,“Size”指的是哈希表中用于存储数据的数组的大小。创建哈希表时,会指定数组的大小,并且该大小在哈希表的整个生命周期内保持不变。大小通常根据预期的存储键数量以及期望的性能特征等因素来选择。
The hash method uses a simple hash function to map the key to an index in the array. In this example, the hash function is the sum of the ASCII values of the characters in the key modulo the size of the array. This is just one example of a hash function, and there are many other ways to design hash functions depending on the specific requirements of the task at hand.
哈希方法使用一个简单的哈希函数将键映射到数组中的索引。在本例中,哈希函数是键中字符的 ASCII 值之和取模数组大小。这只是哈希函数的一个示例,根据具体任务的要求,还有许多其他设计哈希函数的方法。
The add method computes the index for the given key using the hash method and then checks if there is an entry at that index in the table. If there is no entry, it creates a new one as an empty list. It then appends the key-value pair to the entry.
add 方法使用哈希方法计算给定键的索引,然后检查表中的该索引处是否有条目。如果没有条目,它会创建一个新的空列表作为条目。然后它将键值对追加到该条目中。
The get method retrieves the value associated with a given key by computing the index for the key and then searching the entry at that index for the key. If the key is found, it returns the associated value; if it is not found, it returns None.
get 方法通过计算键的索引,然后在该索引的条目中搜索该键,来检索与给定键关联的值。如果找到该键,则返回关联的值;如果未找到,则返回 None。
The delete method removes a key-value pair from the hash table by computing the index for the key and then searching the entry at that index for the key. If the key is found, it removes the key-value pair from the entry.
delete 方法通过计算键的索引,然后在该索引的条目中搜索该键,来从哈希表中移除键值对。如果找到该键,则从条目中移除该键值对。
By implementing these methods, you can create a fully functional hash table in Python that can be used to store and retrieve data efficiently.
通过实现这些方法,你可以在 Python 中创建一个功能完整的哈希表,用于高效地存储和检索数据。
303. How do you implement a binary search tree in code?
如何在代码中实现二叉搜索树?
- 知识点: 算法与数据结构 (标签: interviewbit, publicis-sapient, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Publicis Sapient
- id: 69b37c2058d557c902bb7a53 | 官方: 否 | 付费: 否
答案:
A binary search tree (BST) is a tree-based data structure that is used to store and retrieve data in an ordered manner. In a BST, each node has at most two children, and the value of a node's left child is always less than its value, while the value of a node's right child is always greater. This allows for efficient search, insertion, and deletion operations, as the tree is always balanced and the time complexity is logarithmic in the number of nodes.
二叉搜索树(BST)是一种基于树的数据结构,用于以有序的方式存储和检索数据。在 BST 中,每个节点最多有两个子节点,并且节点的左子节点的值总是小于其值,而节点的右子节点的值总是大于其值。这允许高效的搜索、插入和删除操作,因为树总是保持平衡,并且时间复杂度相对于节点数量是呈对数级的。
Here is an example of how you might implement a BST in Python:
以下是一个如何在 Python 中实现 BST 的示例:
class Node:
class Node:
def __init__(self, data):
def __init__(self, data):
self.data = data
self.data = data
self.left = None
self.left = None
self.right = None
self.right = None
class BST:
class BST:
def __init__(self):
def __init__(self):
self.root = None
self.root = None
The Node class represents a single node in the BST, and contains a data element and references to its left and right children. The BST class represents the BST itself, and contains a reference to the root node.
Node 类表示二叉搜索树中的一个节点,包含一个数据元素以及指向其左、右子节点的引用。BST 类表示二叉搜索树本身,包含一个指向根节点的引用。
To insert a new node into the BST, you can use the insert method:
要向二叉搜索树中插入一个新节点,可以使用 insert 方法:
def insert(self, data):
def insert(self, data):
new_node = Node(data)
new_node = Node(data)
if self.root is None:
if self.root is None:
self.root = new_node
self.root = new_node
return
return
current_node = self.root
current_node = self.root
while True:
while True:
if data < current_node.data:
如果数据小于当前节点的数据:
if current_node.left is None:
如果当前节点的左子节点为空:
current_node.left = new_node
将新节点设置为当前节点的左子节点
return
return
current_node = current_node.left
current_node = current_node.left
else:
否则:
if current_node.right is None:
如果当前节点的右子节点为空:
current_node.right = new_node
将新节点设置为当前节点的右子节点
return
return
current_node = current_node.right
当前节点 = 当前节点的右子节点
This method creates a new Node object with the given data and inserts it into the BST by traversing the tree and finding the appropriate position based on the node's value. If the value is less than the current node's value, it goes to the left child; if it is greater, it goes to the right child. If a leaf node is reached, the new node is added as a child of that node.
此方法创建一个给定数据的新节点对象,并通过遍历树、根据节点值找到合适的位置将其插入到二叉树搜索树中。如果值小于当前节点的值,则插入到左子节点;如果大于,则插入到右子节点。如果到达叶子节点,则将新节点添加为该节点的子节点。
To search for a node with a given value in the BST, you can use the search method:
要在二叉树搜索树中搜索给定值的节点,可以使用 search 方法:
def search(self, data):
def search(self, data):
current_node = self.root
current_node = self.root
while current_node and current_node.data != data:
while current_node and current_node.data != data:
if data < current_node.data:
如果数据小于当前节点的数据:
current_node = current_node.left
current_node = current_node.left
else:
否则:
current_node = current_node.right
当前节点 = 当前节点的右子节点
return current_node
返回当前节点
To continue the example of implementing a BST in Python, here are some additional methods that you might want to consider: - delete: This method removes a node with the given value from the BST.
继续以在 Python 中实现二叉搜索树为例,这里有一些你可能需要考虑的额外方法:- 删除:此方法从二叉搜索树中移除具有给定值的节点。
- preorder_traversal: This method performs a preorder traversal of the BST and returns a list of the data elements in the visited nodes.
- inorder_traversal: This method performs an inorder traversal of the BST and returns a list of the data elements in the visited nodes.
postorder_traversal: This method performs a postorder traversal of the BST and returns a list of the data elements in the visited nodes.
Here is how these additional methods might be implemented:下面是这些额外方法可能如何实现:
def delete(self, data):
def delete(self, data):
def delete_node(node, data):
def delete_node(node, data):
if node is None:
如果节点为空:
return node
return node
if data < node.data:
如果数据小于节点数据:
node.left = delete_node(node.left, data)
节点左子节点 = delete_node(节点左子节点, 数据)
elif data > node.data:
否则如果数据大于节点数据:
node.right = delete_node(node.right, data)
节点右子节点 = delete_node(节点右子节点, 数据)
else:
否则:
if node.left is None:
如果节点左子节点为空:
return node.right
返回节点右子节点
elif node.right is None:
elif node.right is None:
return node.left
return node.left
node.data = min_value(node.right)
node.data = min_value(node.right)
node.right = delete_node(node.right, node.data)
node.right = delete_node(node.right, node.data)
return node
return node
def min_value(node):
def min_value(node):
current_node = node
current_node = node
while current_node.left:
while current_node.left:
current_node = current_node.left
current_node = current_node.left
return current_node.data
return current_node.data
self.root = delete_node(self.root, data)
self.root = delete_node(self.root, data)
def preorder_traversal(self, node, result):
def preorder_traversal(self, node, result):
if node:
如果节点存在:
result.append(node.data)
将节点数据添加到结果列表
self.preorder_traversal(node.left, result)
self.preorder_traversal(node.left, result)
self.preorder_traversal(node.right, result)
self.preorder_traversal(node.right, result)
return result
return result
def inorder_traversal(self, node, result):
定义中序遍历方法(self, node, result)
if node:
如果节点存在:
self.inorder_traversal(node.left, result)
递归调用中序遍历(节点的左子节点,结果列表)
result.append(node.data)
将节点数据添加到结果列表
self.inorder_traversal(node.right, result)
递归调用中序遍历(节点的右子节点,结果列表)
return result
return result
def postorder_traversal(self, node, result):
定义后序遍历方法(self, node, result)
if node:
如果节点存在:
self.postorder_traversal(node.left, result)
递归调用后序遍历(节点的左子节点,结果列表)
self.postorder_traversal(node.right, result)
递归调用后序遍历(节点的右子节点,结果列表)
result.append(node.data)
将节点数据添加到结果列表
return result
return result
The delete method uses a recursive helper function delete_node to find and remove the node with the given value from the BST. If the node is found, it is replaced with either its left or right child, or with the smallest value in its right subtree (if it has two children).
删除方法使用递归辅助函数delete_node来查找并移除二叉搜索树中具有给定值的节点。如果找到该节点,则用其左子节点或右子节点替换它,或者用其右子树中的最小值替换它(如果它有两个子节点)。
There are other options for replacing a deleted node in a binary search tree. For example, you could replace it with the largest value in its left subtree instead of the smallest value in its right subtree. This would require a different recursive helper function that traverses down the left subtree instead of the right subtree to find the largest value.
在二叉搜索树中替换被删除节点还有其他选项。例如,您可以改用其左子树中的最大值而不是右子树中的最小值来替换它。这需要不同的递归辅助函数,该函数遍历左子树而不是右子树来找到最大值。
Deleting a node with two children can also be more complex than deleting a node with one child. One approach is to promote the successor node to take the deleted node’s place, as you mentioned. The successor node is the node with the smallest value in the deleted node’s right subtree. If the successor node has a right child, that child becomes the new left child of the successor node’s parent. This process may need to be repeated recursively until a node is deleted that has at most one child.
删除具有两个子节点的节点可能比删除只有一个子节点的节点更复杂。一种方法是将后继节点提升到被删除节点的位置,如您所提到的。后继节点是被删除节点右子树中具有最小值的节点。如果后继节点有右子节点,则该右子节点将成为后继节点父节点的新的左子节点。此过程可能需要递归重复,直到删除的节点最多只有一个子节点。
Alternatively, you could choose to promote the predecessor node instead of the successor node. The predecessor node is the node with the largest value in the deleted node’s left subtree. This approach would involve traversing down the left subtree to find the predecessor node instead of the right subtree to find the successor node.
或者,你也可以选择提升前驱节点而不是后继节点。前驱节点是被删除节点左子树中值最大的节点。这种方法需要向下遍历左子树来找到前驱节点,而不是遍历右子树来找到后继节点。
Overall, the specific implementation of a binary search tree depends on the particular use case and requirements. The basic operations of inserting, searching, and deleting nodes can be implemented in different ways depending on the desired behavior and performance characteristics.
总体而言,二叉搜索树的具体实现取决于特定的用例和需求。插入、搜索和删除节点的基本操作可以根据期望的行为和性能特征以不同的方式实现。
The preorder_traversal, inorder_traversal, and postorder_traversal methods are also recursive, and perform a depth-first traversal of the BST, visiting the nodes in a specific order: preorder traversal visits the root node first, then the left child, then the right child; inorder traversal visits the left child, then the root node, then the right child; and postorder traversal visits the left child, then the right child, then the root node.
preorder_traversal、inorder_traversal 和 postorder_traversal 方法也是递归的,它们对 BST 执行深度优先遍历,按特定顺序访问节点:前序遍历先访问根节点,然后是左子节点,最后是右子节点;中序遍历先访问左子节点,然后是根节点,最后是右子节点;后序遍历先访问左子节点,然后是右子节点,最后是根节点。
By implementing these methods, you can create a fully functional BST in Python that can be used to store and retrieve data efficiently.
通过实现这些方法,你可以在 Python 中创建一个功能完整的 BST,用于高效地存储和检索数据。
304. How do you implement a linked list in code?
如何在代码中实现链表?
- 知识点: 算法与数据结构 (标签: interviewbit, publicis-sapient, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Publicis Sapient
- id: 69b37c2058d557c902bb7a56 | 官方: 否 | 付费: 否
答案:
A linked list is a linear data structure that consists of a sequence of nodes, where each node contains a data element and a reference (link) to the next node in the sequence. Linked lists are often used to implement lists, stacks, and queues, as they can be easily inserted or removed in constant time.
链表是一种线性数据结构,由一系列节点组成,每个节点包含一个数据元素和一个指向序列中下一个节点的引用(链接)。链表常用于实现列表、栈和队列,因为它们可以在常数时间内轻松插入或移除元素。
Here is an example of how you might implement a linked list in Python:
以下是如何在 Python 中实现链表的一个示例:
class Node:
class Node:
def __init__(self, data):
def __init__(self, data):
self.data = data
self.data = data
self.next = None
self.next = None
class LinkedList:
class LinkedList:
def __init__(self):
def __init__(self):
self.head = None
self.head = None
The Node class represents a single node in the linked list and contains a data element and a reference to the next node in the sequence. The LinkedList class represents the linked list itself and contains a reference to the head of the list (the first node).
Node 类表示链表中的单个节点,包含一个数据元素和一个指向序列中下一个节点的引用。LinkedList 类表示链表本身,包含对列表头部(第一个节点)的引用。
To add a new node to the linked list, you can use the append method:
要向链表添加新节点,可以使用 append 方法:
def append(self, data):
def append(self, data):
new_node = Node(data)
new_node = Node(data)
if self.head is None:
if self.head is None:
self.head = new_node
self.head = new_node
return
return
current_node = self.head
current_node = self.head
while current_node.next:
while current_node.next:
current_node = current_node.next
current_node = current_node.next
current_node.next = new_node
current_node.next = new_node
This method creates a new Node object with the given data and appends it to the end of the linked list by updating the next reference of the last node in the list.
此方法使用给定数据创建一个新的Node对象,并通过更新列表中最后一个节点的next引用来将其追加到链表的末尾。
To remove a node from the linked list, you can use the delete method:
要从链表中删除节点,可以使用delete方法:
def delete(self, data):
def delete(self, data):
current_node = self.head
current_node = self.head
if current_node.data == data:
if current_node.data == data:
self.head = current_node.next
self.head = current_node.next
return
return
prev_node = None
prev_node = None
while current_node.data != data:
当 current_node.data 不等于 data 时循环:
prev_node = current_node
prev_node = current_node
current_node = current_node.next
current_node = current_node.next
prev_node.next = current_node.next
prev_node.next = current_node.next
Overall, implementing a linked list involves creating classes for the nodes and the list itself, and defining methods for inserting and deleting nodes.
总体而言,实现链表涉及为节点和链表本身创建类,并定义插入和删除节点的方法。
305. Can you explain the difference between a stack and a queue?
你能解释一下栈和队列之间的区别吗?
- 知识点: 算法与数据结构 (标签: interviewbit, publicis-sapient, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Publicis Sapient
- id: 69b37c2058d557c902bb7a59 | 官方: 否 | 付费: 否
答案:
A stack is a linear data structure that follows the principle of last-in first-out (LIFO), meaning that the last element added to the stack will be the first one to be removed. This is similar to a stack of plates, where the plate added last will be the one removed first.
栈是一种线性数据结构,遵循后进先出(LIFO)原则,这意味着最后添加到栈中的元素将最先被移除。这类似于一叠盘子,最后放的盘子会最先被拿走。
A queue is a linear data structure that follows the first-in first-out (FIFO) principle, meaning that the first element added to the queue will be the first one to be removed. This is similar to a queue at a ticket counter, where the person who arrived first will be the first one to be served.
队列是一种线性数据结构,遵循先进先出(FIFO)原则,这意味着第一个添加到队列中的元素将最先被移除。这类似于售票处的排队,先到的人会先被服务。
In terms of implementation, a stack is typically implemented using an array or a linked list, while a queue is typically implemented using an array, a linked list, or a circular buffer.
在实现方面,栈通常使用数组或链表实现,而队列通常使用数组、链表或环形缓冲区实现。
Some key differences between stacks and queues include: - Access pattern: Stacks follow a LIFO pattern, while queues follow a FIFO pattern.
栈和队列之间的一些关键区别包括:- 访问模式:栈遵循 LIFO 模式,而队列遵循 FIFO 模式。
- Insertion and deletion: In a stack, elements can only be added or removed from the top, while in a queue, elements can only be added at the end and removed from the front.
Use cases: Stacks are often used to implement undo/redo functionality, while queues are often used to store tasks to be processed in order.
Overall, the choice between using a stack or a queue will depend on the specific requirements of the task at hand.总体而言,选择使用栈还是队列将取决于手头任务的具体要求。
Publicis Sapient Interview Preparation
306. Check if a string is a palindrome or not?
检查一个字符串是否是回文?
- 知识点: 算法与数据结构 (标签: interviewbit, pwc, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 普华永道
- id: 69b37c2258d557c902bb7b31 | 官方: 否 | 付费: 否
答案:
Palindrome: A string is called a palindrome if it can be read the same way starting from the front (or) starting from the back. In other words, a string is a palindrome if the reverse of the string is equal to the original string.
回文:如果一个字符串从前面读和从后面读的结果相同,则该字符串称为回文。换句话说,如果字符串的反转等于原始字符串,则该字符串是回文。
Naive Implementation:
朴素实现:
include
include
include
using namespace std;
using namespace std;
// To reverse a string
// 反转一个字符串
string reverseString(string str)
string reverseString(string str)
{
int len = str.length();
int len = str.length();
int mid = len / 2;
int mid = len / 2;
// Traverse until mid and swap characters from ends
// 遍历到中间位置,并交换两端的字符
for (int i = 0; i < mid; i++)
for (int i = 0; i < mid; i++)
swap(str[i], str[len - i - 1]);
swap(str[i], str[len - i - 1]);
return str;
return str;
}
bool isPalindrome(string a)
bool isPalindrome(string a)
{
// This reverse the string
// 这是反转字符串
string b = reverseString(a);
string b = reverseString(a);
// Check if reversed string and original string are same
// 检查反转后的字符串与原始字符串是否相同
return a == b;
return a == b;
}
int main()
int main()
{
string s1 = "BANANA";
字符串 s1 = "BANANA";
string s2 = "MADAM";
字符串 s2 = "MADAM";
cout<<s1<<" is "<< (isPalindrome(s1) ? "NOT ": "") <<" a PALINDROME\n";
cout<<s1<<" 是 "<< (isPalindrome(s1) ? "不是 ": "") <<" 回文\n";
cout<<s2<<" is "<< (isPalindrome(s2) ? "NOT ": "") <<" a PALINDROME\n";
cout<<s2<<" 是 "<< (isPalindrome(s2) ? "不是 ": "") <<" 回文\n";
}
Output:
输出:
BANANA is NOT a PALINDROME
BANANA 不是 回文
MADAM is a PALINDROME
MADAM 是 回文
This approach has a Time Complexity of O(N) and also Space Complexity of O(N).
这种方法的时间复杂度为 O(N),空间复杂度也为 O(N)。
A better version to solve this is to not create the actual copy but use 2 pointers one from start and another from the end to check if these 2 pointers point to the same characters and move them until the midpoint of the string.
解决此问题的一个更好版本是不创建实际的副本,而是使用两个指针,一个从开头开始,另一个从末尾开始,检查这两个指针是否指向相同的字符,并将它们移动到字符串的中点。
include
include
include
using namespace std;
using namespace std;
bool isPalindrome(string a)
bool isPalindrome(string a)
{
int len = a.length();
int len = a.length();
int start = 0;
int start = 0;
int end = len-1;
int end = len-1;
while(start < end)
while(start < end)
{
// if not same then return false
// if not same then return false
if(a[start] != a[end])
if(a[start] != a[end])
{
return false;
返回 false;
}
// update the start and end
// 更新起始位置和结束位置
start++;
start++;
end--;
end--;
}
// If it had reached upto this, then all characters are equal until mid
// 如果能够执行到这里,则说明所有字符直到中间位置都是相等的
return true;
返回 true;
}
int main()
int main()
{
string s1 = "BANANA";
字符串 s1 = "BANANA";
string s2 = "MADAM";
字符串 s2 = "MADAM";
cout<<s1<<" is "<< (isPalindrome(s1) ? "NOT ": "") <<" a PALINDROME\n";
cout<<s1<<" 是 "<< (isPalindrome(s1) ? "不是 ": "") <<" 回文\n";
cout<<s2<<" is "<< (isPalindrome(s2) ? "NOT ": "") <<" a PALINDROME\n";
cout<<s2<<" 是 "<< (isPalindrome(s2) ? "不是 ": "") <<" 回文\n";
}
Output:
输出:
BANANA is NOT a PALINDROME
BANANA 不是 回文
MADAM is a PALINDROME
MADAM 是 回文
This approach has a Time Complexity of O(N). Space Complexity is O(1) as we are not making a copy of the string here.
此方法的时间复杂度为 O(N)。空间复杂度为 O(1),因为我们没有复制该字符串。
307. What is merge sort? What is the Time & Space Complexity for merge sort?
什么是归并排序?归并排序的时间与空间复杂度是多少?
- 知识点: 算法与数据结构 (标签: interviewbit, pwc, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 普华永道
- id: 69b37c2258d557c902bb7b40 | 官方: 否 | 付费: 否
答案:
Merge Sort is a Divide & Conquer algorithm that is used to sort a given input (can be an array or linked list). It involved dividing the input into 2 halves at each step until input has only 1 element and then merging these sorted halves to finally get a sorted input.
归并排序是一种分治算法,用于对给定的输入(可以是数组或链表)进行排序。它涉及在每一步将输入分成两半,直到输入只剩 1 个元素,然后合并这些已排序的一半,最终得到一个排序好的输入。
Merge sort is not an in-place algorithm (which means you need to use extra space for sorting the input). Merge sort is a stable algorithm which means if there are 2 same elements in the input, the sorted output will maintain the relative ordering of these elements. - Time Complexity: O(NLogN) even in the worst case. (where N is the size of the input)
归并排序不是一种原地算法(这意味着对输入进行排序时你需要使用额外的空间)。归并排序是一种稳定的算法,这意味着如果输入中有两个相同元素,排序后的输出将保持这些元素的相对顺序。- 时间复杂度:即使在最坏情况下也是 O(NLogN)。(其中 N 是输入的大小)
- Space Complexity: O(N)
308. Difference between linear and non-linear data structures?
线性数据结构和非线性数据结构之间有什么区别?
- 知识点: 算法与数据结构 (标签: interviewbit, pwc, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 普华永道
- id: 69b37c2258d557c902bb7b46 | 官方: 否 | 付费: 否
答案:
Data Structures are divided into 2 types based on the shape/ based on the arrangement of the data elements. They are Linear Data Structures and Non-Linear Data Structures.
根据数据元素的形状/排列方式,数据结构分为两种类型。它们是线性数据结构和非线性数据结构。
| Linear Data Structure 线性数据结构 | Non-Linear Data Structure 非线性数据结构 |
|---|---|
| Data elements are arranged in a sequential/ linear fashion. 数据元素按顺序/线性方式排列。 | Data elements are arranged in a hierarchical/ non-linear fashion. 数据元素按层次/非线性方式排列。 |
| We can traverse all elements without storing visited elements in a single traversal. 我们可以在单次遍历中遍历所有元素而无需存储已访问元素。 | We cannot traverse all elements without storing visited elements in a single traversal. 我们无法在单次遍历中遍历所有元素而无需存储已访问元素。 |
| Only the next element and/or previous element is connected to current the element. 只有下一个元素和/或上一个元素与当前元素相连。 | Any number of elements can be connected to a single node. 任意数量的元素可以连接到单个节点。 |
| Easier implementation than Non-Linear Data Structures. 比非线性数据结构更容易实现。 | Implementation is more complex than Linear Data Structures 实现比线性数据结构更复杂。 |
| Only a single level is involved. 只涉及一个层级。 | Multiple levels are involved. 涉及多个层级。 |
| Examples: Array, Linked List, Stack, Queue etc. 示例:数组、链表、栈、队列等。 | Examples: Trees, Graphs, Trie etc. 示例:树、图、Trie 等。 |
309. What is the difference between Binary Tree and Binary Search Tree?
二叉树和二叉搜索树之间有什么区别?
- 知识点: 算法与数据结构 (标签: interviewbit, pwc, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 普华永道
- id: 69b37c2258d557c902bb7b4e | 官方: 否 | 付费: 否
答案:
- Binary Tree: A Binary Tree is a tree in which each node can have at most 2 children. The children are named left child and right child. There is no constraint on the value the node or its children can have. We need to traverse the whole tree for searching in the case of a binary tree.
- Binary Search Tree: Binary Search Tree (BST) is a Binary Tree but with an additional constraint that the left subtree of a node can only have nodes whose values are less than the parent node's value & the right subtree of a node can only have nodes whose values are greater than parent node's value. We need to traverse only the height of a tree (in the worst-case scenario) for searching in the case of a Binary Search Tree.
PwC Interview Preparation
310. Find the length of the longest substring without repeated characters given a string s.
给定一个字符串 s,找出不含重复字符的最长子串的长度。
- 知识点: 算法与数据结构 (标签: interviewbit, qualcomm, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 高通
- id: 69b37c2d58d557c902bb813b | 官方: 否 | 付费: 否
答案:
Example 1: - Input: s = "abcabcbb"Output: 3Explanation: The answer is "abc", with a length of 3.
示例 1:- 输入:s = "abcabcbb"输出:3解释:答案是 "abc",其长度为 3。
Example 2: - Input: s = "bbbbb"
示例 2:- 输入:s = "bbbbb"
- Output: 1
Explanation: The answer is "b", with a length of 1.
Example 3: - Input: s = "pwwkew"示例 3:- 输入:s = "pwwkew"
- Output: 3
Explanation: The answer is "wke", with a length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.请注意,答案必须是子串,"pwke" 是一个子序列而不是子串。
The issue in this question is determining where to choose our next substring after identifying a duplicate character. We can simply select whatever substring we wish to examine by using two pointers and a sliding window. In fact, if you realise the following point, finding the longest substring without repeated characters becomes considerably easier.
本题的难点在于识别出重复字符后如何确定下一个子串的选择位置。我们可以使用两个指针和一个滑动窗口来简单地选择任何想要检查的子串。事实上,如果你意识到以下这点,找出不含重复字符的最长子串会变得相当容易。
Key Observation: Once we've located a previously encountered character, we want to change the left pointer of our window to the index following the last occurrence of that character.
关键观察:一旦我们找到了之前遇到过的字符,我们希望将窗口的左指针移动到该字符上一次出现位置之后的索引处。
To show this in action, consider the following example using the input string s = "babcadba":
为了展示这一点,考虑以下使用输入字符串 s = "babcadba" 的示例:
class Solution {
class Solution {
public:
public:
int lengthOfLongestSubstring(string s) {
int lengthOfLongestSubstring(string s) {
if (s == "")
如果(s == "")
return 0;
return 0;
//Vector vec1, stores the frequency of characters appearing on the string
//Vector vec1,存储字符串中出现的字符频率
vectorvec1(128,0);
向量vec1(128,0);
int end = 0, max = INT_MIN, len= s.size(), start= 0;
整数 end = 0, max = INT_MIN, len= s.size(), start= 0;
while (end < len) {
当 (end < len) {
//As we go from left to the right on the string, we fill the frequency vector.
//当我们从左到右遍历字符串时,填充频率向量。
// s[end]: if the character at s[end] was a, then it would fill the vec1 at the
// s[end]: 如果 s[end] 处的字符是 a,那么它会在
// index 96, it will increase the frequeny.
// 索引 96 处填充 vec1,它会增加频率。
vec1[s[end]]++;
vec1[s[end]]++;
//When traversing when the number at any index of the vector is greater than one means
//遍历时,当向量任意索引处的数值大于1,意味着
// that there is a duplicate.
// 存在重复。
// Next question: find if a string contains duplicate, can also do it this way
// 下一个问题:判断字符串是否包含重复,也可以这样做
if (vec1[s[end]] > 1) {
如果 (vec1[s[end]] > 1) {
//So we start traversing our start pointer till the point there was duplicate.
//所以我们开始遍历我们的 start 指针,直到出现重复的位置。
//Example: abcadefgh
//示例:abcadefgh
// will do duplicate at s[3], at this point we will bring start here,
// 会在s[3]处产生重复,此时我们会把起始位置移到这里,
// so next time when we calculate the maximum length we will do, end of string -
// 所以下次计算最大长度时,我们会用字符串末尾 -
//this start
// 这个起始位置
while (vec1[s[end]] > 1) {
while (vec1[s[end]] > 1) {
vec1[s[start]]--;
vec1[s[start]]--;
start++;
start++;
}
}
if (end-start > max) {
if (end-start > max) {
max = end-start;
max = end-start;
}
end++;
end++;
}
return max+1;
return max+1;
}
};
311. Get the longest palindromic substring contained in s from a given string s.
从给定字符串s中获取包含在s中的最长回文子串。
- 知识点: 算法与数据结构 (标签: interviewbit, qualcomm, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 高通
- id: 69b37c2d58d557c902bb813e | 官方: 否 | 付费: 否
答案:
Example 1: - Input: s = "babad"
示例1:- 输入:s = "babad"
- Output: "bab"
Explanation: "aba" is also a valid answer.
Example 2: - Input: s = "cbbd"示例2:- 输入:s = "cbbd"
Output: "bb"
General concept: compare the prior best result with the present one, loop through each letter, and determine whether its siblings are equivalent. For further information, look at the code's comments.总体思路:将先前的最佳结果与当前结果进行比较,遍历每个字母,并判断其两侧字符是否相等。更多信息请参阅代码中的注释。
var longestPalindrome = function(s) {
var longestPalindrome = function(s) {
// simple case
// 简单情况
if (s.length <= 1) {
if (s.length <= 1) {
return s
return s
}
// to store the best result
// 用于存储最佳结果
let longest = ''
let longest = ''
// for each item, unless we are at the point, when the longest can't be any better (this is why - longest.length / 2, and divided by two becase we check siblings on both sides)
// 对于每个元素,除非我们达到最长的结果无法再优化的点(这就是为什么要减去 longest.length / 2,并且除以2是因为我们同时检查两侧的相邻元素)
for (let i = 0; i < s.length - longest.length / 2; i++) {
for (let i = 0; i < s.length - longest.length / 2; i++) {
let soFar = s[i]
let soFar = s[i]
// here we handle the case when there are few same symbols in a row
// 这里处理连续出现几个相同符号的情况
while (s[i] === s[i + soFar.length]) {
while (s[i] === s[i + soFar.length]) {
soFar += s[i + soFar.length]
soFar += s[i + soFar.length]
}
let counter = 1
let counter = 1
// if there were few symbols in a row, we want to know the offset
// 如果一行中有几个相同的符号,我们需要知道偏移量
let duplicateOffest = soFar.length - 1
let duplicateOffest = soFar.length - 1
while (typeof s[i - counter] !== 'undefined' && s[i - counter] === s[i + duplicateOffest + counter]) {
while (typeof s[i - counter] !== 'undefined' && s[i - counter] === s[i + duplicateOffest + counter]) {
soFar = s[i - counter] + soFar + s[i + duplicateOffest + counter]
soFar = s[i - counter] + soFar + s[i + duplicateOffest + counter]
counter++
counter++
}
// update the best
// 更新最佳结果
if (soFar.length > longest.length) {
if (soFar.length > longest.length) {
longest = soFar
longest = soFar
}
// if there were few symbols in a row, we don't want to check these sybmols, as we have already done that
// 如果连续出现几个符号,我们不需要检查这些符号,因为我们已经做过检查了
i += duplicateOffest
i += duplicateOffest
}
return longest
return longest
};
- Data Science
- All Events
- My Events
312. Return the number of structurally unique binary search trees (BSTs) that have exactly n nodes and unique values ranging from 1 to n, given an integer n.
给定一个整数 n,返回恰好有 n 个节点且值在 1 到 n 之间的唯一值的结构不同的二叉搜索树(BST)的数量。
- 知识点: 算法与数据结构 (标签: interviewbit, qualcomm, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 高通
- id: 69b37c2d58d557c902bb814d | 官方: 否 | 付费: 否
答案:
Example 1:
示例1:
- Input: n = 3
- Output: 5
Example 2:
示例2:
- Input: n = 1
- Output: 1
The aim is to utilise each integer I as a root node, followed by left and right branches that represent what is smaller and greater than I respectively. Their output is the total number of distinctive structures. Add up the product for each number as a result. To remember the visited number, use a map.
目标是利用每个整数 I 作为根节点,然后用左右子树分别表示小于和大于 I 的值。输出是不同结构的总数。将每个数字作为根节点的乘积相加。使用映射来记住已访问过的数字。
public class Solution {
public class Solution {
public int numTrees(int n) {
public int numTrees(int n) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(0,1);
map.put(0,1);
map.put(1,1);
map.put(1,1);
return numTrees(n, map);
return numTrees(n, map);
}
private int numTrees(int n, Map<Integer, Integer> map){
private int numTrees(int n, Map<Integer, Integer> map){
// check memory
// 检查记忆
if(map.containsKey(n)) return map.get(n);
if(map.containsKey(n)) return map.get(n);
// recursion
// 递归
int sum = 0;
int sum = 0;
for(int i = 1;i <= n;i++)
for(int i = 1;i <= n;i++)
sum += numTrees(i-1, map) * numTrees(n-i, map);
sum += numTrees(i-1, map) * numTrees(n-i, map);
map.put(n, sum);
map.put(n, sum);
return sum;
return sum;
}
}
313. Reverse the nodes of the list from position left to position right, and then return the reversal list, given the head of a singly linked list and two numbers left and right, where left = right.
给定单链表的头节点和两个数 left 和 right,其中 left <= right,反转从位置 left 到位置 right 的链表节点,并返回反转后的链表。
- 知识点: 算法与数据结构 (标签: interviewbit, qualcomm, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 高通
- id: 69b37c2d58d557c902bb8161 | 官方: 否 | 付费: 否
答案:
Example 1:
示例1:
- Input: head = [1,2,3,4,5], left = 2, right = 4
- Output: [1,4,3,2,5]
Example 2:
示例2:
- Input: head = [5], left = 1, right = 1
- Output: [5]
Although it is not required, the dummy node makes the scenario when m == 1 easier to understand. Without the dummy node, we would have to reverse the list from an offset, connect the node at the offset to the head of the reversed list, and then return the original head of the list when m == 1. In the absence of the dummy node, we would have to reverse the list from the beginning like the typical reversal algorithm and return the final value of prev. These two situations converge to the latter with the fake node.
虽然这不是必需的,但哑节点使得 m == 1 的情况更容易理解。如果没有哑节点,当 m == 1 时,我们必须从偏移位置反转链表,将偏移位置的节点连接到反转链表的头部,然后返回链表的原始头节点。在没有哑节点的情况下,我们必须像典型的反转算法那样从链表开头反转,并返回 prev 的最终值。有了哑节点后,这两种情况就统一到了后者。
To discover the node preceding the one from which we will start to reverse, we first iterate m - 1 times. That node is required so that it may subsequently be linked to the start of the reverse list. Prev and head are used to designate the head and tail of the reversed list, respectively, at the conclusion of the second loop.
为了找到我们开始反转位置之前的前一个节点,我们首先迭代 m - 1 次。该节点是必需的,以便随后它可以链接到反转列表的起始处。Prev 和 head 分别用于在第二个循环结束时指定反转列表的头和尾。
class Solution
类解决方案
{
private:
private:
// Given a reference (pointer to pointer) to the head of a list and an int, appends a new node at the end
// 给定一个指向链表头部的指针(指向指针的指针)和一个整数,在末尾追加一个新节点
void append(ListNode** head, int value)
void append(ListNode** head, int value)
{
// First make a new node, insert data in it, and then make its 'next' as NULL, signifying that the end of the linked list has been reached.
// 首先创建一个新节点,将数据插入其中,然后将其 'next' 设为 NULL,表示链表已到达末尾。
ListNode* newNode = new ListNode(); // 1. Allocate node
ListNode* newNode = new ListNode(); // 1. 分配节点
ListNode last = head; // Used in step 5.
ListNode last = head; // 用于步骤 5。
newNode->val = value; // 2. Put in the data.
newNode->val = value; // 2. 放入数据。
newNode->next = NULL; // 3. This new node is going to be the last node, so make next of it as NULL.
newNode->next = NULL; // 3. 这个新节点将是最后一个节点,所以将其 next 设为 NULL。
if(*head == NULL) // 4. If the Linked List is empty, then make the new node as head
if(*head == NULL) // 4. 如果链表为空,则将新节点设为头节点
{
*head = newNode;
*head = newNode;
return;
return;
}
while(last->next != NULL) // 5. Else traverse till the last node.
while(last->next != NULL) // 5. 否则遍历到最后一个节点。
last = last->next;
last = last->next;
last->next = newNode; // 6. Change the next of last node.
last->next = newNode; // 6. 更改最后一个节点的 next。
return;
return;
}
public:
public:
ListNode reverseBetween(ListNode head, int left1, int right1)
ListNode reverseBetween(ListNode head, int left1, int right1)
{
int left = left1 - 1, right = right1 - 1; // We subtract 1 from the given input values because of index issues.
int left = left1 - 1, right = right1 - 1; // 我们从给定输入值中减去1,因为存在索引问题。
std::vectorlinkedList; // This will store our linked list in a vector form.
std::vectorlinkedList; // 这将把我们的链表以向量形式存储。
ListNode firstTemp = head, finalList = NULL; // Temporary variables to hold the linked list.
ListNode firstTemp = head, finalList = NULL; // 用于保存链表的临时变量。
// We first iterate through the LinkedList using the temporary variable 'temp' and insert the data into the vector.
// 我们首先使用临时变量'temp'遍历链表,并将数据插入到向量中。
while(firstTemp != NULL)
while(firstTemp != NULL)
{
linkedList.push_back(firstTemp->val);
linkedList.push_back(firstTemp->val);
firstTemp = firstTemp->next;
firstTemp = firstTemp->next;
}
if(left >= linkedList.size() || left < 0 || left > right || right >= linkedList.size() || right < 0) // We check to make sure that the left and right conditions do not pose any outofbound conditions.
if(left >= linkedList.size() || left < 0 || left > right || right >= linkedList.size() || right < 0) // 我们检查以确保左和右条件不会造成任何越界情况。
// std::cout << "\nThere are errors with the left and right value.";
// std::cout << "\n左右值存在错误。";
return finalList;
return finalList;
/* What we now is essentially involves-
/* 我们现在所做的基本上涉及-
We traverse and insert the data elements from the vector into the new linked list until we reach the 'left' index.
我们遍历并从向量中插入数据元素到新的链表,直到到达'left'索引。
When we reach the 'left' index, we start inserting elements into the linked list starting from 'right' index until the 'left' index.
当我们到达'left'索引时,我们开始从'right'索引向'left'索引方向向链表插入元素。
We then insert the remaining elements after the 'right' index.
我们随后在“right”索引之后插入剩余元素。
*/
int index = 0;
int index = 0;
for(; index < left; index++)
for(; index < left; index++)
append(&finalList, linkedList[index]);
append(&finalList, linkedList[index]);
index = right + 1;
index = right + 1;
for(; right >= left; right--)
for(; right >= left; right--)
append(&finalList, linkedList[right]);
append(&finalList, linkedList[right]);
for(; index < linkedList.size(); index++)
for(; index < linkedList.size(); index++)
append(&finalList, linkedList[index]);
append(&finalList, linkedList[index]);
return finalList;
return finalList;
}
};
Useful Resources
有用资源
- Technical Interview Questions
- Coding Interview Questions
- Interview Resources
- DSA- Programming
- Mock Interview
314. What is Stack corruption?
什么是栈破坏?
- 知识点: 算法与数据结构 (标签: interviewbit, qualcomm, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 高通
- id: 69b37c2d58d557c902bb8167 | 官方: 否 | 付费: 否
答案:
When stack corruption is suspected, one should look at the local variables in the called and calling functions to see if the values passed are different from the values passed by the calling function. A stack corruption has occurred when a parameter seems to have a different value than the one that was passed. When a stack corruption is detected, one should look at the local variables in the called and calling functions to see if they may have been used as a source of memory corruption.
当怀疑发生栈破坏时,应查看被调用函数和调用函数中的局部变量,以判断传入的值是否与调用函数传递的值不一致。当一个参数的值似乎与传入的值不同时,表明发生了栈破坏。检测到栈破坏后,应检查被调用函数和调用函数中的局部变量,看它们是否可能被用作内存破坏的源头。
315. Given an integer targetSum and a binary tree representing a root-to-leaf path that adds up all the values along the path, return true if and only if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
给定一个整数targetSum和一个二叉树,表示一条从根到叶的路径,该路径累加所有沿路径节点的值,当且仅当该树存在一条从根到叶的路径,使得沿路径所有值之和等于targetSum时,返回true。
- 知识点: 算法与数据结构 (标签: interviewbit, qualcomm, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 高通
- id: 69b37c2d58d557c902bb817a | 官方: 否 | 付费: 否
答案:
Example 1:
示例1:
- Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
- Output: true
- Explanation: The root-to-leaf path with the target sum is shown.
Example 2: - Input: root = [1,2,3], targetSum = 5
示例2: - 输入:root = [1,2,3], targetSum = 5
- Output: false
Explanation: There two root-to-leaf paths in the tree:(1 --> 2): The sum is 3.(1 --> 3): The sum is 4.There is no root-to-leaf path with sum = 5.
Example 3: - Input: root = [], targetSum = 0示例3:- 输入:root = [],targetSum = 0
- Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.
Solution解决方案
The function is calculating the sum of the current node value and the target value and then checks to see if the current node value is equal to the target value at the leaf node. If the function succeeds at the leaf node, it is self-evident that the path has a value of sum equal to targetSum.
该函数计算当前节点值与目标值之和,然后检查当前节点值在叶节点处是否等于目标值。如果函数在叶节点处成功,则显然该路径的和等于targetSum。
int sum=0;
int sum=0;
public boolean hasPathSum(TreeNode root, int targetSum) {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root==null){
if(root==null){
return false;
返回 false;
}
if(root.left==null && root.right==null){ //checking for leaf node
if(root.left==null && root.right==null){ //检查是否为叶节点
if(targetSum-root.val==0){ //subtracting value of root from the sum given in order to find total sum is same to target sum or not
if(targetSum-root.val==0){ //从给定的总和中减去根的值,以判断总和是否等于目标总和
return true;
返回 true;
}
}
else{
否则{
return hasPathSum(root.left,targetSum-root.val)|| hasPathSum(root.right,targetSum-root.val);
return hasPathSum(root.left,targetSum-root.val)|| hasPathSum(root.right,targetSum-root.val);
}
return false;
返回 false;
}
}
316. Find the largest contiguous subarray (containing at least one number) of an integer array nums and return its value. An array subrange is a contiguous portion of an array.
找出整数数组nums中最大的连续子数组(至少包含一个数字)并返回其值。数组子范围是数组的连续部分。
- 知识点: 算法与数据结构 (标签: interviewbit, qualcomm, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: 高通
- id: 69b37c2d58d557c902bb8187 | 官方: 否 | 付费: 否
答案:
Example 1: - Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
示例1:- 输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
- Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2: - Input: nums = [1]示例2:- 输入:nums = [1]
Output: 1
Example 3: - Input: nums = [5,4,-1,7,8]示例 3: - 输入:nums = [5,4,-1,7,8]
Output: 23
Solution解决方案
To solve the problem, we need to separate it into two distinguishable parts. nums[ ] contains both positive and negative numbers. We iterate through nums[ ], and we increment nums[i] by adding nums[i] to our current variable. If the current is negative, then we discard it. If the current is positive, then we retain it. In the meantime, we must ensure that max keeps track of the maximum sum. nums[ ] only contains negative numbers. We can pick up the biggest number among them simply by choosing it.
要解决这个问题,我们需要将其分为两个可区分的部分。nums[ ] 同时包含正数和负数。我们遍历 nums[ ],并通过将 nums[i] 加到当前变量来递增 nums[i]。如果当前值为负,则丢弃它。如果当前值为正,则保留它。同时,我们必须确保 max 记录最大和。nums[ ] 仅包含负数。我们可以通过选择其中最大的数来直接选取最大的一个。
class Solution
类解决方案
{
public int maxSubArray(int[] nums)
公共 int maxSubArray(int[] nums)
{
// O(n) time | O(1) space
// O(n) 时间 | O(1) 空间
int current = nums[0];
int current = nums[0];
int max = nums[0];
int max = nums[0];
for(int i = 1; i < nums.length; i++)
对于(int i = 1; i < nums.length; i++)
{
current = Math.max(nums[i], nums[i] + current);
current = Math.max(nums[i], nums[i] + current);
max = Math.max(current, max);
max = Math.max(current, max);
}
return max;
返回 max;
}
}
317. A length of the longest consecutive elements sequence can be obtained from an unsorted array of integers by running the algorithm O(n) time.
通过运行算法 O(n) 时间,可以从无序整数数组中获得最长连续元素序列的长度。
- 知识点: 算法与数据结构 (标签: interviewbit, qualcomm, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: 高通
- id: 69b37c2d58d557c902bb819f | 官方: 否 | 付费: 否
答案:
Example 1: - Input: nums = [100,4,200,1,3,2]
示例 1: - 输入:nums = [100,4,200,1,3,2]
- Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2: - Input: nums = [0,3,7,2,5,8,4,6,0,1]示例 2: - 输入:nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
A max-length sequence can be generated by considering each element to be a part of some series and searching for the largest sequence that includes that number. Copy all the elements in the set first. Count the previous consecutive element from this element and the similar next consecutive elements from this element. A max-length sequence from this element is "prevCount + nextCount + 1". It is the result of the calculations above. To find the max-length sequence, you must delete all the numbers you had visited once so that you can again try to find a sequence that already belongs to an existing sequence.通过将每个元素视为某个序列的一部分,并搜索包含该数字的最大序列,可以生成最大长度序列。首先将所有元素复制到集合中。从该元素开始,计算前一个连续元素的数量,以及从该元素开始的类似下一个连续元素的数量。从该元素得到的最大长度序列是“prevCount + nextCount + 1”。这是上述计算的结果。为了找到最大长度序列,你必须删除所有已访问过的数字,以免再次尝试查找已经属于现有序列的序列。
class Solution {
class Solution {
public int longestConsecutive(int[] a) {
public int longestConsecutive(int[] a) {
int len = a.length;
int len = a.length;
if(len == 0 || len == 1) {
if(len == 0 || len == 1) {
return len;
return len;
}
int result = 0;
int result = 0;
HashSet
HashSetset = new HashSet ();
for(int i : a) {
for(int i : a) {
set.add(i);
set.add(i);
}
for(int i = 0; i < len; i++) {
for(int i = 0; i < len; i++) {
int item = a[i];
int item = a[i];
if(!set.contains(item)) continue;
if(!set.contains(item)) continue;
int prevItem = item-1;
int prevItem = item-1;
int nextItem = item+1;
int nextItem = item+1;
int prevCount = 0;
int prevCount = 0;
int nextCount = 0;
int nextCount = 0;
set.remove(item);
set.remove(item);
while(set.contains(prevItem)) {
while(set.contains(prevItem)) {
set.remove(prevItem);
set.remove(prevItem);
prevCount++;
prevCount++;
prevItem--;
prevItem--;
}
while(set.contains(nextItem)) {
while(set.contains(nextItem)) {
set.remove(nextItem);
set.remove(nextItem);
nextCount++;
nextCount++;
nextItem++;
nextItem++;
}
result = Math.max(result, (prevCount+nextCount+1));
result = Math.max(result, (prevCount+nextCount+1));
}
return result;
return result;
}
}
Qualcomm Interview Preparation
318. What is the difference between array and hash table?
数组和哈希表之间有什么区别?
- 知识点: 算法与数据结构 (标签: interviewbit, siemens, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Siemens
- id: 69b37c5158d557c902bc75bb | 官方: 否 | 付费: 否
答案:
An array has a set number of memory regions at first. It should store a preset type at each site (e.g. an integer). It could have repeated values or not.
数组起初具有固定数量的内存区域。它应在每个位置存储预设类型(例如整数)。它可能有重复值,也可能没有。
Hash is implemented as a set, on the other hand. It's built around an array. A hash function determines the position of an item in an array. There should be no duplicates in a hash. A collision occurs when duplicates occur, and there are several techniques for resolving this (e.g. chain duplicates, rehash and so on).
另一方面,哈希是作为集合实现的。它围绕数组构建。哈希函数决定数组中某项的位置。哈希中不应有重复项。当出现重复时会发生冲突,并且有几种解决该问题的技术(例如,链式重复、重新哈希等)。
319. What is meant by stack and queue?
栈和队列是什么意思?
- 知识点: 算法与数据结构 (标签: interviewbit, siemens, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Siemens
- id: 69b37c5158d557c902bc75ec | 官方: 否 | 付费: 否
答案:
- A stack is a linear data structure in which elements can only be added or removed from the top side of the list. The LIFO (Last In First Out) principle dictates that the element put last is the first to come out of a stack. Pushing an element into a stack is referred to as a push operation while removing an element from a stack is referred to as a pop operation. With a pointer called top, we always maintain track of the last entry in the list in the stack.
- A queue is a linear data structure in which elements can only be inserted from one side of the list, called the back, and only deleted from the other side, called the front. The FIFO (First In First Out) principle governs the queue data structure, which means that the element placed first in the list is the first one withdrawn from the list. Enqueue operations are used to add items to a queue, and dequeue operations are used to remove items from a queue.
320. What is the RR Scheduling Algorithm in OS?
操作系统中的RR调度算法是什么?
- 知识点: 算法与数据结构 (标签: interviewbit, tcs, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c6a58d557c902bc84d7 | 官方: 否 | 付费: 否
答案:
The RR (round-robin) scheduling algorithm was designed with time-sharing systems in mind. The CPU scheduler goes around a circular queue, allocating CPU to each task for a time period of up to around 10 to 100 milliseconds.
RR(轮转)调度算法是为分时系统设计的。CPU调度器围绕一个循环队列工作,为每个任务分配最多约10到100毫秒的CPU时间。
It is simple and easy to implement. It is preemptive because processes are only allotted CPU for a certain amount of time. All processes get an equal share of CPU. Disadvantages include context switches, low throughput, larger waiting time, and response time.
它简单且易于实现。它是抢占式的,因为进程只被分配一定量的CPU时间。所有进程获得相等的CPU份额。缺点包括上下文切换、低吞吐量、较长的等待时间和响应时间。
321. Discuss the RSA algorithm in brief.
简要讨论RSA算法。
- 知识点: 算法与数据结构 (标签: interviewbit, tcs, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c6a58d557c902bc8501 | 官方: 否 | 付费: 否
答案:
The RSA, an asymmetric cryptography algorithm, is used to protect the data transfer. For encryption, this technique uses a public key, while the decryption key is kept secure or secret. Two huge prime numbers are used to generate the encryption key, which is then publicized along with an auxiliary value. This public key can be used for encryption by anyone, but only someone who knows the prime numbers can decrypt it. This technique, however, is believed to be slow, and as a result, it is not frequently used to encrypt data.
RSA是一种非对称密码算法,用于保护数据传输。对于加密,该技术使用公钥,而解密密钥保持安全或秘密。使用两个巨大的质数生成加密密钥,然后与一个辅助值一起公开。任何人都可以使用此公钥进行加密,但只有知道质数的人才能解密。然而,该技术被认为较慢,因此不常用于加密数据。
322. In a software program, what is cyclomatic complexity?
在软件程序中,什么是圈复杂度?
- 知识点: 算法与数据结构 (标签: interviewbit, tcs, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c6a58d557c902bc8504 | 官方: 否 | 付费: 否
答案:
The number of linearly independent paths in a code segment is measured in terms of cyclomatic complexity. It's a software statistic that shows how complex a code is. It is calculated using the program's Control Flow Graph. The nodes in the graph represent the smallest set of commands in a program, and a directed edge connects the two nodes, indicating whether the second command should be executed immediately after the first.
代码段中线性独立路径的数量以圈复杂度来衡量。它是一个软件统计量,显示代码的复杂程度。它使用程序的控制流图来计算。图中的节点表示程序中最小的命令集,有向边连接两个节点,指示第二个命令是否应在第一个命令之后立即执行。
The directed graph inside control flow is the edge connecting two basic blocks of the program mathematically, as control may flow from first to second.
控制流中的有向图在数学上是连接程序两个基本块的边,因为控制可能从第一个流向第二个。
CC = E − N + P
CC = E − N + P
where,
其中,
CC: cyclomatic complexity.
CC:圈复杂度。
E : number of edges in the control flow graph
E:控制流图中边的数量
N : the number of nodes in the control flow graph
N:控制流图中节点的数量
P : the number of connected elements
P:连接元素的数量
323. What is a data structure and can you name some examples?
什么是数据结构,你能举一些例子吗?
- 知识点: 算法与数据结构 (标签: interviewbit, tcs-digital, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c6d58d557c902bc865a | 官方: 否 | 付费: 否
答案:
A data structure is a way of organizing and storing data in a computer so that it can be accessed and modified efficiently. Different data structures are suited to different kinds of applications, and choosing an appropriate data structure can have a significant impact on the performance and efficiency of a program.
数据结构是一种在计算机中组织和存储数据的方式,以便高效地访问和修改数据。不同的数据结构适用于不同类型的应用程序,选择合适的数据结构会对程序的性能和效率产生显著影响。
There are 2 main types of Data Structures as shown in the image below-
如下图所示,主要有2种类型的数据结构——
Linear Data Structures: A linear data structure is a type of data structure in which data elements are arranged sequentially or linearly. Each element is attached to its previous and next adjacent elements. With only one level involved, all elements in a linear data structure can be traversed in a single run. Implementing linear data structures is relatively easy since computer memory is arranged linearly. Examples of linear data structures include arrays, linked lists, stacks, and queues.
- 线性数据结构:线性数据结构是一种数据元素按顺序或线性排列的数据结构。每个元素与其前一个和后一个相邻元素相连。由于只涉及一个层级,线性数据结构中的所有元素可以在单次运行中遍历。实现线性数据结构相对容易,因为计算机内存是线性排列的。线性数据结构的示例包括数组、链表、栈和队列。
Array: An array is a linear data structure that stores a fixed-size sequential collection of elements of the same type. Arrays are indexed, meaning that each element can be accessed directly by its position in the array.
数组:数组是一种线性数据结构,存储相同类型元素的固定大小顺序集合。数组是有索引的,这意味着每个元素可以通过其在数组中的位置直接访问。
Linked list: A linked list is a linear data structure that consists of a sequence of nodes, where each node stores a reference to the next node in the list. Linked lists do not have a fixed size and can grow or shrink as needed.
链表:链表是一种线性数据结构,由一系列节点组成,其中每个节点存储对列表中下一个节点的引用。链表没有固定大小,可以根据需要增长或缩小。
Stack: A stack is a linear data structure that follows the last-in, first-out (LIFO) principle. It has two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element from the stack.
栈:栈是一种遵循后进先出(LIFO)原则的线性数据结构。它有两个主要操作:push,将元素添加到栈顶;pop,从栈顶移除元素。
Queue: A queue is a linear data structure that follows the first-in, first-out (FIFO) principle. It has two main operations: enqueue, which adds an element to the end of the queue, and dequeue, which removes the element from the front of the queue. 2. Non-Linear Data Structures: A non-linear data structure is a type of data structure in which data elements are not arranged sequentially or linearly. Unlike linear data structures, a single level is not involved in non-linear data structures, so it is impossible to traverse all the elements in a single run. Implementing non-linear data structures is more difficult than implementing linear data structures. However, non-linear data structures use computer memory more efficiently than linear data structures. Examples of non-linear data structures include trees and graphs. 3. Tree: A tree is a non-linear data structure that consists of a set of nodes organized in a hierarchical structure. Each node has one or more child nodes, and the top node is called the root. Trees are often used to represent hierarchical relationships, such as the structure of a file system. 4. Graph: A graph is a non-linear data structure that consists of a set of vertices (nodes) and edges that connect them. Graphs are often used to represent complex relationships and networks, such as social networks or transportation networks.
队列:队列是一种遵循先进先出(FIFO)原则的线性数据结构。它有两个主要操作:enqueue,将元素添加到队列末尾;dequeue,从队列前端移除元素。 2. 非线性数据结构:非线性数据结构是一种数据元素不按顺序或线性排列的数据结构。与线性数据结构不同,非线性数据结构不涉及单一层级,因此无法在单次运行中遍历所有元素。实现非线性数据结构比实现线性数据结构更困难。然而,非线性数据结构比线性数据结构更高效地利用计算机内存。非线性数据结构的示例包括树和图。 3. 树:树是一种非线性数据结构,由一组按层次结构组织的节点组成。每个节点有一个或多个子节点,顶部节点称为根。树通常用于表示层次关系,如文件系统的结构。 4. 图:图是一种非线性数据结构,由一组顶点(节点)和连接它们的边组成。图通常用于表示复杂关系和网络,如社交网络或交通网络。
The choice of data structure depends on the specific needs of the application and the trade-offs between different factors, such as space complexity, time complexity, and ease of implementation.
数据结构的选择取决于应用的具体需求以及不同因素之间的权衡,例如空间复杂度、时间复杂度和实现难易度。
324. What is an algorithm? Can you give an example of a simple algorithm?
什么是算法?你能给出一个简单算法的例子吗?
- 知识点: 算法与数据结构 (标签: interviewbit, tcs-digital, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c6d58d557c902bc8660 | 官方: 否 | 付费: 否
答案:
An algorithm is a set of well-defined steps or instructions that can be followed to solve a problem or accomplish a task. Algorithms are an essential part of computer science and are used in a wide range of applications, including data processing, machine learning, and artificial intelligence.
算法是一组定义明确的步骤或指令,可用于解决问题或完成任务。算法是计算机科学的重要组成部分,广泛应用于数据处理、机器学习和人工智能等领域。
An algorithm should have the following properties: - Input: An algorithm should take one or more inputs as input.
一个算法应具有以下属性: - 输入:算法应接受一个或多个输入。
- Output: An algorithm should produce one or more outputs as a result of the input.
- Definiteness: An algorithm should have a clear and precise set of steps that can be followed in a specific order.
- Finiteness: An algorithm should have a finite number of steps and should terminate after a certain point.
Effectiveness: An algorithm should be able to solve a problem or accomplish a task in a reasonable amount of time.
Here is an example of a simple algorithm for finding the maximum value in a list of numbers:以下是一个用于查找数字列表中最大值的简单算法示例:
Set a variable called "max" to the first number in the list. 2. For each number in the list, starting with the second number:If the current number is greater than "max", set "max" to the current number. 3. Return "max" as the output.
- 将名为“max”的变量设置为列表中的第一个数字。 2. 对于列表中的每个数字,从第二个数字开始:如果当前数字大于“max”,则将“max”设置为当前数字。 3. 将“max”作为输出返回。
This algorithm takes a list of numbers as input and returns the maximum value in the list as output. It follows a clear and precise set of steps and terminates after a finite number of iterations. It is also effective, as it can find the maximum value in the list in a reasonable amount of time.
该算法以数字列表作为输入,并输出列表中的最大值。它遵循清晰而精确的步骤,并在有限次迭代后终止。它也是有效的,因为它能在合理的时间内找到列表中的最大值。
325. What is a stack, and how does it work?
什么是栈,它如何工作?
- 知识点: 算法与数据结构 (标签: interviewbit, tcs-digital, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c6e58d557c902bc867a | 官方: 否 | 付费: 否
答案:
A stack is a linear data structure that follows the last-in, first-out (LIFO) principle. This means that the last element added to the stack is the first one to be removed.
栈是一种遵循后进先出(LIFO)原则的线性数据结构。这意味着最后添加到栈中的元素最先被移除。
A stack representation is a way of visualizing how data is stored and retrieved in a Last-In-First-Out (LIFO) data structure. In a stack, data is added and removed from the top of the stack, and a stack representation shows how the elements are stacked on top of each other as shown in the above image. This is commonly used in computer science and programming to help understand how data is organized and accessed in memory.
栈表示是一种可视化在LIFO数据结构中如何存储和检索数据的方式。在栈中,数据从栈顶添加和移除,栈表示展示了元素如何相互叠加,如上面的图像所示。这在计算机科学和编程中常用于帮助理解数据在内存中如何组织和访问。
A stack has the following operations: - Push: This operation adds an element to the top of the stack.
栈具有以下操作: - Push:该操作向栈顶添加一个元素。
- Pop: This operation removes the top element from the stack and returns it.
- Peek: This operation returns the top element of the stack without removing it.
isEmpty: This operation returns true if the stack is empty, and false otherwise.
The time and space complexity of the stack operations are: - Time Complexity: O(1) - Constant time, which means it takes constant time to execute push, pop, peek, and check if the stack is empty.栈操作的时间复杂度和空间复杂度为:- 时间复杂度:O(1)——常数时间,这意味着执行 push、pop、peek 和检查栈是否为空只需常数时间。
Space Complexity: O(1) - Constant space, as the above-listed operations require only a fixed amount of memory.
A stack is usually implemented using an array or a linked list. Here is an example of a stack implemented using an array in Python (you can also find sample inputs and corresponding outputs in the code comments):栈通常使用数组或链表实现。下面是使用 Python 中的数组实现栈的示例(你也可以在代码注释中找到示例输入和相应的输出):
class Stack:
类 Stack:
def __init__(self):
def __init__(self):
self.stack = [] # initialize an empty list to represent the stack
self.stack = [] # 初始化一个空列表来表示栈
def push(self, item):
def push(self, item):
self.stack.append(item) # add the item to the top of the stack
self.stack.append(item) # 将元素添加到栈的顶部
def pop(self):
def pop(self):
if self.is_empty():
if self.is_empty():
return None # if the stack is empty, return None
return None # 如果栈为空,则返回 None
return self.stack.pop() # remove and return the top item from the stack
return self.stack.pop() # 从栈中移除并返回顶部元素
def peek(self):
def peek(self):
if self.is_empty():
if self.is_empty():
return None # if the stack is empty, return None
return None # 如果栈为空,则返回 None
return self.stack[-1] # return the top item from the stack without removing it
return self.stack[-1] # 返回栈的顶部元素但不移除它
def is_empty(self):
def is_empty(self):
return len(self.stack) == 0 # return True if the stack is empty, False otherwise
返回 len(self.stack) == 0 # 如果栈为空则返回 True,否则返回 False
Example usage
stack = Stack() # create an empty stack
stack = Stack() # 创建一个空栈
stack.push(1) # add 1 to the top of the stack
stack.push(1) # 将 1 添加到栈顶
stack.push(2) # add 2 to the top of the stack
stack.push(2) # 将 2 添加到栈顶
stack.push(3) # add 3 to the top of the stack
stack.push(3) # 将 3 添加到栈顶
print(stack.stack) # output: [1, 2, 3] (the current state of the stack)
print(stack.stack) # 输出:[1, 2, 3](栈的当前状态)
print(stack.pop()) # output: 3 (remove and return the top item from the stack)
print(stack.pop()) # 输出:3(从栈中移除并返回栈顶元素)
print(stack.peek()) # output: 2 (return the top item from the stack without removing it)
print(stack.peek()) # 输出:2(返回栈顶元素但不移除)
stack.push(4) # add 4 to the top of the stack
stack.push(4) # 将 4 添加到栈顶
print(stack.stack) # output: [1, 2, 4] (the current state of the stack)
print(stack.stack) # 输出:[1, 2, 4](栈的当前状态)
print(stack.is_empty()) # output: False (the stack is not empty)
print(stack.is_empty()) # 输出:False(栈不为空)
Stacks are used in various applications, such as evaluating expressions, reversing a string, and implementing undo/redo functions. They are also commonly used in programming languages as a means of storing and accessing local variables during function calls.
栈用于各种应用中,例如计算表达式、反转字符串以及实现撤销/重做功能。它们也常用于编程语言中,作为在函数调用期间存储和访问局部变量的手段。
326. What is Dynamic programming?
什么是动态规划?
- 知识点: 算法与数据结构 (标签: interviewbit, tcs-digital, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c6e58d557c902bc8680 | 官方: 否 | 付费: 否
答案:
Dynamic programming is a method of solving problems by breaking them down into smaller subproblems, solving the subproblems, and combining the solutions to the subproblems to solve the original problem. It is particularly useful for solving problems that can be divided into overlapping subproblems, such as optimization problems, recursive problems, and decision problems.
动态规划是一种通过将问题分解为更小的子问题、解决子问题,并将子问题的解合并来解决原始问题的方法。它特别适用于解决可以划分为重叠子问题的问题,例如优化问题、递归问题和决策问题。
Top-down and bottom-up are two common approaches to problem-solving and programming. Here is an explanation of both approaches, as well as examples of implementing the Fibonacci series using both methods:
自顶向下和自底向上是解决问题和编程的两种常见方法。以下是这两种方法的解释,以及使用这两种方法实现斐波那契数列的示例:
- Top-down approach: The top-down approach is also known as the "divide and conquer" approach. It involves breaking a problem down into smaller sub-problems, solving each sub-problem, and then combining the results to solve the original problem.
- This approach is also called memoization. This approach is often used when the problem is complex and difficult to solve in one step. It provides a high-level view of the problem and helps to identify the key sub-problems that need to be solved.
- Example: To find the nth number in the Fibonacci series using the top-down approach, we would start by defining a function that takes an integer n as an argument. The function would first check if n is less than or equal to 1, in which case it would return n. Otherwise, it would recursively call itself to calculate the two previous numbers in the series and add them together to get the nth number. This has been illustrated in the diagram below for the example of getting the 5th number in the Fibonacci series:
Here is the code example:
以下是代码示例:
int fibonacci_top_down(int n) {
int fibonacci_top_down(int n) {
if (n <= 1) {
if (n <= 1) {
return n;
返回 n;
}
return fibonacci_top_down(n-1) + fibonacci_top_down(n-2);
return fibonacci_top_down(n-1) + fibonacci_top_down(n-2);
}
// Get 5th fibonacci number
// 获取第5个斐波那契数
fibonacci_top_down(5);
fibonacci_top_down(5);
// Output = 5
// 输出 = 5
In the above code, we have to find the 5th Fibonacci number. To do this, we have to find the 4th Fibonacci number and the 3rd Fibonacci number. And this goes on until it reaches the base problem. The values are then summed up to get the actual 5th Fibonacci number. So this is nothing but the top-down approach.
在上述代码中,我们需要找到第5个斐波那契数。为此,我们需要找到第4个和第3个斐波那契数,并以此类推,直到达到基本情况。然后将这些值相加,得到实际的第5个斐波那契数。所以这无非就是自顶向下的方法。
- Bottom-up approach: The bottom-up approach is also known as the "iterative" or “tabulation” approach. It involves solving the smaller subproblems first and using those solutions to solve the larger problem. This approach is often used when the problem can be solved by a series of simple steps, and when it is easy to identify the order in which the steps should be performed.
Example: To find the nth number in the Fibonacci series using the bottom-up approach, we would start by defining an array to store the results of the previous two numbers in the series. We would then use a loop to iterate through the numbers from 2 to n, calculating each number in turn by adding the previous two numbers in the array together. This has been illustrated in the diagram below for the example of getting the 5th number in the Fibonacci series:
示例:使用自底向上方法找到斐波那契数列中的第n个数时,我们会先定义一个数组来存储数列中前两个数的结果。然后使用循环从2到n迭代,通过将数组中的前两个数相加来计算每个数。下面用图示说明了获取斐波那契数列中第5个数的示例:
Code example:
代码示例:
int fibonacci_bottom_up(int n) {
int fibonacci_bottom_up(int n) {
if (n <= 1) {
if (n <= 1) {
return n;
返回 n;
}
int fib[n+1];
int fib[n+1];
fib[0] = 0;
fib[0] = 0;
fib[1] = 1;
fib[1] = 1;
for (int i = 2; i <= n; i++) {
for (int i = 2; i <= n; i++) {
fib[i] = fib[i-1] + fib[i-2];
fib[i] = fib[i-1] + fib[i-2];
}
return fib[n];
return fib[n];
}
// Get 5th fibonacci number
// 获取第5个斐波那契数
fibonacci_bottom_up(5);
fibonacci_bottom_up(5);
// Output = 5
// 输出 = 5
In the above image, we have to find the 5th Fibonacci number, so to do this, we have to know about the 3rd and 4th Fibonacci Numbers and so on till the base problem. So instead of solving from the 5th, we can start from the lower and move towards the Upwards. This is nothing but Bottom-Up Approach
在上图中,我们需要找到第5个斐波那契数,要做到这一点,我们必须知道第3个和第4个斐波那契数,以此类推直到基础问题。因此,与其从第5个开始求解,我们可以从较小的数开始,向上移动。这就是自底向上的方法
In summary. both top-down and bottom-up approaches have their own pros and cons, and the choice of which approach to use depends on the problem being solved. The Fibonacci series is just one example of how these approaches can be applied in practice.
总之,自顶向下和自底向上两种方法各有优缺点,选择使用哪种方法取决于所解决的问题。斐波那契数列只是这些方法在实际应用中的一个例子。
327. Write a program to find the sum of each row of a matrix?
编写一个程序来计算矩阵每一行的和?
- 知识点: 算法与数据结构 (标签: interviewbit, tcs-ninja, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c7258d557c902bc880c | 官方: 否 | 付费: 否
答案:
class RowSum{
class RowSum{
static void sumOfRow(int matrix[][],int row, int col)
static void sumOfRow(int matrix[][],int row, int col)
{
int i, j;
int i, j;
int sum = 0;
int sum = 0;
for (i = 0; i < row; ++i) {
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
for (j = 0; j < col; ++j) {
//Calculating sum of elements in a row
// 计算一行中元素的和
sum = sum + matrixi;
sum = sum + matrixi;
}
System.out.println(sum);
System.out.println(sum);
//Reset sum after each row
//在每行之后重置 sum
sum = 0;
sum = 0;
}
}
public static void main(String[] args)
public static void main(String[] args)
{
//Input matrix
//输入矩阵
int[][] matrix = {{1,2,3,4},
int[][] matrix = {{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}};
sumOfRow(matrix,4,4);
sumOfRow(matrix,4,4);
}
}
Output:
输出:
10, 26, 42, 58
Take variable sum to store the sum of the row. Start traversing the matrix and in each traversal calculate the sum of the row and then print it and then rest it. - Time Complexity: O(m*n), we are traversing through the whole matrix so. Where m is the number of rows and n is the number of columns.
取变量 sum 存储该行的和。开始遍历矩阵,在每次遍历中计算该行的和,然后打印它,然后将其重置。 - 时间复杂度:O(m*n),因为我们遍历了整个矩阵。其中 m 是行数,n 是列数。
Space Complexity: O(1)
Useful Resources - TCS Interview Questions有用资源 - TCS 面试问题
- TCS HR Interview Questions
- Technical Interview Questions
- Coding Interview Questions
- Interview Resources
- Programming- DSA
- Online Compiler
328. Write a program to calculate the sum of diagonal of a matrix?
编写一个程序来计算矩阵对角线的和?
- 知识点: 算法与数据结构 (标签: interviewbit, tcs-ninja, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c7258d557c902bc8822 | 官方: 否 | 付费: 否
答案:
Include only the total of the primary diagonal elements and the secondary diagonal elements that are not a part of the primary diagonal.
仅包含主对角线元素的总和以及不属于主对角线的次对角线元素。
class Solution {
class Solution {
public static int diagonalSum(int[][] matrix) {
public static int diagonalSum(int[][] matrix) {
int row=0,col,leftSum=0,rightSum=0,n=matrix.length;
int row=0,col,leftSum=0,rightSum=0,n=matrix.length;
col=n-1;
col=n-1;
while(row<n){
while(row<n){
//Calculate sum of left diagonal
//计算左对角线之和
leftSum += matrixi;
leftSum += matrixi;
//Check if row and column are not same
//检查行和列是否相同
if(row!=col)
if(row!=col)
//Calculate the sum of right diagonal
//计算右对角线之和
rightSum += matrixi;
rightSum += matrixi;
//update row and col
//更新行和列
row++;
row++;
col--;
col--;
}
return (leftSum + rightSum);
return (leftSum + rightSum);
}
public static void main(String []args){
public static void main(String []args){
//Input matrix
//输入矩阵
int [][]matrix = {{10,20,30},
int [][]matrix = {{10,20,30},
{40,50,60},
{70,80,90}};
int result = diagonalSum(matrix);
int result = diagonalSum(matrix);
System.out.println(result);
System.out.println(result);
}
}
Output:
输出:
250
Take two variables to store the sum of the left and right diagonal.
使用两个变量分别存储左对角线和右对角线的和。
Take two pointers row, col to traverse the matrix. If row and col are equal then we have to add that element only once either in leftSum or rightSum. - Time Complexity: O(n), as we are running a loop to n times.
使用两个指针 row、col 来遍历矩阵。如果 row 和 col 相等,则只需将该元素添加到 leftSum 或 rightSum 中一次。- 时间复杂度:O(n),因为我们循环运行 n 次。
- Space Complexity: O(1)
329. Write a program to check if given number is palindrome or not?
编写一个程序,检查给定的数字是否为回文数?
- 知识点: 算法与数据结构 (标签: interviewbit, tcs-ninja, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c7258d557c902bc8825 | 官方: 否 | 付费: 否
答案:
When a number reads the same both forward and backward, it is a palindrome.
当一个数字正向和反向读取相同时,它就是回文数。
Example: 232 is a palindrome while 233 is not.
示例:232 是回文数,而 233 不是。
class Palindrome {
class Palindrome {
public static boolean checkPalindrome(int number) {
public static boolean checkPalindrome(int number) {
//Check if number is zero
//检查数字是否为零
if (number < 0) {
if (number < 0) {
return false;
返回 false;
}
//To store the remaining number after each iteration
//存储每次迭代后的剩余数字
int remain = number;
int remain = number;
int reversNumber = 0;
int reversNumber = 0;
while (remain != 0) {
while (remain != 0) {
//Extract last digit and add to the reversed number
//提取最后一位数字并加到反转后的数字上
reversNumber = reversNumber * 10 + remain % 10;
reversNumber = reversNumber * 10 + remain % 10;
//Update the remaining number
//更新剩余数字
remain /= 10;
remain /= 10;
}
return number == reversNumber;
return number == reversNumber;
}
public static void main(String []args){
public static void main(String []args){
//Input number
//输入数字
int number = 123;
int number = 123;
boolean result = checkPalindrome(number);
boolean result = checkPalindrome(number);
System.out.println(result);
System.out.println(result);
}
}
Output:
输出:
true
true
Take two-variable remain and reverseNumber initially copy the number into the remaining variable. Start a loop till the remains become zero.
使用两个变量remain和reverseNumber,首先将数字复制到remain变量中。开始一个循环,直到remain变为零。
Extract the last digit of the number using the modulus operator and then add it to the reverseNumber. Now update the remaining number. When the remaining is zero comes out of the loop and checks if the number and reverseNumber are strictly equal then returns true otherwise returns false. - Time Complexity: O(n), where n is the number of digits in the given number.
使用模运算符提取数字的最后一位,然后将其加到reverseNumber中。现在更新remain数字。当remain为零时退出循环,并检查number和reverseNumber是否严格相等,若相等则返回true,否则返回false。- 时间复杂度:O(n),其中n是给定数字的位数。
- Space complexity: O(1), as we are only using a single variable to store reversed numbers.
330. What is a linked list explain with an example?
什么是链表,并举例说明?
- 知识点: 算法与数据结构 (标签: interviewbit, tcs-ninja, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c7258d557c902bc8850 | 官方: 否 | 付费: 否
答案:
A linked list is a linear data structure. Unlike a conventional sequential data structure, a linked list maintains its elements at non-contiguous memory locations. A linked list is composed of nodes interconnected by pointers. A node in the Linked List consists of two parts: data and a pointer. The pointer points to the next node in the list.
链表是一种线性数据结构。与传统的顺序数据结构不同,链表将其元素存储在非连续的内存位置中。链表由通过指针相互连接的节点组成。链表中的节点由两部分组成:数据和指针。指针指向列表中的下一个节点。
The head always points to the first node of the linked list, and the last node will always point to null.
头指针始终指向链表的第一个节点,而最后一个节点始终指向null。
Example: music or video player, next and previous buttons in the browser.
例如:音乐或视频播放器中的上一个和下一个按钮,浏览器中的上一步和下一步按钮。
Types of Linked List: - Singly Linked List.
链表的类型:- 单向链表。
- Doubly Linked List.
- Circular Linked List.
331. What is the stack data structure and its operations?
什么是栈数据结构及其操作?
- 知识点: 算法与数据结构 (标签: interviewbit, tcs-ninja, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c7258d557c902bc885a | 官方: 否 | 付费: 否
答案:
The Last In First Out (LIFO) concept is used by stacks, which are dynamic data structures. The first thing to be removed from a stack is the last thing that was added to it. The addition and removal of items are limited in stacks. Only one end of the stack, i.e., the top, can have items added or removed. The top item is the one at the very top. Push() and pop() are the names of the operations that add and remove items, respectively.
栈是动态数据结构,采用后进先出(LIFO)的概念。从栈中第一个被移除的元素是最后添加进去的元素。栈中元素的添加和移除是受限的。只能从栈的一端,即栈顶,添加或移除元素。栈顶元素就是位于最顶端的那个元素。添加和移除元素的操作分别称为push()和pop()。
Some common operations used on stacks include the following: - push(): Push operation is used to insert an item at the top of the stack.
栈上常用的一些操作包括以下内容:- push():Push操作用于在栈顶插入一个元素。
- pop(): Pop operation is used to remove the element from the top of the stack.
- isEmpty(): This method is used to know if the stack is empty or not.
- isFull(): This method is used to know if the stack is full or not.
- peek(): This method returns the element at any given index in the stack.
332. What is fragmentation? What does Linked List have to do with it?
什么是碎片化?链表与它有什么关系?
- 知识点: 算法与数据结构 (标签: interviewbit, tcs-nqt, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c7558d557c902bc8966 | 官方: 否 | 付费: 否
答案:
We know that when we use arrays, we use sequential memory, i.e. the memory is used contiguously. Now, let us say that we have a large size array and we don’t have that much sequential memory. So, we won’t be able to store that data. Even if the memory is available, it is not available contiguously, but rather in fragments and we are not able to utilize this. This is called fragmentation.
我们知道当使用数组时,我们使用的是顺序内存,即内存是连续使用的。现在,假设我们有一个大型数组,但我们没有那么多连续内存。所以,我们将无法存储那些数据。即使内存可用,也不是连续可用的,而是以碎片形式存在,我们无法利用这些内存。这称为碎片化。
So, we can use a linked list to store the data as it does not require contiguous memory and thus solves the problem of fragmentation. In a linked list, data is stored in a node that also stores the pointer to the next node as the data is not contiguous and the next node can be present anywhere in the memory.
因此,我们可以使用链表来存储数据,因为它不需要连续内存,从而解决了碎片化问题。在链表中,数据存储在一个节点中,该节点同时存储指向下一个节点的指针,因为数据不是连续的,下一个节点可以位于内存中的任何位置。
333. Write a program to perform Binary Search on an array.
编写一个程序,在数组上执行二分搜索。
- 知识点: 算法与数据结构 (标签: interviewbit, tcs-nqt, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Tata Consultancy Services
- id: 69b37c7558d557c902bc896c | 官方: 否 | 付费: 否
答案:
The binary search algorithm is used to find an element in a sorted array. It is an optimized searching algorithm as the linear search scans all the elements of the array and the searching time for the linear search thus becomes O(N). However, the searching time of Binary Search is O(log2N). This is because in an average case, only log2N elements of an array are compared. We start by checking the middle element of the array. If the middle element of the array is our answer, we have found the element. If the number that we are searching for is greater than the middle element, it will be on the right half of the array as the array is sorted. So, apply binary search on the right half. If the number that we are searching for is smaller than the middle element of the array, we will apply the binary search on the left half of the array. Following is the C++ program for binary search.
二分搜索算法用于在已排序数组中查找元素。它是一种优化的搜索算法,因为线性搜索会扫描数组中的所有元素,因此线性搜索的搜索时间变为O(N)。然而,二分搜索的搜索时间为O(log2N)。这是因为在平均情况下,数组中只有log2N个元素会被比较。我们首先检查数组的中间元素。如果数组的中间元素就是我们的答案,我们就找到了该元素。如果要搜索的数字大于中间元素,由于数组已排序,它将在数组的右半部分。因此,对该右半部分应用二分搜索。如果要搜索的数字小于数组的中间元素,我们将对数组的左半部分应用二分搜索。以下是二分搜索的C++程序。
C++ Program for Binary Search
C++二分搜索程序
include
include
include
using namespace std;
using namespace std;
int binary_search(int arr[], int n,int target) {
int binary_search(int arr[], int n,int target) {
int lo = 0;
int lo = 0;
int hi = n-1;
int hi = n-1;
while(lo <= hi) {
while(lo <= hi) {
int mid = lo + (hi-lo)/2;
int mid = lo + (hi-lo)/2;
if(arr[mid] == target) return mid;
if(arr[mid] == target) return mid;
else if(arr[mid] < target) lo = mid + 1;
else if(arr[mid] < target) lo = mid + 1;
else hi = mid -1;
else hi = mid -1;
}
return -1;
return -1;
}
int main() {
int main() {
// Your code goes here;
// 你的代码写在这里;
int arr[] = {10,12,25,36,42,58,97};
int arr[] = {10,12,25,36,42,58,97};
if(binary_search(arr,7,12) == -1) {
if(binary_search(arr,7,12) == -1) {
cout<<"Element was not found";
cout<<"未找到元素";
} else {
} else {
cout<<"Element was found at index " << binary_search(arr,7,12);
cout<<"元素在索引 " << binary_search(arr,7,12) << " 处找到";
}
}
Output:
输出:
Element was found at index 1
元素在索引1处找到
334. What is a stack, and can ROM be used as one?
什么是栈,ROM 能否用作栈?
- 知识点: 算法与数据结构 (主题: technical-support;标签: interviewbit, technical-support, topic-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: fullstack
- id: 69b37c7958d557c902bc8ba5 | 官方: 否 | 付费: 否
答案:
The content of the program counter and general-purpose registers are saved in the stack, which is a piece of RAM. Because ROM cannot be written on, it cannot be used as a stack.
程序计数器和通用寄存器的内容保存在栈中,栈是 RAM 的一部分。由于 ROM 不可写,它不能用作栈。
335. What are B-trees Data structures?
什么是B树数据结构?
- 知识点: 算法与数据结构 (标签: interviewbit, tiger-analytics, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Tiger Analytics
- id: 69b37c7c58d557c902bc8d98 | 官方: 否 | 付费: 否
答案:
In computer science and database systems, self-balancing search tree data structures known as B-trees are frequently employed. Large amounts of data can be stored and retrieved effectively with B-trees by reducing the number of disc accesses necessary to reach any given element.
在计算机科学和数据库系统中,经常使用称为B树的自平衡搜索树数据结构。通过减少访问任何给定元素所需的磁盘访问次数,B树可以有效地存储和检索大量数据。
An example of a multi-level index is a B-tree, which stores data in a hierarchical structure with a fraction of the data at each level. A defined number of keys and pointers are present in each node of the B-tree, and the keys are arranged to facilitate efficient searching and retrieval.
多级索引的一个例子是B树,它以分层结构存储数据,每一层只包含一部分数据。B树的每个节点都包含一定数量的键和指针,这些键的排列方式便于高效搜索和检索。
The degree, or the maximum number of offspring that each node can have, determines the structure of a B-tree. A B-tree of degree m has the following properties:
度(即每个节点可以拥有的最大子节点数)决定了B树的结构。度为m的B树具有以下性质:
Each node has at most m children. 2. Each node, except for the root node, has at least ceil(m/2) children. 3. The root node has at least 2 children. 4. All leaves are at the same level.
- 每个节点最多有m个子节点。 2. 除了根节点外,每个节点至少有ceil(m/2)个子节点。 3. 根节点至少有2个子节点。 4. 所有叶子节点都在同一层。
B-trees are typically used in applications that require large amounts of data to be stored and accessed efficiently, such as database systems and file systems. B-trees are particularly well-suited to these applications because they minimize the number of disk accesses required to access any given element, which can significantly improve performance. B-trees are also self-balancing, which means that the structure of the tree is automatically adjusted as data is added or removed to ensure that the tree remains balanced and efficient.
B树通常用于需要高效存储和访问大量数据的应用程序,例如数据库系统和文件系统。B树特别适合这些应用,因为它最小化访问任何给定元素所需的磁盘访问次数,从而显著提高性能。B树也是自平衡的,这意味着随着数据的添加或删除,树的结构会自动调整,以确保树保持平衡和高效。
336. How do you represent a graph in computer memory, and how does it affect the performance of Topological Sorting algorithm?
如何在计算机内存中表示图,以及这会如何影响拓扑排序算法的性能?
- 知识点: 算法与数据结构 (标签: interviewbit, tiger-analytics, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Tiger Analytics
- id: 69b37c7c58d557c902bc8d9b | 官方: 否 | 付费: 否
答案:
An adjacency matrix or an adjacency list are two methods that a graph can be stored in computer memory.
图可以通过邻接矩阵或邻接表这两种方法存储在计算机内存中。
A 2D array known as an adjacency matrix is used to store connections between graph vertices. The values in the matrix show whether there is an edge between two vertices, while the rows and columns of the matrix stand in for vertices. The matrix can be implemented as a 2D array in memory, where the amount of memory used for each element is fixed. When applied to an adjacency matrix, Topological Sorting has an O(V^2) time complexity, where V is the number of vertices in the graph.
称为邻接矩阵的二维数组用于存储图顶点之间的连接。矩阵中的值表示两个顶点之间是否存在边,而矩阵的行和列代表顶点。矩阵可以在内存中实现为二维数组,其中每个元素使用的内存量是固定的。当应用于邻接矩阵时,拓扑排序的时间复杂度为O(V^2),其中V是图中的顶点数。
An adjacency list is a collection of linked lists used to store links between graph vertices. The edges related to one vertex are shown in each linked list. An array of linked lists in memory can be used to implement the adjacency list, with the amount of memory needed for each linked list inversely proportional to the number of edges connected to the vertex. Topological sorting on an adjacency list has a temporal complexity of O(V+E), where E is the number of edges in the graph.
邻接表是用于存储图顶点之间链接的链表集合。每个链表显示与一个顶点相关的边。内存中的链表数组可用于实现邻接表,每个链表所需的内存量与连接到该顶点的边数成反比。在邻接表上进行拓扑排序的时间复杂度为O(V+E),其中E是图中的边数。
The effectiveness of Topological Sorting algorithms can be impacted by the graph representation chosen. When the network is thick, an adjacency matrix is more effective because it requires a constant amount of time to determine if two vertices are connected by an edge.
拓扑排序算法的效率会受到所选择的图表示方式的影响。当网络较稠密时,邻接矩阵更有效,因为它只需要常量时间来确定两个顶点之间是否有边连接。
However, for sparse graphs, an adjacency list is more efficient as it requires less memory and allows faster access to vertices and edges. Therefore, the choice of graph representation depends on the properties of the graph and the specific requirements of the Topological Sorting algorithm.
然而,对于稀疏图,邻接表更高效,因为它需要更少的内存,并且允许更快地访问顶点和边。因此,图表示方式的选择取决于图的属性和拓扑排序算法的特定要求。
337. Can you explain the concept of recursion in programming, and provide an example of a recursive function?
你能解释编程中的递归概念,并给出一个递归函数的示例吗?
- 知识点: 算法与数据结构 (标签: interviewbit, tiger-analytics, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Tiger Analytics
- id: 69b37c7d58d557c902bc8dc8 | 官方: 否 | 付费: 否
答案:
Recursion is a programming technique in which a function calls itself in order to solve a problem. The idea is to break down a problem into smaller sub-problems, and then solve each sub-problem by calling the function recursively until a base case is reached.
递归是一种编程技术,其中函数调用自身来解决问题。其思想是将一个问题分解为较小的子问题,然后通过递归调用函数来解决每个子问题,直到到达基本情况。
An example of a recursive function to calculate the factorial of a positive integer is:
一个计算正整数阶乘的递归函数示例是:
def factorial(n):
def factorial(n):
if n == 0:
if n == 0:
return 1
return 1
else:
否则:
return n * factorial(n-1)
return n * factorial(n-1)
In this function, we first check if the input n is equal to 0, which is our base case. If it is, we return 1 since the factorial of 0 is 1. Otherwise, we calculate the factorial of n-1 by calling the factorial function recursively and multiplying it by n to get the factorial of n.
在这个函数中,我们首先检查输入 n 是否等于 0,这是我们的基本情况。如果是,我们返回 1,因为 0 的阶乘是 1。否则,我们通过递归调用 factorial 函数来计算 n-1 的阶乘,并将其乘以 n 得到 n 的阶乘。
For example, if we call factorial(5), the function will call itself with the input 4, then 3, then 2, then 1, until it reaches the base case of factorial(0). At this point, it will start returning the factorial of each number in the sequence, multiplying it by the next number until it reaches the final result of 120, which is the factorial of 5.
例如,如果我们调用 factorial(5),该函数会以输入 4、然后 3、然后 2、然后 1 调用自身,直到达到基本情况 factorial(0)。此时,它将开始返回序列中每个数字的阶乘,将其与下一个数字相乘,直到达到最终结果 120,即 5 的阶乘。
Recursive functions can be very powerful and can make complex problems easier to solve by breaking them down into smaller, more manageable sub-problems. However, it's important to make sure that the recursive function has a base case to avoid infinite recursion, which can cause the program to crash or hang.
递归函数可以非常强大,通过将复杂问题分解为更小、更易管理的子问题,可以使它们更容易解决。然而,重要的是要确保递归函数有一个基本情况以避免无限递归,无限递归可能导致程序崩溃或挂起。
338. What is the difference between a stack and a queue data structure, and when would you use each one?
栈和队列数据结构之间有什么区别,以及每种结构在什么情况下会使用?
- 知识点: 算法与数据结构 (标签: interviewbit, tiger-analytics, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Tiger Analytics
- id: 69b37c7d58d557c902bc8dd4 | 官方: 否 | 付费: 否
答案:
A stack and a queue are two common data structures used in computer programming. - Stack: A stack is a linear data structure in which elements are stored and accessed using a "last-in, first-out" (LIFO) approach. This means that the most recently added item is the first one to be removed. Stacks are used for tasks that require temporary storage of data, such as function calls, expression evaluation, or undo-redo operations. Some examples of applications that use stacks include web browsers (for the back button), compilers (for parsing expressions), and operating systems (for handling system calls).
栈和队列是计算机编程中常用的两种数据结构。- 栈:栈是一种线性数据结构,其中元素使用“后进先出”(LIFO)方法存储和访问。这意味着最近添加的项目是第一个被移除的。栈用于需要临时存储数据的任务,如函数调用、表达式求值或撤销-重做操作。使用栈的应用程序示例包括Web浏览器(用于后退按钮)、编译器(用于表达式解析)和操作系统(用于处理系统调用)。
Queue: A queue follows a "first-in, first-out" (FIFO) approach. This means that the first element added to the queue is the first one to be removed. Queues are commonly used in scenarios where you need to process items in the order they were received, such as printing jobs, message queues, or network requests. Some examples of applications that use queues include:
operating systems: for scheduling processes, e-commerce websites: for order processing and transportation systems: for handling passenger queues.操作系统:用于调度进程,电子商务网站:用于订单处理和运输系统:用于处理乘客队列。
Therefore, stacks and queues are both useful data structures for managing collections of elements. If you need to process items in the order they were added, use a queue. If you need to handle items in reverse order, use a stack.
因此,栈和队列都是管理元素集合的有用数据结构。如果您需要按添加的顺序处理项目,请使用队列。如果您需要以相反的顺序处理项目,请使用栈。
339. Write functional code for solving the problem given below: Detect whether or not a given linked list contains a cycle.
编写功能代码来解决以下问题:检测给定的链表是否包含环。
- 知识点: 算法与数据结构 (标签: interviewbit, uber, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: 优步
- id: 69b37c8358d557c902bc90ec | 官方: 否 | 付费: 否
答案:
C ++ function which solves the given Data Structures and Algorithm problem is given below:
下面给出了解决上述数据结构和算法问题的C++函数:
bool detectCycle(ListNode* root)
bool detectCycle(ListNode* root)
{
ListNode slow = root, fast = root;
ListNode slow = root, fast = root;
while (slow && fast && fast -> link) {
while (slow && fast && fast -> link) {
slow = slow->link;
slow = slow->link;
fast = fast->link->link;
fast = fast->link->link;
if (slow == fast) {
if (slow == fast) {
return true;
返回 true;
}
}
return false;
返回 false;
}
For solving this question, we can use Floyd's Approach to Find cycle in a linked list. It is stated below: - Two pointers are used for traversing the linked list.
为了解决这个问题,我们可以使用弗洛伊德算法来检测链表中的环。该算法如下:- 使用两个指针遍历链表。
- One pointer (slow) should be moved by one, while another pointer (fast) should be moved by two.
- There is a loop if these points intersect at the same node. A linked list does not have a loop if the pointers do not meet.
340. Search for a value in an m x n integer matrix matrix using an efficient algorithm.
使用一种高效的算法在一个 m x n 的整数矩阵中搜索一个值。
- 知识点: 算法与数据结构 (标签: interviewbit, virtusa, company-specific)
- 类型: technical | 难度: easy | 子类型: coding
- 分类: general
- 公司: Virtusa
- id: 69b37c8a58d557c902bc9408 | 官方: 否 | 付费: 否
答案:
The following properties must exist:
必须具备以下属性:
341. Eliminate all duplicates to head a sorted linked list, ensuring that every element appears only once. Return the linked list in order.
消除所有重复项,使排序链表只保留每个元素一次。按顺序返回链表。
- 知识点: 算法与数据结构 (标签: interviewbit, virtusa, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Virtusa
- id: 69b37c8a58d557c902bc940e | 官方: 否 | 付费: 否
答案:
We can use the two-pointer approach to solve this problem by getting the nodes that contain the duplicate value. Since the lists are already in sorted order, It becomes easy to point to the node with duplicate values. So the code solution for this problem will be -
我们可以使用双指针方法来解决这个问题,通过获取包含重复值的节点。由于链表已经有序,指向具有重复值的节点变得容易。因此,该问题的代码解决方案如下-
class Solution {
class Solution {
public ListNode deleteDuplicates(ListNode head) {
public ListNode deleteDuplicates(ListNode head) {
// if LL is empty or contains only 1 element then return LL.
// 如果链表为空或只包含一个元素,则直接返回链表。
if(head==null || head.next==null) {
if(head==null || head.next==null) {
return head;
return head;
}
// creating a dummy Head for traversing the LinkedList.
// 为遍历链表创建一个虚拟头节点。
ListNode node = head;
ListNode node = head;
while(node.next!=null) {
while(node.next!=null) {
if(node.val!=node.next.val) {
if(node.val!=node.next.val) {
// if value of current node is same as value of next node then
// 如果当前节点的值与下一个节点的值相同,则
// traverse the node forward.
// 向前遍历节点。
node = node.next;
node = node.next;
} else {
} else {
// if value of current node is same as value of next node then
// 如果当前节点的值与下一个节点的值相同,则
//connect current with next to next node.
// 将当前节点连接到下一个的下一个节点。
node.next = node.next.next;
node.next = node.next.next;
}
}
return head;
return head;
}
}
342. What do you understand about Stack Unwinding in C++?
你对C++中的栈展开(Stack Unwinding)有什么理解?
- 知识点: 算法与数据结构 / 编程语言基础 (标签: interviewbit, wipro, company-specific)
- 类型: technical | 难度: easy | 子类型: concept
- 分类: general
- 公司: Wipro
- id: 69b37c9858d557c902bc9b8e | 官方: 否 | 付费: 否
答案:
Stack Unwinding is the process of eliminating function entries from the function call stack at runtime. Exception Handling is often associated with Stack Unwinding. When an exception occurs in C++, the function call stack is searched linearly for the exception handler, and any entries before the function with the exception handler are deleted from the function call stack. If the exception is not handled in the same code, stack unwinding is required (where it is thrown).
栈展开是在运行时从函数调用栈中消除函数条目的过程。异常处理通常与栈展开相关联。当C++中发生异常时,函数调用栈会被线性搜索以寻找异常处理程序,而异常处理程序之前的任何函数条目都会从函数调用栈中删除。如果异常未在同一段代码中处理,则需要进行栈展开(在抛出异常的地方)。
343. 你如何为一个项目选择工具(Tool)和技术栈(Technology Stack)?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 (主题: system-design;标签: tech-stack, requirements, tradeoffs, budget)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 695cc0351da553795622a751 | 官方: 是 | 付费: 否
答案:
TL;DR先分析需求(Requirements)与兼容性(Compatibility),再选择能解决问题的语言(Language)/框架(Framework),参考类似项目方案,并评估成本(Cost)是否符合预算(Budget)。
招聘方希望了解你在选择技术栈(Technology Stack)时的考虑因素(Consideration Factors),你可以包含以下要点:
- 分析项目需求,并考虑兼容性要求
- 选择能够提供最佳解决方案的语言与框架
- 调研类似项目使用的技术
- 评估可能需要的付费工具成本,并确认是否符合预算
344. 什么是不可变对象(Immutable Object)?Java 中怎么创建一个不可变对象?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, oop;标签: immutable, String, wrapper)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965dbd5fa809e6d38860c63 | 官方: 是 | 付费: 否
答案:
答案不可变对象(Immutable Object)指对象一旦被创建,状态(State)就不能再改变。任何修改都会创建一个新的对象,如 String、Integer及其它包装类(Wrapper Class)。详情参见答案,一步一步指导你在 Java 中创建一个不可变的类(Immutable Class)。
345. 为什么 Java 中的 String 是不可变的(Immutable)?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, string;标签: String, immutable)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965dcf6fa809e6d38863293 | 官方: 是 | 付费: 否
答案:
答案Java 中的 String 不可变是因为 Java 的设计者认为字符串使用非常频繁,将字符串设置为不可变可以允许多个客户端(Client)之间共享相同的字符串。更详细的内容参见答案。
346. 我们能在 Switch(Switch Statement)中使用 String 吗?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, language-basics;标签: switch, String, Java 7, hashCode)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965dcf6fa809e6d38863297 | 官方: 是 | 付费: 否
答案:
答案从 Java 7 开始,我们可以在 switch case 中使用字符串,但这仅仅是一个语法糖(Syntactic Sugar)。内部实现在 switch 中使用字符串的 hash code(哈希码)。
347. Java 中 LinkedHashMap 和 PriorityQueue 的区别是什么?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, collections;标签: LinkedHashMap, PriorityQueue, ordering)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965dcf6fa809e6d38863305 | 官方: 是 | 付费: 否
答案:
答案PriorityQueue 保证最高或者最低优先级的的元素总是在队列头部,但是 LinkedHashMap 维持的顺序是元素插入的顺序(Insertion Order)。当遍历一个 PriorityQueue 时,没有任何顺序保证,但是 LinkedHashMap 课保证遍历顺序是元素插入的顺序。
348. Hashtable 与 HashMap 有什么不同之处?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, collections;标签: Hashtable, HashMap, synchronized, null key)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965dcf7fa809e6d388633f6 | 官方: 是 | 付费: 否
答案:
答案这两个类有许多不同的地方,下面列出了一部分:
a) Hashtable 是 JDK 1 遗留下来的类,而 HashMap 是后来增加的。
b)Hashtable 是同步的(Synchronized),比较慢,但 HashMap 没有同步策略,所以会更快。
c)Hashtable 不允许有个空的 key(Null Key),但是 HashMap 允许出现一个 null key(Null Key)。 更多的不同之处参见答案。
349. ArrayList(动态数组)和 HashMap(哈希映射)的默认大小(default capacity)是多少?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, collections;标签: ArrayList, HashMap, default capacity)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965dcf7fa809e6d38863406 | 官方: 是 | 付费: 否
答案:
答案在 Java 7 中,ArrayList(动态数组)的默认大小是 10 个元素,HashMap(哈希映射)的默认大小是16个元素(必须是2的幂,power of 2)。这就是 Java 7 中 ArrayList(动态数组)和 HashMap(哈希映射)类的代码片段:
// from ArrayList.java JDK 1.7 private static final int DEFAULT_CAPACITY = 10; //from HashMap.java JDK 7 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 来自 ArrayList.java JDK 1.7 private static final int DEFAULT_CAPACITY = 10; // 来自 HashMap.java JDK 7 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 即 16
350. Java 中,Comparator(比较器)与 Comparable(可比较的)有什么不同?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: java, collections;标签: Comparator, Comparable, sorting)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965de58fa809e6d388650b2 | 官方: 是 | 付费: 否
答案:
答案Comparable(可比较的)接口用于定义对象的自然顺序(natural ordering),而 comparator(比较器)通常用于定义用户定制的顺序(custom ordering)。Comparable(可比较的)总是只有一个,但是可以有多个 comparator(比较器)来定义对象的顺序。
351. Java 中如何利用泛型(generics)写一个 LRU(最近最少使用)缓存?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, generics, collections;标签: LRU, LinkedHashMap, Generics)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965e03dfa809e6d3886840e | 官方: 是 | 付费: 否
答案:
答案常见做法是用 LinkedHashMap<K,V>(有序哈希映射)(accessOrder=true)实现 LRU(最近最少使用)。构造时传入容量 capacity(容量),并重写 removeEldestEntry(移除最老条目):当 size() > capacity(容量)时返回 true 触发淘汰最久未使用的元素。为了线程安全(thread safety)可在外层加锁或使用 Collections.synchronizedMap(同步映射)包装。
352. 什么时候使用组合模式(Composite Pattern)?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 / 编程语言基础 (主题: design-patterns, oop, java;标签: Composite, Tree)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965e1cdfa809e6d3886a312 | 官方: 是 | 付费: 否
答案:
答案组合模式(Composite Pattern)使用树结构(tree structure)来展示部分与整体继承关系。它允许客户端采用统一的形式来对待单个对象和对象容器(object container)。当你想要展示对象这种部分与整体的继承关系时采用组合模式(Composite Pattern)。
353. 如何实现字符串的反转(reverse)及替换(replace)?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, string, recursion;标签: Reverse String, Recursion, StringBuilder)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965e5a4fa809e6d38872ca5 | 官方: 是 | 付费: 否
答案:
答案方法很多,可以自己写实现也可以使用String(字符串)或StringBuffer/StringBuilder(字符串缓冲区/字符串构建器)中的方法。有一道很常见的面试题是用递归(recursion)实现字符串反转(reverse),代码如下所示:
public static String reverse(String originStr) {
public static String reverse(String originStr) {
if (originStr == null || originStr.length() <= 1)
if (originStr == null || originStr.length() <= 1)
return originStr;
return originStr;
return reverse(originStr.substring(1)) + originStr.charAt(0);
return reverse(originStr.substring(1)) + originStr.charAt(0);
}
354. 怎样将GB2312(简体中文字符集)编码的字符串转换为ISO-8859-1(拉丁字符集)编码的字符串?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, encoding, string;标签: Encoding, GB2312, ISO-8859-1)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965e5a4fa809e6d38872ca9 | 官方: 是 | 付费: 否
答案:
答案代码如下所示:
String(字符串) s1 = "你好";
String s2 = new String(s1.getBytes("GB2312"), "ISO-8859-1");
String s2 = new String(s1.getBytes("GB2312"), "ISO-8859-1");
355. == 和 equals(相等)的区别是什么?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java, oop;标签: ==, equals, String, Object)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965e90cfa809e6d38877f7a | 官方: 是 | 付费: 否
答案:
答案== 解读
对于基本类型(primitive type)和引用类型(reference type)== 的作用效果是不同的,如下所示:
基本类型(Primitive Type):比较的是值是否相同;
引用类型(Reference Type):比较的是引用是否相同;
代码示例:
String x = "string";
String x = "string";
String y = "string";
String y = "string";
String z = new String("string");
String z = new String("string");
System.out.println(x==y); // true
System.out.println(x==y); // 真
System.out.println(x==z); // false
System.out.println(x==z); // 假
System.out.println(x.equals(y)); // true
System.out.println(x.equals(y)); // 真
System.out.println(x.equals(z)); // true代码解读:因为 x 和 y 指向的是同一个引用,所以 == 也是 true,而 new String()方法则重写开辟了内存空间,所以 == 结果为 false,而 equals 比较的一直是值,所以结果都为 true。
equals 解读
equals 本质上就是 ==,只不过 String 和 Integer 等重写了 equals 方法,把它变成了值比较。看下面的代码就明白了。
首先来看默认情况下 equals 比较一个有相同值的对象,代码如下:
class Cat {
class Cat {
public Cat(String name) {
public Cat(String name) {
this.name = name;
this.name = name;
}
private String name;
private String name;
public String getName() {
public String getName() {
return name;
return name;
}
public void setName(String name) {
public void setName(String name) {
this.name = name;
this.name = name;
}
}
Cat c1 = new Cat;
Cat c1 = new Cat;
Cat c2 = new Cat;
Cat c2 = new Cat;
System.out.println(c1.equals(c2)); // false输出结果出乎我们的意料,竟然是 false?这是怎么回事,看了 equals 源码就知道了,源码如下:
public boolean equals(Object obj) {
public boolean equals(Object obj) {
return (this == obj);
return (this == obj);
}原来 equals 本质上就是 ==。
那问题来了,两个相同值的 String 对象,为什么返回的是 true?代码如下:
String s1 = new String("老王");
String s2 = new String("老王");
System.out.println(s1.equals(s2)); // true同样的,当我们进入 String 的 equals 方法,找到了答案,代码如下:
public boolean equals(Object anObject) {
public boolean equals(Object anObject) {
if (this == anObject) {
if (this == anObject) {
return true;
返回 true;
}
if (anObject instanceof String) {
if (anObject instanceof String) {
String anotherString = (String)anObject;
String anotherString = (String)anObject;
int n = value.length;
int n = value.length;
if (n == anotherString.value.length) {
if (n == anotherString.value.length) {
char v1[] = value;
char v1[] = value;
char v2[] = anotherString.value;
char v2[] = anotherString.value;
int i = 0;
int i = 0;
while (n-- != 0) {
while (n-- != 0) {
if (v1[i] != v2[i])
if (v1[i] != v2[i])
return false;
返回 false;
i++;
i++;
}
return true;
返回 true;
}
}
return false;
返回 false;
}原来是 String 重写了 Object 的 equals 方法,把引用比较(Reference Comparison)改成了值比较(Value Comparison)。
总结:== 对于基本类型(Primitive Type)来说是值比较,对于引用类型(Reference Type)来说是比较的是引用;而 equals 默认情况下是引用比较,只是很多类重新了 equals 方法,比如 String、Integer 等把它变成了值比较,所以一般情况下 equals 比较的是值是否相等。
356. 下面示例中创建了多少个 String 对象?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: String Pool, String Objects)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965f3d9fa809e6d3888bac6 | 官方: 是 | 付费: 否
答案:
答案在上述示例中创建了两个 java.lang.String 对象。s1 和 s3 引用的是同一个对象。
357. 为什么 Java(Java) 中的 String(String) 被称为不可变(Immutable)?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: String, Immutable)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965f3d9fa809e6d3888bacb | 官方: 是 | 付费: 否
答案:
答案在 Java(Java) 中,字符串对象被称为不可变(immutable),因为一旦给字符串赋值,就不能更改;如果“更改”,实际上会创建一个新对象。
下面示例中,引用 str(str) 指向值为 "Value one" 的字符串对象:
String str="Value One";
String str="Value One";
当给它赋一个新值时,会创建一个新的 String(String) 对象,引用会移动到新对象:
str="New Value";
str="New Value";
358. 数组(array)和 Vector(Vector) 的区别是什么?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: Array, Vector, Collections)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965f3d9fa809e6d3888bacf | 官方: 是 | 付费: 否
答案:
答案数组将相同原始类型的数据组合在一起,并且是静态的;而 Vector(Vector) 是动态的,并且可以保存不同数据类型的数据。
359. 当数据需要大量修改时,应该优先使用 String(String) 还是 StringBuffer(StringBuffer)?为什么?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: String, StringBuffer, Immutability)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965f590fa809e6d3888f488 | 官方: 是 | 付费: 否
答案:
答案由于 StringBuffer(StringBuffer) 是动态的,我们可以改变 StringBuffer(StringBuffer) 对象的值;而 String(String) 是不可变的(immutable)。因此,当数据需要频繁修改时,使用 StringBuffer(StringBuffer) 更合适。
如果在这种场景使用 String(String),每次数据变更都会创建一个新的 String(String) 对象,这会带来额外开销。
360. equals()(equals()) 方法和 == 运算符的比较有什么区别?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: equals, ==, String)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6965f595fa809e6d3888fb11 | 官方: 是 | 付费: 否
答案:
答案在 Java(Java) 中,equals()(equals()) 用于比较两个字符串对象的内容(contents),如果值相同则返回 true;而 == 运算符比较的是两个字符串对象的引用(references)。
下面示例中,equals()(equals()) 返回 true(因为值相同),而 == 返回 false(因为引用不同):
public class equalsTest {
public class equalsTest {
public static void main(String args[]) {
public static void main(String args[]) {
String str1 = new String("Hello World");
String str1 = new String("Hello World");
String str2 = new String("Hello World");
String str2 = new String("Hello World");
if (str1.equals(str2))
if (str1.equals(str2))
{ // this condition is true
{ // 此条件为真
System.out.println("str1 and str2 are equal in terms of values");
System.out.println("str1和str2在值上是相等的");
}
if (str1 == str2) {
if (str1 == str2) {
//This condition is true
//此条件为真
System.out.println("Both strings are referencing same object");
System.out.println("两个字符串引用的是同一个对象");
} else
} else
{
// This condition is NOT true
// 此条件不为真
System.out.println("Both strings are referencing different objects");
System.out.println("两个字符串引用的是不同的对象");
}
}
}
361. 集合中有哪些 List(List)?分别有什么特点?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: List, ArrayList, Vector, LinkedList)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69660513fa809e6d388b2fd3 | 官方: 是 | 付费: 否
答案:
答案List(List) 中的值按索引位置添加,因此是按索引有序的;允许重复元素。
ArrayList:
ArrayList:
- 迭代快,随机访问快
- 是按索引有序(ordered),但不保证排序(not sorted)
实现 Random Access 接口
示例:
public class Fruits{public class Fruits{
public static void main (String [ ] args){
public static void main (String [ ] args){
ArrayListnames = new ArrayList ();
ArrayListnames = new ArrayList ();
names.add ("apple");
names.add ("apple");
names.add ("cherry");
names.add ("cherry");
names.add ("kiwi");
names.add ("kiwi");
names.add ("banana");
names.add ("banana");
names.add ("cherry");
names.add ("cherry");
System.out.println (names);
System.out.println (names);
}
}
// Output:
// 输出:
// [Apple, cherry, kiwi, banana, cherry]从输出可见,ArrayList(ArrayList) 维护插入顺序且允许重复,但不排序。
Vector:
Vector:- 与 ArrayList 类似
- Vector 的方法是同步的(synchronized)
- 线程安全(Thread safety)
- 也实现 Random Access
线程安全通常会带来性能损耗
示例:
public class Fruit {public class Fruit {
public static void main (String [ ] args){
public static void main (String [ ] args){
Vectornames = new Vector ( );
Vectornames = new Vector ( );
names.add ("cherry");
names.add ("cherry");
names.add ("apple");
names.add ("apple");
names.add ("banana");
names.add ("banana");
names.add ("kiwi");
names.add ("kiwi");
names.add ("apple");
names.add ("apple");
System.out.println ("names");
System.out.println ("names");
}
}
// Output:
// 输出:
// [cherry,apple,banana,kiwi,apple]Vector 同样维护插入顺序并允许重复。
LinkedList:
LinkedList:- 元素是双向链表连接
- 性能比 ArrayList 慢
- 适合插入和删除
Java 5.0 支持常见队列方法 peek()、Pool()、Offer() 等
示例:
public class Fruit {public class Fruit {
public static void main (String [ ] args){
public static void main (String [ ] args){
Linkedlistnames = new linkedlist ( ) ;
Linkedlistnames = new linkedlist ( ) ;
names.add("banana");
names.add("banana");
names.add("cherry");
names.add("cherry");
names.add("apple");
names.add("apple");
names.add("kiwi");
names.add("kiwi");
names.add("banana");
names.add("banana");
System.out.println (names);
System.out.println (names);
}
}
// Output:
// 输出:
// [ banana,cherry,apple,kiwi,banana]LinkedList 维护插入顺序并允许重复。
362. 请解释 Map 以及 Map 的类型。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: Map, HashMap, Hashtable, LinkedHashMap, TreeMap)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69660860fa809e6d388bce77 | 官方: 是 | 付费: 否
答案:
答案Map 关注唯一标识符。我们可以将一个唯一的 key 映射到一个特定的 value。它是 key/value 键值对。我们可以基于 key 查找 value。与 Set 类似,Map 也使用 equals() 方法来判断两个 key 是否相同或不同。
HashMap:
HashMap:
- 无序且不排序的 Map。
- 当我们不关心顺序时,HashMap 是一个不错的选择。
允许一个 null key 和多个 null value。
示例:
Public class Fruit{公共类 Fruit{
Public static void main(String[ ] args){
公共静态主方法 main(String[ ] args){
HashMap<Sting,String> names =new HashMap<String,String>( );
HashMap<Sting,String> names =new HashMap<String,String>( );
names.put(“key1”,“cherry”);
names.put(“key1”,“cherry”);
names.put (“key2”,“banana”);
names.put (“key2”,“banana”);
names.put (“key3”,“apple”);
names.put (“key3”,“apple”);
names.put (“key4”,“kiwi”);
names.put (“key4”,“kiwi”);
names.put (“key1”,“cherry”);
names.put (“key1”,“cherry”);
System.out.println(names);
System.out.println(names);
}
}Output:
}输出:
{key2 =banana, key1=cherry, key4 =kiwi, key3= apple}Map 不允许重复 key。
不维护插入顺序且不排序。
HashTable:
HashTable:- 与 Vector 类似,该类的方法是同步的(synchronized)。
- 线程安全,因此性能更慢。
不允许任何 null。
示例:
public class Fruit{public class Fruit{
public static void main(String[ ]args){
public static void main(String[ ]args){
Hashtable<Sting,String> names =new Hashtable<String,String>( );
Hashtable<Sting,String> names =new Hashtable<String,String>( );
names.put(“key1”,“cherry”);
names.put(“key1”,“cherry”);
names.put(“key2”,“apple”);
names.put(“key2”,“apple”);
names.put(“key3”,“banana”);
names.put(“key3”,“banana”);
names.put(“key4”,“kiwi”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
names.put(“key2”,“orange”);
System.out.println(names);
System.out.println(names);
}
}Output:
}输出:
{key2=apple, key1=cherry,key4=kiwi, key3=banana}不允许重复 key。
LinkedHashMap:
LinkedHashMap:- 维护插入顺序。
- 比 HashMap 慢。
可以获得更快的迭代。
示例:
public class Fruit{public class Fruit{
public static void main(String[ ] args){
public static void main(String[ ] args){
LinkedHashMap<Sting,String> names =new LinkedHashMap<String,String>( );
LinkedHashMap<Sting,String> names =new LinkedHashMap<String,String>( );
names.put(“key1”,“cherry”);
names.put(“key1”,“cherry”);
names.put(“key2”,“apple”);
names.put(“key2”,“apple”);
names.put(“key3”,“banana”);
names.put(“key3”,“banana”);
names.put(“key4”,“kiwi”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
names.put(“key2”,“orange”);
System.out.println(names);
System.out.println(names);
}
}Output:
}输出:
{key2=apple, key1=cherry,key4=kiwi, key3=banana}不允许重复 key。
TreeMap:
TreeMap:- Sorted Map(有序 Map)。
像 TreeSet 一样,我们可以通过构造函数构建排序规则。
示例:
public class Fruit{public class Fruit{
public static void main(String[ ]args){
public static void main(String[ ]args){
TreeMap<Sting,String> names =new TreeMap<String,String>( );
TreeMap<Sting,String> names =new TreeMap<String,String>( );
names.put(“key1”,“cherry”);
names.put(“key1”,“cherry”);
names.put(“key2”,“banana”);
names.put(“key2”,“banana”);
names.put(“key3”,“apple”);
names.put(“key3”,“apple”);
names.put(“key4”,“kiwi”);
names.put(“key4”,“kiwi”);
names.put(“key2”,“orange”);
names.put(“key2”,“orange”);
System.out.println(names);
System.out.println(names);
}
}Output:
}输出:
{key1=cherry, key2=banana, key3 =apple, key4=kiwi}它会基于 key 以升序排序。不允许重复 key。
363. 解释一下异常传播(Exception Propagation)。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: Exception Propagation, Call Stack)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69660863fa809e6d388bd1dc | 官方: 是 | 付费: 否
答案:
答案异常首先从栈顶的方法抛出。如果该方法未捕获异常,则异常会弹出到上一层方法,如此继续,直到被捕获或到达最外层。
这称为异常传播(Exception propagation)。
示例:
public class Manipulation{
public class Manipulation{
public static void main(String[] args){
public static void main(String[] args){
add();
add();
}
public void add(){
public void add(){
addition();
addition();
}
}从上面的示例中,栈(stack)调用关系如图所示(略)。如果 addition() 方法发生异常(exception)但未捕获,则会移动到 add(),再移动到 main(),并停止执行流程,这称为异常传播(exception propagation)。
364. Python 中的 split()、sub() 和 subn() 方法是什么?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: python, regex;标签: re, regex, string)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969ab753695832c6e08a4f0 | 官方: 是 | 付费: 否
答案:
答案- 这些方法属于 Python 正则表达式(RegEx)的 ‘re’ 模块,用于修改字符串(string)。
- split():用于把给定字符串拆分为一个列表。
- sub():用于找到正则模式匹配的子串,并用另一个字符串替换该匹配子串。
- subn():与 sub() 类似,但会返回新的字符串,以及替换发生的次数。
365. Python 数组(array)和 Python 列表(list)有什么区别?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: python, array, list;标签: array, list, data-structure)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969ad483695832c6e08e08f | 官方: 是 | 付费: 否
答案:
答案在 Python 里,我们口头说的“array(数组)”很多时候其实指的是 list(列表)。这是因为 list 对 Python 来说非常基础,就像 array 对很多底层语言一样基础。
不过,Python 确实也有一个名为 ‘array’ 的模块,只是它在实际使用或讨论中相对少见。下面是 Python arrays 和 Python lists 的一些差异:
Arrays(数组)Lists(列表)数组只能存储同质数据(同一种类型的数据)。列表可以存储异质且任意类型的数据。由于只能存一种数据类型,数组只为一种类型的对象分配内存,因此通常数组比列表占用更少的内存。列表可以存储多种数据类型,因此通常比数组需要更多内存。数组长度在创建时就是固定的,因此不能再添加更多元素。列表长度不固定,因此可以向其中追加元素。
366. Python 里可以写多行注释(multiline comments)吗?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: python;标签: comments, docstring)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969ad4d3695832c6e08e4c2 | 官方: 是 | 付费: 否
答案:
答案Python 并没有像其他编程语言那样提供一种“专门的语法”来写多行注释。不过,开发者可以使用三引号字符串(docstrings)来写多行注释;当 docstring 不是作为方法/函数中的第一条语句时,它会被 Python 解析器(parser)忽略。
367. Python 中的 docstring(文档字符串)是什么?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: python;标签: docstring, comments)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969af513695832c6e091549 | 官方: 是 | 付费: 否
答案:
答案Python 允许开发者使用 documentation strings(docstrings,文档字符串)为方法/函数加入描述(或快速备注)。Docstring 与普通注释不同:普通注释会被 Python 解释器(interpreter)完全忽略;而当 docstring 作为方法或函数中的第一条语句时,Python 的文档字符串可以在运行时通过点运算符(dot operator)访问。
368. 编写一个 Python 程序:在不使用迭代方法的情况下,判断给定字符串是否为回文(palindrome)。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: python, string;标签: palindrome, string)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969af563695832c6e0917bc | 官方: 是 | 付费: 否
答案:
答案注:回文(palindrome)指正着读和倒着读都一样的单词、短语或序列,例如 madam、nurses run 等。
def fun(string):
def fun(string):
s1 = string
s1 = string
s = string[::-1]
s = string[::-1]
if(s1 == s):
if(s1 == s):
return true
返回 true
else:
否则:
return false
return false
print(fun("madam"))
print(fun("madam"))
369. 编写一个 Python 程序:计算一个数字列表的总和。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: python, recursion;标签: list, sum, recursion)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969af573695832c6e0917e3 | 官方: 是 | 付费: 否
答案:
答案def sum(num):
if len(num) == 1:
if len(num) == 1:
return num[0] #with only one element in the list, sum result will be equal to the element.
return num[0] #只有列表中的一个元素时,求和结果将等于该元素。
else:
否则:
return num[0] + sum(num[1:])
return num[0] + sum(num[1:])
print(sum([2, 4, 5, 6, 7]))输出:
24
370. 什么是算法(Algorithm)?为什么需要算法(Algorithm)?
- 知识点: 算法与数据结构 (主题: algorithms, analysis;标签: algorithm, complexity)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969b19e3695832c6e0963bc | 官方: 是 | 付费: 否
答案:
答案算法(Algorithm)是一种定义良好的计算过程:它接收一些值或一组值作为输入,并产生一组值或某些值作为输出。
算法(Algorithm)的需求:
算法(Algorithm)为设计者提供问题的基本思路以及解决问题的方法。使用算法(Algorithm)的一些原因如下:
- 算法可以提升现有技术/方法的效率。
- 用于与其他技术相比,评估算法性能。
- 为设计者提供对问题需求与目标的清晰描述。
- 帮助更合理地理解程序流程。
- 衡量方法在不同情况下(最好、最坏、平均)的表现。
- 识别算法所需资源(输入/输出、内存)以及循环等。
- 帮助度量与分析问题的时间复杂度与空间复杂度。
- 降低设计成本。
371. 什么是算法复杂度(Algorithm Complexity)?
- 知识点: 算法与数据结构 (主题: algorithms, complexity;标签: time-complexity, space-complexity)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969b1a03695832c6e0966ba | 官方: 是 | 付费: 否
答案:
答案算法复杂度(Algorithm Complexity)用于对比算法(Algorithm)相对其他方案的效率,关注的是:当待处理数据集增大时,执行时间如何增长。算法的计算复杂度(Computational Complexity)在计算机领域非常重要。
它非常适合用“所需时间的相对大小”或“所需空间的相对大小”来对算法(Algorithm)进行分类,并把时间/空间需求的增长描述为输入规模的函数。
时间复杂度(Time Complexity):时间复杂度(Time Complexity)是程序运行时间关于输入规模的函数。
空间复杂度(Space Complexity):空间复杂度(Space Complexity)从算法(Algorithm)完成任务所需的空间大小来分析算法(Algorithm)。在计算机发展的早期(存储空间有限)空间复杂度(Space Complexity)分析非常关键。如今由于计算机空间更充足,空间问题较少出现。复杂度(Complexity)通常有以下分析类型:
最坏情况(Worst Case):f(n) —— 在规模为 n 的任意输入实例中,算法(Algorithm)所需步骤的最大值。
最好情况(Best Case):f(n) —— 在规模为 n 的任意输入实例中,算法(Algorithm)所需步骤的最小值。
平均情况(Average Case):f(n) —— 在规模为 n 的任意输入实例中,算法(Algorithm)所需步骤的平均值。
372. 写一个算法(Algorithm)来反转字符串(例如:"uhsnamiH" 反转为 "Himanshu")。
- 知识点: 算法与数据结构 (主题: algorithms, strings;标签: string, reverse)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969b1a03695832c6e0966bd | 官方: 是 | 付费: 否
答案:
答案字符串反转算法(String Reversal Algorithm)。
- 步骤1:开始
- 步骤2:取两个变量 i 和 j
- 步骤3:令 j = length(string) - 1,将 j 设置为最后一个位置
- 步骤4:令 i 指向 string[0],即第一个字符
- 步骤5:交换 string[i] 与 string[j]
- 步骤6:i 加 1
- 步骤7:j 加 1
- 步骤8:如果 i > j,则转到步骤3
- 步骤9:停止
373. 写一个算法(Algorithm)在有序链表(Sorted Linked List)中插入一个节点(Node)。
- 知识点: 算法与数据结构 (主题: data-structures, linked-list;标签: linked-list, insertion)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969b1a33695832c6e09693e | 官方: 是 | 付费: 否
答案:
答案在有序链表(Sorted Linked List)中插入节点(Node)的算法(Algorithm)。
情况1:
如果链表(Linked List)为空,则将该节点设为 head(Head Node)并返回。
New_node-> Next= head;
- New_node-> Next= head;
- Head=New_node情况2:
在中间插入新节点(Insert New Node) While( P!= insert position)
- While( P!= insert position)
- {
P= p-> Next;
- P= p-> Next;
- }
Store_next=p->Next;
- Store_next=p->Next;
P->Next= New_node;
- P->Next= New_node;
- New_Node->Next = Store_next;情况3:
在末尾插入节点(Insert Node at End) While (P->next!= null)
- While (P->next!= null)
- {
P= P->Next;
- P= P->Next;
- }
P->Next = New_Node;
- P->Next = New_Node;
New_Node->Next = null;
- New_Node->Next = null;
374. 什么是渐进记号(Asymptotic Notations)?
- 知识点: 算法与数据结构 (主题: algorithms, complexity;标签: big-o, theta, omega)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969b1a33695832c6e096945 | 官方: 是 | 付费: 否
答案:
答案渐进分析(Asymptotic Analysis)用于衡量算法效率(Algorithm Efficiency),它不依赖机器相关常数(Machine-Dependent Constant),并避免仅通过“耗时”直接比较算法。渐进记号(Asymptotic Notation)是一种数学工具,用于在渐进分析中表示算法的时间复杂度(Time Complexity)。
最常用的三种渐进记号如下:
θ 记号(Theta Notation)
θ 记号定义了精确的渐进行为(Asymptotic Behavior):通过对函数进行上下界(Upper Bound and Lower Bound)同时约束来描述其行为。获得表达式 Theta 记号的一个方便方法是:丢弃低阶项(Lower-Order Term)并忽略首项系数(Leading Coefficient)。
Big O 记号(Big O Notation)
Big O 记号从上界对函数进行约束,定义了算法的上界(Upper Bound)。以插入排序(Insertion Sort)为例:最好情况下是线性时间(Linear Time),最坏情况下是二次时间(Quadratic Time)。插入排序的时间复杂度是 O(n2)。当我们只掌握算法时间复杂度上界时,它非常有用。
Ω 记号(Omega Notation)
类似 Big O 记号提供渐进上界,Ω 记号提供函数的渐进下界(Asymptotic Lower Bound)。当我们掌握算法时间复杂度下界时,它很有用。
375. 解释冒泡排序算法(Bubble Sort Algorithm)。
- 知识点: 算法与数据结构 (主题: algorithms, sorting;标签: bubble-sort, sorting)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969b1a53695832c6e096b1b | 官方: 是 | 付费: 否
答案:
答案冒泡排序(Bubble Sort)是所有排序算法(Sorting Algorithm)中最简单的一种。它通过不断交换相邻元素(当它们顺序错误时)来完成排序。
例如:
(72538) 作为待排序数组(Array)。
第一趟:
- (72538) -> (27538) 交换 7 和 2。
- (27538) -> (25738) 交换 7 和 5
- (25738) -> (25378) 交换 7 和 3。
- (25378) -> (25378) 因为 7第二趟:
- (25378) -> (25378) 因为 2 (23578) 交换 3 和 5。
- (23578) -> (23578) 因为 5 (23578) 因为 7此时,已排序的元素为 (23578)。
376. 在 Java 中如何不使用临时变量(Temporary Variable)交换两个整数(Integer)?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: algorithms, bitwise, java;标签: swap, xor, overflow)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969b1a73695832c6e096cff | 官方: 是 | 付费: 否
答案:
答案这是一个非常常见的“技巧题”。解决方法很多,但必要条件是:不能使用临时变量(Temporary Variable)交换。如果你能考虑到整数溢出(Integer Overflow)并给出对应方案,会给面试官留下很好的印象。
假设有两个整数(Integer) i 和 j,i=7、j=8,如何在不使用第三个变量的情况下交换它们?我们需要用 Java 的编程结构来完成。可以通过加减乘除等数学运算来交换,但可能会带来整数溢出(Integer Overflow)问题。
使用加法与减法(Addition and Subtraction):
a= a + b;
- a= a + b;
b=a - b; // this will act like (a+b)-b, now b is equal to a.
- b=a - b; // 这将像(a+b)-b 一样作用,现在 b 等于 a。
- a=a - b; // (a+b)-a, now, a is equal to b.这是一个不错的技巧。但如果加法结果超过 int 原生类型(Primitive Type)的最大值(Integer.MAX_VALUE),或者减法结果小于最小值(Integer.MIN_VALUE),就会发生整数溢出(Integer Overflow)。
使用 XOR 技巧(XOR Trick):
另一种不用第三个变量(Temp Variable)交换两个整数(Integer)的方法,被广泛认为是最好的解决方案,因为它也适用于不处理整数溢出(Integer Overflow)的语言(例如 C、C++)。Java 支持多种位运算符(Bitwise Operator),其中之一是 XOR(用 ^ 表示)。 x=x^y;
- x=x^y;
y=x^y;
- y=x^y;
x=x^y;
- x=x^y;
377. 什么是哈希表(Hash Table)?如何用它在字典(Dictionary)中找出所有变位词(Anagram)?
- 知识点: 算法与数据结构 (主题: data-structures, hash-table;标签: hash-table, anagram)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969b1a73695832c6e096d02 | 官方: 是 | 付费: 否
答案:
答案哈希表(Hash Table)是一种数据结构(Data Structure),用于把任意类型的 key 映射到 value 并存储。哈希表通过哈希函数(Hash Function)得到数组索引(Array Index)。索引用来存放元素。我们用哈希函数把每个可能元素分配到某个桶(Bucket)。多个 key 可能会被分配到同一个桶,因此所有 key-value 对会在各自桶内以列表(List)形式存储。选择合适的哈希函数对性能影响很大。
要在字典(Dictionary)中找到所有变位词(Anagram),我们需要把包含同一组字母的单词分到同一组。因此,如果把每个单词映射为“其字母排序后的字符串”,就可以用该字符串作为 key,把单词分组到列表中。
FUNCTION find_anagrams(words)
- 函数 find_anagrams(words)
word_groups = HashTable
- word_groups = 哈希表
FOR word IN words
- 对于 words 中的每个 word
word_groups.get_or_default(sort(word), []).push(word)
- word_groups.get_or_default(sort(word), []).push(word)
END FOR
- 结束循环
anagrams = List
- anagrams = 列表
FOR key, value IN word_groups
- 对于 word_groups 中的每个 key, value
anagrams.push(value)
- anagrams.push(value)
END FOR
- 结束循环
- RETURN anagrams哈希表(Hash Table)把“列表”映射到“字符串”。对每个单词,我们要么把它加入对应 key 的列表中,要么创建一个新列表并把它加入。
378. 解释 BFS(广度优先搜索(Breadth-First Search))算法。
- 知识点: 算法与数据结构 (主题: algorithms, graphs;标签: bfs, graph-traversal)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969b1a73695832c6e096d05 | 官方: 是 | 付费: 否
答案:
答案BFS(Breadth First Search,广度优先搜索)是一种图遍历算法。它从根节点开始遍历图,并探索所有相邻节点。它选择最近的节点并访问所有未探索的节点。算法会对每一层最接近的节点重复同样的过程,直到达到目标状态。
算法(Algorithm):
- 步骤1:设置 status=1(ready state)
- 步骤2:将起始节点 A 入队,并将其状态设为 status=2,即(waiting state)
- 步骤3:重复步骤4和步骤5,直到队列为空。
- 步骤4:出队一个节点 N,处理它,并将其状态设为 status=3,即(processed state)
- 步骤5:将所有处于 ready state(status=1)的 N 的邻居节点入队,并将它们的状态设为 status=2(waiting state)
- [Stop Loop]
- 步骤6:退出
379. 什么是 Dijkstra(Dijkstra,迪杰斯特拉)最短路径算法(Shortest Path Algorithm)?
- 知识点: 算法与数据结构 (主题: algorithms, graphs, dijkstra, shortest-path;标签: graph, shortest path)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969e2643695832c6e0e1810 | 官方: 是 | 付费: 否
答案:
答案
Dijkstra 算法(Dijkstra Algorithm)是一种图算法(Graph Algorithm),用于从一个源节点(Source Node)出发,找出到图中所有其他节点的最短路径(Shortest Path)。
它通过维护一组“从源点到该节点的最短距离(Shortest Distance)已确定”的节点集合(Node Set),并反复选择当前“暂定距离(Tentative Distance)最小”的节点,然后更新其邻居节点(Neighbor Node)的距离来工作。
380. 请给出分治(Divide and Conquer)算法的一些例子?
- 知识点: 算法与数据结构 (主题: algorithms, divide-and-conquer;标签: divide and conquer, sorting, search)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969e2643695832c6e0e1814 | 官方: 是 | 付费: 否
答案:
答案
下面是一些分治算法(Divide and Conquer Algorithm)的例子:
- 归并排序(Merge Sort)
- 快速排序(Quick Sort)
- 二分查找(Binary Search)
- Karatsuba 乘法算法
- Strassen 矩阵乘法算法
381. 什么是贪心算法(Greedy Algorithm)?请给出一些例子。
- 知识点: 算法与数据结构 (主题: algorithms, greedy;标签: greedy, mst, optimization)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969e2663695832c6e0e19ce | 官方: 是 | 付费: 否
答案:
答案
贪心算法(Greedy Algorithm)是一种算法策略(Algorithm Strategy):在每个子阶段都做出当前看来“最优”的选择,希望最终能得到全局最优解(Global Optimal Solution)。这意味着算法只考虑眼前的最优解,而不考虑其后果。
换句话说,它在求解过程中总是选择当前最好的即时(局部)解(Local Optimal Solution)。
对于某些问题,贪心算法可以得到整体最理想的解;但对于另一些问题的某些实例,可能会得到不够理想的解。
以下是一些使用贪心算法求解的典型问题/算法(Problem/Algorithm):
- 旅行商问题(Travelling Salesman Problem)
- Prim 最小生成树算法(Prim's Minimal Spanning Tree Algorithm)
- Kruskal 最小生成树算法(Kruskal's Minimal Spanning Tree Algorithm)
- Dijkstra 最小生成树算法(Dijkstra's Minimal Spanning Tree Algorithm)
- 图 - 地图着色(Graph - Map Coloring)
- 图 - 顶点覆盖(Graph - Vertex Cover)
- 背包问题(Knapsack Problem)
- 作业调度问题(Job Scheduling Problem)
382. 什么是线性搜索(Linear Search)?
- 知识点: 算法与数据结构 (主题: algorithms, search;标签: linear search, array)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969e2663695832c6e0e19d1 | 官方: 是 | 付费: 否
答案:
答案
线性搜索(Linear Search)用于在一组元素中查找目标值(Target Value)。它依赖从头到尾遍历列表(Traverse List)的方式,依次访问路径上的所有元素并进行比较。比如有一个包含若干整数的数组(Array),你需要找出并打印与目标值匹配元素的位置。线性搜索的流程是:从列表开头逐个与目标整数匹配;若条件为 True,则打印该元素的位置。
实现线性搜索(Implementing Linear Search)
实现线性搜索需要以下步骤:
- Step1: 使用 for 循环遍历数组。
- Step2: 每次迭代中,将目标值与数组当前值进行比较。
- Step3: 如果值匹配,返回当前索引。
- Step4: 如果不匹配,继续下一个元素。
- Step5: 如果未找到匹配,返回 -1。
383. 什么是二叉搜索树(Binary Search Tree, BST)?
- 知识点: 算法与数据结构 (主题: data-structures, bst, trees;标签: binary search tree, tree)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969e2663695832c6e0e19d5 | 官方: 是 | 付费: 否
答案:
答案
二叉搜索树(Binary Search Tree, BST)是一种特殊的数据结构(Data Structure),具有以下性质:
- 小于根节点的节点位于左子树。
- 大于根节点的节点(即值更大)位于右子树。
- 二叉搜索树不应包含重复节点。
- 左右子树本身也应分别是二叉搜索树。
384. 写出在二叉搜索树(Binary Search Tree, BST)中插入节点的算法(Algorithm)?
- 知识点: 算法与数据结构 (主题: data-structures, bst, trees;标签: insert, bst)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969e2693695832c6e0e1b90 | 官方: 是 | 付费: 否
答案:
答案
插入节点是一个相对平滑的操作。需要将待插入节点与根节点(Root Node)比较:若更小则向左遍历,若更大则向右遍历,直到找到可插入的位置。
算法(Algorithm):
- 将根节点设为当前节点
- 如果待插入节点 < 根节点
- 若当前节点有左孩子,则向左遍历
- 若没有左孩子,则在此处插入节点
- 如果待插入节点 > 根节点
- 若当前节点有右孩子,则向右遍历
- 若没有右孩子,则在此处插入节点。
385. 如何统计二叉树(Binary Tree)中叶子节点(leaf nodes)的数量?
- 知识点: 算法与数据结构 (主题: data-structures, trees;标签: leaf, recursion)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969e2693695832c6e0e1b93 | 官方: 是 | 付费: 否
答案:
答案
如果一个节点没有任何子节点(Child Nodes),则称为叶子节点(Leaf Node)。因此统计“子节点数量为 0”的节点个数,就能得到叶子节点数量。
- 使用递归遍历二叉树。
- 如果某个节点没有子节点(0 个 children),则计数加 1。
386. 如何从一个字符棋盘(Character Board)中找到所有可能组成的单词(Words)?
- 知识点: 算法与数据结构 (主题: algorithms, backtracking, dfs;标签: grid, word search)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969e26d3695832c6e0e1d80 | 官方: 是 | 付费: 否
答案:
答案
给定一个字典(Dictionary)、字典查找方法(Dictionary Lookup Method),以及一个 M x N 的字符棋盘(Character Board)(每个格子包含一个字符),找出所有可以由相邻字符序列组成的单词(Words)。注意:我们可以向 8 个相邻方向移动,但一个单词不能重复使用同一个格子。
示例(Example):
输入:dictionary[] = {"GEEKS","FOR","QUIZ","GO"}
board[][] = {{'G','I','Z'},{'U','E','K'},{'Q','S','E'}}
board[][] = {{'G','I','Z'},{'U','E','K'},{'Q','S','E'}}
输出(Output): GEEKS QUIZ
387. 写出在单链表(singly linked list)中插入节点的算法(Algorithm)?
- 知识点: 算法与数据结构 (主题: data-structures, linked-list;标签: insert, singly linked list)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969e26d3695832c6e0e1d83 | 官方: 是 | 付费: 否
答案:
答案
在单链表(Singly Linked List)中插入节点需要遵循以下步骤:
算法(Algorithm)
- 使用指针创建一个新节点
- 为新节点赋值
- 如果它是链表中的第一个节点,则将新节点设置为 head,并将新节点的 next 指向 null
- 否则遍历到链表末尾,将最后一个节点的 next 指向新节点
- 将新节点的 next 指向 null
388. 算法分析(Algorithm Analysis)的标准是什么?
- 知识点: 算法与数据结构 (主题: algorithms, complexity;标签: time complexity, space complexity)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969e2703695832c6e0e1f40 | 官方: 是 | 付费: 否
答案:
答案
算法分析(Algorithm Analysis)通常包括以下标准:
- 时间复杂度(Time Complexity):算法执行所需时间,通常表示为输入规模 n 的函数。
- 空间复杂度(Space Complexity):算法执行所需空间,通常表示为输入规模 n 的函数。
389. 栈(Stack)和队列(Queue)的区别是什么?
- 知识点: 算法与数据结构 (主题: data-structures, stack, queue;标签: lifo, fifo)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969e2733695832c6e0e2103 | 官方: 是 | 付费: 否
答案:
答案
栈(Stack)和队列(Queue)都是用于存储数据元素的非原始数据结构(Non-primitive Data Structure),并且都对应现实世界的某些等价物。下面从几个参数来看它们的关键差异。
工作原理(Working Principle)
栈(Stack)使用 LIFO(Last In First Out,后进先出)来访问与添加元素;队列(Queue)使用 FIFO(First In First Out,先进先出)来获取元素。
结构(Structure)
栈(Stack)在同一端进行插入与删除;队列(Queue)在一端插入(rear 端),另一端删除元素。
指针数量(Number of Pointers Used)
栈(Stack)使用一个指针;队列(Queue)(简单情形)使用两个指针。
操作(Operations Performed)
栈(Stack)的操作是 Push / Pop;队列(Queue)的操作是 Enqueue / Dequeue。
变体(Variants)
栈(Stack)没有变体;队列(Queue)有循环队列(Circular Queue)、优先队列(Priority Queue)、双端队列(Deque)等变体。
实现(Implementation)
栈(Stack)更简单,而队列(Queue)相对更复杂。
390. 单链表(Singly Linked List)与双链表(Doubly Linked List)有什么区别?
- 知识点: 算法与数据结构 (主题: data-structures, linked-list;标签: singly, doubly, traversal)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969e2733695832c6e0e2106 | 官方: 是 | 付费: 否
答案:
答案
这是一个经典的数据结构(Data Structure)面试题。单链表(Singly Linked List)与双链表(Doubly Linked List)的主要区别在于遍历能力。
在单链表(Singly Linked List)中无法向后遍历,因为每个节点(Node)只指向下一个节点,并没有指向前一个节点的指针(Pointer)。
而双链表(Doubly Linked List)维护了两个指针(Pointer),分别指向下一个节点和前一个节点,因此可以在两个方向上进行遍历。
391. 在 Java 中如何不使用临时变量(Temporary Variable)交换两个整数(Integer)?
- 知识点: 算法与数据结构 (主题: algorithms;标签: algorithm)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969efa03695832c6e0f9af4 | 官方: 是 | 付费: 否
答案:
答案这是一道非常常见的“技巧题”。解决方法很多,但必要条件是:不能使用临时变量(Temporary Variable)交换。如果你能考虑到整数溢出(Integer Overflow)并给出对应方案,会给面试官留下很好的印象。
But the necessary condition is we have to solve it without swapping the temporary variable.
但必要条件是,我们必须在交换临时变量的情况下解决它。
If we think about integer overflow and consider its solution, then it creates an excellent impression in the eye of interviewers.
如果我们考虑整数溢出及其解决方案,那么这会给面试官留下极好的印象。
假设有两个整数(Integer) i 和 j,i=7、j=8,如何在不使用第三个变量的情况下交换它们?这是一个经典问题。我们需要用 Java 的编程结构来完成。可以通过加减乘除等数学运算来交换,但可能会带来整数溢出(Integer Overflow)问题。
We need to do this using Java programming constructs. We can swap numbers by performing some mathematical operations like addition, subtraction, multiplication, and division. But maybe it will create the problem of integer overflow.
我们需要使用Java编程结构来完成此操作。我们可以通过执行一些数学运算(如加法、减法、乘法和除法)来交换数字。但这可能会产生整数溢出问题。
使用加法与减法
a= a + b;b=a - b; // this will act like (a+b)-b, now b is equal to a.
a= a + b;b=a - b; // 这将类似于(a+b)-b,现在b等于a。
a=a - b; // (a+b)-a, now, a is equal to b.
a=a - b; // (a+b)-a,现在a等于b。
这是一个不错的技巧。但如果加法结果超过 int 原生类型的最大值(Maximum Value,Integer.MAX_VALUE),或者减法结果小于最小值(Minimum Value,Integer.MIN_VALUE),就会发生整数溢出(Integer Overflow)。
使用 XOR 技巧
另一种不用第三个变量(Temporary Variable)交换两个整数(Integer)的方法,被广泛认为是更好的解决方案,因为它也适用于不处理整数溢出(Integer Overflow)的语言(例如 C、C++)。Java 支持多种位运算符(Bitwise Operator),其中之一是 XOR(用 ^ 表示)。
x=x^y;
x=x^y;
y=x^y;
y=x^y;
x=x^y;
x=x^y;
392. 什么是分治算法(Divide and Conquer Algorithm)?
- 知识点: 算法与数据结构 (主题: algorithms;标签: algorithm)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969efa03695832c6e0f9afc | 官方: 是 | 付费: 否
答案:
答案Divide and Conquer is not an algorithm; it's a pattern for the algorithm. It is designed in a way as to take dispute on a huge input, break the input into minor pieces, and decide the problem for each of the small pieces. Now merge all of the piecewise solutions into a global solution. This strategy is called divide and conquer.
Divide and conquer uses the following steps to make a dispute on an algorithm.
分治法使用以下步骤来对算法进行争议性讨论。
Divide(分解):把问题分解为若干规模更小的子问题(Subproblem)。
Conquer(解决):递归(Recursion)地解决子问题(Subproblem)。若子问题足够小,则直接求解。
Combine(合并):把子问题(Subproblem)的解组合起来,得到整个问题的解。
393. 举一些分治算法(Divide and Conquer Algorithm)的例子。
- 知识点: 算法与数据结构 (主题: algorithms;标签: algorithm)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969f3453695832c6e0fe976 | 官方: 是 | 付费: 否
答案:
答案以下是一些使用分治算法(Divide and Conquer)求解的问题示例:
归并排序(Merge Sort)
快速排序(Quick Sort)
二分查找(Binary Search)
Strassen 矩阵乘法(Strassen Matrix Multiplication)
最近点对(Closest Pair of Points)
394. 如何统计二叉树的叶子节点(Leaf Node)数量?
- 知识点: 算法与数据结构 (主题: algorithms;标签: algorithm)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969f3513695832c6e0ff2b4 | 官方: 是 | 付费: 否
答案:
答案算法(Algorithm)-
统计叶子节点数量的步骤如下:
If the node is null (contains null values) then return 0.
如果节点为空(包含空值),则返回0。
If encountered leaf node. Left is null and node Right is null then return 1.递归地(Recursively)计算叶子节点数量:
叶子节点数 = 左子树(Left Subtree)叶子节点数 + 右子树(Right Subtree)叶子节点数。
395. 如何在字符棋盘中找出所有可能单词(Boggle 游戏)?
- 知识点: 算法与数据结构 (主题: algorithms;标签: algorithm)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969f3513695832c6e0ff2b7 | 官方: 是 | 付费: 否
答案:
答案给定一个字典(Dictionary),我们需要判断字符串是否在字典中。同时在棋盘上组合字母时,可以从相邻单元格扩展,但一个单词不能重复使用同一个单元格。
示例:
dictionary[] = {"Java", "Point","Quiz"};
dictionary[] = {"Java", "Point","Quiz"};
Array[][] = {{'J', 'T', 'P',},
Array[][] = {{'J', 'T', 'P',},
{'U', 'A', 'A'},
{'U', 'A', 'A'},
{'Q', 'S', 'V'}};
{'Q', 'S', 'V'}};
isWord(str): returns true if str is present in dictionary否则返回 false。
输出:
字典(dictionary)中存在以下单词:
JAVA
JAVA
396. 写一个在链表(linked list)中插入节点(node)的算法(algorithm)。
- 知识点: 算法与数据结构 (主题: algorithms;标签: algorithm)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969f3533695832c6e0ff47c | 官方: 是 | 付费: 否
答案:
答案算法
检查:如果链表为空,则将该节点设为 head 并返回。
检查:如果待插入节点的值小于 head 节点的值,则在链表头部插入该节点,并将其设为新的 head。
循环查找合适的插入位置:找到一个节点,使得该节点值小于待插入节点值,而它的下一个节点值大于待插入节点值。该节点就是插入位置的前驱节点(predecessor node)。
将节点插入到步骤3找到的正确位置之后。
397. 算法分析(algorithm analysis)的标准有哪些?
- 知识点: 算法与数据结构 (主题: algorithms, complexity;标签: algorithm, time complexity, space complexity)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969f7193695832c6e104443 | 官方: 是 | 付费: 否
答案:
答案算法通常从两个因素进行分析。
时间复杂度(time complexity)
空间复杂度(space complexity)
时间复杂度用于量化算法的运行时间:也就是程序/函数处理给定输入所需的时间。
空间复杂度是算法为执行并产生结果所使用的内存量。
398. 解释在计算机中什么是算法?
- 知识点: 算法与数据结构 (主题: algorithms;标签: algorithm, basics)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fadae6ae93548e54a826 | 官方: 是 | 付费: 否
答案:
答案算法是一种定义良好的计算过程:它接收某个值或一组值作为输入(input),并生成某个值或一组值作为输出(output)。
简单来说,它是一系列计算步骤,用于将输入转换为输出。
399. 解释什么是快速排序(Quick Sort)算法?
- 知识点: 算法与数据结构 (主题: algorithms, sorting, quicksort;标签: sorting, quicksort, divide and conquer)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fadae6ae93548e54a829 | 官方: 是 | 付费: 否
答案:
答案快速排序算法能够快速对列表或查询结果(query result)进行排序。
它基于“分区交换排序(partition exchange sort)”或“分治(Divide and conquer)”思想。
这种算法占用较少空间,并将列表(list)划分为三个主要部分:
- 小于枢轴(Pivot)元素的元素
- 枢轴(Pivot)元素
- 大于枢轴(Pivot)元素的元素
400. 解释什么是算法的时间复杂度(Time Complexity)?
- 知识点: 算法与数据结构 (主题: algorithms, complexity;标签: time complexity, big o)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fadae6ae93548e54a82c | 官方: 是 | 付费: 否
答案:
答案算法的时间复杂度(Time Complexity)表示程序运行至完成所需的总时间。
通常使用大 O(Big O)记号(notation)来表示。
401. 时间复杂度常用的记号(Notation)有哪些?
- 知识点: 算法与数据结构 (主题: algorithms, complexity;标签: big o, big omega, big theta)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fadae6ae93548e54a82f | 官方: 是 | 付费: 否
答案:
答案时间复杂度常用的记号(Notation)包括:
- Big Oh:表示“少于或等于”
次迭代 - Big Omega:表示“多于或等于”
次迭代 - Big Theta:表示“等于”
次迭代 - Little Oh:表示“少于”
次迭代 - Little Omega:表示“多于”
次迭代
402. 解释二分查找(Binary Search)是如何工作的?
- 知识点: 算法与数据结构 (主题: algorithms, searching, binary-search;标签: binary search, array)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fadae6ae93548e54a832 | 官方: 是 | 付费: 否
答案:
答案在二分查找(Binary Search)中,我们将关键字(key)与数组(array)中间位置的元素进行比较。
如果 key 小于被查找的中间元素,则它一定在数组(array)的下半部分;如果 key 大于被查找的中间元素,则它在数组(array)的上半部分。
403. 二分查找(Binary Search)能否用于链表(Linked List)?为什么?
- 知识点: 算法与数据结构 (主题: algorithms, searching, linked-list;标签: binary search, linked list)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fadae6ae93548e54a835 | 官方: 是 | 付费: 否
答案:
答案由于链表(Linked List)不支持随机访问(random access),无法在 O(1) 时间内到达中间元素。
因此,二分查找(Binary Search)不适用于链表(Linked List)。
404. 解释什么是堆排序(Heap Sort)?
- 知识点: 算法与数据结构 (主题: algorithms, sorting, heapsort;标签: sorting, heap sort)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fadae6ae93548e54a838 | 官方: 是 | 付费: 否
答案:
答案堆排序是一种基于比较(comparison-based)的排序算法。
它将输入划分为未排序区与已排序区,并不断通过移除最小元素来缩小未排序区,将该最小元素移动到已排序区。
405. 解释什么是跳表(Skip List)?
- 知识点: 算法与数据结构 (主题: data-structures, skip-list;标签: skip list, dictionary)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fadae6ae93548e54a83b | 官方: 是 | 付费: 否
答案:
答案跳表是一种数据组织/结构化的方法,它允许算法在符号表(symbol table)或字典(dictionary)中进行查找、删除与插入。
在跳表中,每个元素由一个节点(node)表示。查找函数会返回与 key 相关联的 value 内容。
插入操作将指定的 key 与一个新 value 关联;删除函数删除指定的 key。
406. 插入排序(Insertion Sort)算法的空间复杂度(space complexity)是什么?
- 知识点: 算法与数据结构 (主题: algorithms, sorting, insertion-sort;标签: insertion sort, space complexity)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fadae6ae93548e54a83e | 官方: 是 | 付费: 否
答案:
答案插入排序是一种原地(in-place)排序算法,这意味着它不需要额外或只需要很少的存储空间。
对于插入排序,它只需要在初始数据之外暂存单个列表元素,因此空间复杂度为 O(1)。
407. 如何判断链表是否有环(loop)?
- 知识点: 算法与数据结构 (主题: data-structures, linked-list, algorithms;标签: linked list, cycle detection, two pointers)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fbece6ae93548e54c5d6 | 官方: 是 | 付费: 否
答案:
答案判断链表是否存在环(loop),需要检查链表中是否包含循环。
解决这个问题可以采用“双指针”(two-pointer)方法:使用两个指针分别按不同速度前进。
慢指针(slow)每次移动 1 个节点;快指针(fast)每次移动 2 个节点。
如果链表存在环,这两个指针最终会相遇;如果链表不存在环,快指针会先到达链表末尾。
408. 最好情况(Best Case)与最坏情况(Worst Case)有什么区别?
- 知识点: 算法与数据结构 (主题: algorithms, complexity;标签: best case, worst case)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fbefe6ae93548e54c7a7 | 官方: 是 | 付费: 否
答案:
答案最好情况(best case)表示在给定输入下,算法可能达到的最短运行时间(runtime)。
最坏情况(worst case)表示在给定输入下,算法(algorithm)可能达到的最长运行时间(running time)。
通常,我们会同时考虑最好情况(best case)与最坏情况,以更好地评估算法(algorithm)的性能(performance)范围。
409. 解释什么是基数排序(Radix Sort)?
- 知识点: 算法与数据结构 (主题: algorithms, sorting, radix-sort;标签: radix sort, non-comparison sort)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fbefe6ae93548e54c7aa | 官方: 是 | 付费: 否
答案:
答案基数排序(Radix Sort)是一种非比较型排序算法(non-comparison sorting algorithm)。
它通过按位(digit)对数字进行排序来工作:从最低有效位(least significant digit)到最高有效位(most significant digit)(或反向)逐位处理。
它通常与计数排序(Counting Sort)等稳定排序(stable sort)作为子过程(subroutine)结合使用。
410. 解释什么是递归算法(Recursive Algorithm)?
- 知识点: 算法与数据结构 (主题: algorithms, recursion;标签: recursion, base case)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fbefe6ae93548e54c7ad | 官方: 是 | 付费: 否
答案:
答案递归算法(recursive algorithm)是一种通过调用自身来解决问题的算法(algorithm)。
它通常将问题分解为更小的子问题(subproblem),直到达到终止条件(base case)。
411. 递归的三条法则(Rules of Recursion)是什么?
- 知识点: 算法与数据结构 (主题: algorithms, recursion;标签: recursion rules, base case)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fbefe6ae93548e54c7b0 | 官方: 是 | 付费: 否
答案:
答案递归的三条法则(Rules of Recursion)是:
- 递归函数必须有一个终止条件(base case)。
- 递归函数必须调用自身。
- 递归函数在每次调用时都必须向终止条件(base case)推进。
412. 解释什么是冒泡排序(Bubble Sort),也称下沉排序(Sinking Sort)?
- 知识点: 算法与数据结构 (主题: algorithms, sorting, bubble-sort;标签: bubble sort, sinking sort)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6969fbefe6ae93548e54c7b7 | 官方: 是 | 付费: 否
答案:
答案冒泡排序(Bubble Sort),也称为下沉排序(Sinking Sort),是一种简单的比较排序算法(comparison sorting algorithm)。
它通过重复遍历列表,比较相邻元素并在顺序错误时交换它们,使较大的元素逐步“冒泡”到末尾。
413. 为什么“只存整数的高性能计数器”能把读复杂度(read complexity)降到 O(1)?适用前提是什么?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 (主题: data-structures, caching, distributed-systems;标签: O(1) read, latest value)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696de486e6ae93548e9675fa | 官方: 是 | 付费: 否
答案:
答案如果业务只关心“当前值”而不需要历史回溯,那么用一个整数(或少量分片整数)保存最新计数即可。读取时直接取值或取 shard 求和,避免复杂 JOIN/全表扫描,读复杂度(read complexity)接近 O(1),延迟(latency)也更稳定。适用前提是:不依赖事务查询(transactional query)、无需长期保留每次更新明细;若需要审计(audit)/回放(replay),可另建事件日志(event log)异步落盘,但在线读路径仍以“最新值缓存(cache)/内存存储(in-memory storage)”为主。
414. 什么是图(Graph)?常见应用有哪些?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: graph, bfs, dfs, dijkstra)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f113f120fcc1591159290 | 官方: 是 | 付费: 否
答案:
答案图由节点(Node)与边(Edge)组成,可有向(Directed)/无向(Undirected)、带权(Weighted)/不带权(Unweighted),用于表达关系网络(Network)。应用包括社交网络(Social Network)、导航路网(Road Network)、依赖关系(Dependency,拓扑排序 Topological Sort)、网络路由(Network Routing)、推荐(Recommendation)与知识图谱(Knowledge Graph)。常见表示邻接表(Adjacency List)/矩阵(Adjacency Matrix),算法有 BFS/DFS、最短路(Shortest Path)、MST 等。
415. Google 的 Technical Phone Screen 通常如何进行?候选人最容易踩的坑是什么?
- 知识点: 算法与数据结构 (主题: algorithms, coding;标签: phone-screen, complexity, edge-cases)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f121e120fcc159115a3a4 | 官方: 是 | 付费: 否
答案:
答案材料描述该环节通常45-60 分钟,视频会议(Video Conference)+共享文档(Shared Document)/协作编辑(Collaborative Editing)(可能要求屏幕共享(Screen Sharing)),需要解决1-2 道算法题(Algorithm Problem)并清晰讲解思路、边界条件(Edge Case)与复杂度(Complexity)。常见坑:只会写代码不解释;一开始不澄清输入输出与约束;忽略复杂度/测试样例(Test Case);把时间花在语法细节而非正确性与优化路径。
416. 材料中 Onsite Loop 的结构是什么?L4/L5 与 L3 的差异在哪?
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 (主题: system-design, algorithms;标签: onsite-loop, leveling, l3-l4-l5)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f121e120fcc159115a3a7 | 官方: 是 | 付费: 否
答案:
答案材料说 onsite(或 virtual loop)通常4-6 轮、每轮约 45 分钟。一般包含三轮 coding(DS&A,中高难+追问)。对 L4/L5 会新增1-2 轮系统设计(System Design),考可扩展性(Scalability)、可靠性(Reliability)与权衡(Trade-off);另有Googleyness行为面(Behavioral Interview)。L3(entry-level)更偏重基础算法与编码功底,通常没有专门的大型系统设计轮。
417. 材料提到 Google 面试常在共享文档里写代码、没有 IDE。如何针对这种环境训练?
- 知识点: 算法与数据结构 / 行为与软技能 (主题: coding, communication;标签: no-ide, mock-interview, thinking-aloud)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f1220120fcc159115a5c5 | 官方: 是 | 付费: 否
答案:
答案材料建议用 mock onsite/模拟面试复刻真实环境:在 Google Doc/协作编辑器(Collaborative Editor)里手写代码,刻意练习清晰的变量命名、手动检查边界与测试、以及边写边讲。训练重点不是语法炫技,而是:先澄清约束(Constraint)→给出思路→写出可运行的核心逻辑→补充复杂度与测试样例→再做优化与讨论权衡。
418. Coding:二叉树的非递归后序遍历怎么写?(给出思路与代码)
- 知识点: 算法与数据结构 (主题: data-structures, binary-tree;标签: binary tree, postorder, iterative, stack)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f13d7120fcc159115c7d9 | 官方: 是 | 付费: 否
答案:
答案后序遍历(Postorder Traversal)是 left→right→root。非递归常见两种写法:
- 双栈法:第一个栈做类似前序(root→left→right),把弹出的节点压入第二个栈,最后第二个栈逆序输出即后序。
单栈 + prev 指针:沿左链入栈;看栈顶节点,如果它有右子树且右子树没处理过,就转向右子树;否则弹栈输出,并把 prev 置为该节点。
Python 示例(单栈)def postorder_traversal(root):
"""Iterative postorder traversal: left -> right -> root""""""迭代后序遍历:左 -> 右 -> 根"""
res = []
res = []
stack = []
stack = []
prev = None
prev = None
cur = root
cur = root
while cur or stack:
while cur or stack:Go as left as possible
while cur:
while cur:
stack.append(cur)
stack.append(cur)
cur = cur.left
cur = cur.left
node = stack[-1]
node = stack[-1]If right subtree is not processed, go right
if node.right and prev is not node.right:
if node.right and prev is not node.right:
cur = node.right
cur = node.right
else:
否则:
stack.pop()
stack.pop()
res.append(node.val)
res.append(node.val)
prev = node
prev = node
return res
return res
复杂度:时间 O(n),空间 O(h)(h 为树高(Tree Height))。
419. 给定一个数组 nums,包含从 1 到 N 的所有整数但缺失两个数字(数组长度为 N-2)。要求 O(N) 时间、O(1) 额外空间,找出缺失的两个数字,并说明思路。
- 知识点: 算法与数据结构 (主题: algorithms, math, bitwise;标签: missing two numbers, O(1) space, O(N) time)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f19ca120fcc15911670a9 | 官方: 是 | 付费: 否
答案:
答案关键是先确定 N:通常 N = len(nums) + 2。目标是在不使用额外哈希表(Hash Table)的前提下恢复两个缺失值。
常见有三类做法:数学(和与平方和)、原地哈希(In-place Hashing)(把值放回“该在的位置”)、位运算(Bit Manipulation)(整体异或后按最低不同位分组)。
三种方法都能做到 O(N) 时间;数学与位运算天然 O(1) 空间,原地哈希也可做到 O(1) 额外空间。
420. 方法一:如何用“和 + 平方和”在 O(N)/O(1) 内求出缺失的两个数?请给出推导与求解步骤。
- 知识点: 算法与数据结构 (主题: algorithms, math;标签: sum, sum of squares, quadratic)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f19ca120fcc15911670ac | 官方: 是 | 付费: 否
答案:
答案设缺失的两个数为 a、b。令 S = 1..N 的总和(sum),Q = 1..N 的平方和(sum of squares);遍历 nums 得到 s = nums 的和,q = nums 的平方和。
则有:a + b = (S - s) = A;a^2 + b^2 = (Q - q) = B。
又因为 (a + b)^2 = a^2 + b^2 + 2ab,所以 ab = (A^2 - B) / 2。
于是 a、b 是方程(quadratic equation)x^2 - A x + ab = 0 的两根:x = (A ± sqrt(A^2 - 4ab)) / 2。
注意溢出(overflow):S/Q 可能很大,建议用 64 位整数(long long)或更高精度类型(high-precision type)。
421. 用数学法时,为什么需要小心数值溢出(numeric overflow)/精度(precision)?有哪些工程上的处理建议?
- 知识点: 算法与数据结构 (主题: math, engineering;标签: overflow, integer sqrt)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f19cc120fcc15911672c4 | 官方: 是 | 付费: 否
答案:
答案S 和 Q 的量级分别是 O(N^2) 与 O(N^3),当 N 较大时 32 位整数(32-bit integer)极易溢出。
建议:使用 64 位整型(64-bit integer);在 C++ 用 long long;在 Java 用 long;在 Python 不担心但要注意性能。
开根号前的判别式(discriminant)D = A^2 - 4ab 必须非负且为完全平方数(perfect square)(因为答案是整数),实现时可先用 128 位或 big integer 计算再转回。
如果语言浮点精度(floating-point precision)可能导致 sqrt 误差,可用整数开方(integer square root)校验或用二分/牛顿法求整数 sqrt。
422. 方法二:在 O(1) 额外空间(extra space)下,如何用“原地哈希/置换”(in-place hashing/permutation)找出缺失的两个数?核心步骤是什么?
- 知识点: 算法与数据结构 (主题: algorithms, array;标签: in-place hashing, cyclic sort, swap)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f19cc120fcc15911672c8 | 官方: 是 | 付费: 否
答案:
答案思路:把每个值 v 放到它应该在的位置(常见映射:索引 i 对应值 i+1)。完成后扫描数组,没对上的位置就是缺失值。
因为 nums 长度是 N-2,可先在数组尾部追加两个占位(placeholder)(如 -1),让长度变为 N,避免越界并能覆盖 1..N 的位置。
循环 i=0..N-1:当 nums[i] 在 1..N 且 nums[i] != nums[nums[i]-1] 时,swap(nums[i], nums[nums[i]-1]),直到当前位置稳定。
最后再扫一遍:若 nums[i] != i+1,则 i+1 是缺失数(missing number)(共两处)。
423. 方法三:如何用位运算(异或(XOR))在 O(N)/O(1) 下找出缺失的两个数?请解释“分组”的依据。
- 知识点: 算法与数据结构 (主题: algorithms, bitwise;标签: xor, lowbit, partition)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f19cc120fcc15911672cc | 官方: 是 | 付费: 否
答案:
答案先计算 xorAll = (1^2^...^N) ^ (nums[0]^nums[1]^... ),得到 xorAll = a ^ b(a、b 为缺失数)。
因为 a != b,所以 xorAll 至少有一位为 1,取最低位 lowbit = xorAll & (-xorAll)(或找到任意为 1 的位)。
用 lowbit 将 1..N 与 nums 分成两组:该位为 1 的一组、为 0 的一组;分别做异或(XOR),缺失的 a、b 会被分到不同组。
最终 groupXor1 得到其中一个缺失数,groupXor2 得到另一个。该法不依赖加法,避免大数溢出。
424. 三种方法如何取舍?分别有哪些优缺点与适用场景?
- 知识点: 算法与数据结构 (主题: algorithms, engineering;标签: tradeoff, methods comparison)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f19cf120fcc15911674f5 | 官方: 是 | 付费: 否
答案:
答案数学法:实现简洁、无需修改数组,但要处理大数与开根号精度;适合 N 不太夸张或语言支持大整数(Big Integer)的场景。
原地哈希(In-place Hashing):不怕溢出、纯整数逻辑,但会修改输入数组;适合允许原地修改且想要直观定位缺失位置的场景。
异或法(XOR):最稳健(不溢出、无需额外结构、无需 sqrt(平方根)),实现也短;但需要理解位分组,面试解释要讲清 lowbit 的意义。
425. Amazon 常见 Graph/Tree 题会考哪些经典能力点?
- 知识点: 算法与数据结构 (主题: amazon, interview, graphs, trees;标签: DFS, BFS, Topological Sort)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f2293120fcc159117e018 | 官方: 是 | 付费: 否
答案:
答案高频点包括:树的遍历与构建(前序+中序还原)、路径问题(最大路径和)、序列化与反序列化、图的连通性与合法性(判断是否为树)、拓扑排序(Topological Sort)(课程安排)、以及基于 DFS/BFS 的搜索与回溯(行程重建等)。准备时要掌握递归与迭代两套写法,并熟悉常见剪枝与 visited 设计。
426. Amazon 常见 Arrays/Strings 题会考哪些套路?
- 知识点: 算法与数据结构 (主题: amazon, interview, arrays, strings;标签: Two Pointers, Sliding Window)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f2293120fcc159117e01b | 官方: 是 | 付费: 否
答案:
答案常见套路是双指针(Two Pointers)、滑动窗口(Sliding Window)、前缀和/差分、哈希计数、排序+去重,以及字符串处理(回文、词频、前缀匹配/搜索建议)。面试中要能快速识别题目属于哪种模式,并说清楚为何这个模式能保证正确性与复杂度。
427. 编写程序:对包含 N 个数字的数组执行归并排序(Merge Sort)。
- 知识点: 算法与数据结构 (主题: algorithms, sorting, merge-sort, array;标签: merge sort, divide and conquer)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f2cc0120fcc1591199a53 | 官方: 是 | 付费: 否
答案:
答案归并排序(Merge Sort)使用分治:把数组递归拆成两半分别排序,再用双指针把两个有序子数组合并。它在最坏/平均情况下都为 O(N log N),稳定排序;但需要额外临时数组,空间复杂度通常为 O(N)。
// Java (core idea)
// Java(核心思想)
void mergeSort(int[] a, int l, int r){
void mergeSort(int[] a, int l, int r){
if(l>=r) return;
如果左边界大于等于右边界,直接返回;
int m = l + (r-l)/2;
计算中间位置m为左边界加上区间长度的一半;
mergeSort(a,l,m);
对左半部分调用归并排序;
mergeSort(a,m+1,r);
对右半部分调用归并排序;
merge(a,l,m,r);
将左右两半合并起来;
}
428. 编写一个用于堆排序(Heap Sort)的程序,并说明时间/空间复杂度。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: dsa, sorting, python;标签: heap sort, heap, complexity)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f31a2120fcc15911a2a60 | 官方: 是 | 付费: 否
答案:
答案
堆排序(Heap Sort)思路:先把数组建成最大堆(Max Heap),然后反复把堆顶(最大值)与末尾交换,并对剩余部分做下沉调整(Sift Down)。建堆是 O(n),每次调整 O(log n),共 n 次,因此整体时间复杂度为 O(n log n),空间复杂度为 O(1)(原地排序(In-place Sort))。
def heap_sort(a):
定义堆排序函数heap_sort,接受参数a;
n = len(a)
获取数组a的长度并赋值给n;
def sift_down(i, size):
定义下沉函数sift_down,接受索引i和当前堆大小size;
while True:
while True:
l = 2 * i + 1
计算左子节点索引l为2*i+1;
r = 2 * i + 2
计算右子节点索引r为2*i+2;
largest = i
将最大值的索引设为i;
if l a[largest]:
如果左子节点的值大于当前最大值,则更新最大索引为l;
largest = l
将最大索引更新为左子节点;
if r a[largest]:
如果右子节点的值大于当前最大值,则更新最大索引为r;
largest = r
将最大索引更新为右子节点;
if largest == i:
如果最大索引仍等于当前索引i,说明已满足堆性质;
break
中断
a[i], a[largest] = a[largest], a[i]
a[i], a[largest] = a[largest], a[i]
i = largest
i = largest
build max heap
for i in range(n // 2 - 1, -1, -1):
for i in range(n // 2 - 1, -1, -1):
sift_down(i, n)
sift_down(i, n)
extract elements
for end in range(n - 1, 0, -1):
for end in range(n - 1, 0, -1):
a[0], a[end] = a[end], a[0]
a[0], a[end] = a[end], a[0]
sift_down(0, end)
sift_down(0, end)
return a
return a
429. 为什么 Java 的 String 是不可变(Immutable)的?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: java;标签: String, Immutability)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f35a4120fcc15911a9422 | 官方: 是 | 付费: 否
答案:
答案Java String 不可变主要带来:安全性(如密码/密钥等敏感数据不易被篡改)、并发友好(可在多线程中安全共享,减少同步需求)、缓存与复用(字符串常量池(String Constant Pool)提升内存与性能)、以及哈希稳定(作为哈希结构(Hash Structure) key 时更可靠、查找更高效)。这些因素共同提升了 Java 应用的稳定性与性能表现。
430. 用数组实现队列(Queue)有哪些缺点?为什么链表(Linked List)更合适?
- 知识点: 算法与数据结构 (主题: data-structures;标签: Queue, Array, Linked List)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 696f35a4120fcc15911a9426 | 官方: 是 | 付费: 否
答案:
答案数组实现队列的典型问题:空间浪费(出队后前部产生空位且难复用,除非做循环队列(Circular Queue)),以及固定容量(很难预估最大长度,扩容需要新建更大数组并复制元素,成本高)。链表实现队列则可以动态扩展、插入删除更灵活,避免频繁扩容复制带来的开销。
431. 区分归并排序(Merge Sort)与快速排序(Quick Sort)。
- 知识点: 算法与数据结构 (主题: algorithms;标签: Merge Sort, Quick Sort)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: general
- id: 696f4e7a120fcc15911fc05e | 官方: 是 | 付费: 否
答案:
Quick sort partitions the array (not necessarily equal halves), is in-place and typically fast due to cache locality, but has worst-case O(n^2) and is not stable by default.
快速排序将数组分区(不一定等分),是原地排序,通常因缓存局部性而速度快,但最坏情况为O(n^2),且默认不稳定。
Merge sort splits into halves, has O(n log n) worst/avg time, is stable, but requires extra memory and has poorer locality; often preferred for linked lists.
归并排序分为两半,最坏/平均时间为O(n log n),稳定,但需要额外内存且局部性较差;通常用于链表。
432. 给定一个只包含 0 和 1 的有序数组,找出第一个 '1' 的下标;若不存在返回 -1。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: Binary Search)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: general
- id: 696f4e7e120fcc15911fc612 | 官方: 是 | 付费: 否
答案:
Method:
方法:
Use binary search leveraging sorted order. Check mid; if a[mid]==0, answer is to the right. If a[mid]==1, it could be mid, but keep searching left to find the first 1.
利用有序顺序进行二分查找。检查中间元素;如果a[mid]==0,则答案在右侧。如果a[mid]==1,则可能是mid,但继续向左搜索以找到第一个1。
Example:
示例:
arr={0,0,0,0} => -1
arr={0,0,0,0} => -1
arr={0,0,0,0,1,1,1} => 4
arr={0,0,0,0,1,1,1} => 4
Code:
代码:
include
using namespace std;
using namespace std;
int searchIndex(int a[], int left, int right){
int searchIndex(int a[], int left, int right){
while(left<=right){
while(left<=right){
int mid = left + (right-left)/2;
int mid = left + (right-left)/2;
if(a[mid]==1 && (mid==0 || a[mid-1]==0)) return mid;
if(a[mid]==1 && (mid==0 || a[mid-1]==0)) return mid;
else if(a[mid]==1) left = mid-1;
else if(a[mid]==1) left = mid-1;
else left = mid+1;
else left = mid+1;
}
return -1;
return -1;
}
int main(){ int a[]={0,0,0,0}; int n=sizeof(a)/sizeof(a[0]); cout<<searchIndex(a,0,n-1); return 0; }
int main(){ int a[]={0,0,0,0}; int n=sizeof(a)/sizeof(a[0]); cout<<searchIndex(a,0,n-1); return 0; }
Output: -1
输出:-1
433. 请说说你对常见算法与数据结构(排序(Sorting)、查找(Searching)、树(Tree)、图(Graph)等)的理解,并举例说明你在项目里如何使用。
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: DSA)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- 公司: Carsales
- id: 69704554120fcc1591309c81 | 官方: 是 | 付费: 否
答案:
答案回答建议:先列常见结构(数组(Array)/哈希表(Hash Table)/堆(Heap)/树/图)与典型复杂度(Complexity),再给一个工程化例子:例如用哈希表做去重与计数、用堆做 TopK、用 BFS(Breadth-First Search)/DFS(Depth-First Search)处理依赖关系、用二分查找(Binary Search)优化查找。
强调:你不仅会背复杂度,也知道如何选型与做边界处理(Edge Case Handling)。
434. 如何优化一个低效的算法(Algorithm)?
- 知识点: 算法与数据结构 (主题: algorithms, performance;标签: optimization, complexity)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- 公司: Telstra
- id: 69709b4b120fcc15913a4d8b | 官方: 是 | 付费: 否
答案:
答题要点- 先量化:基准测试(Benchmark)+ 找热路径(Hot Path)(profiling)
- 再替换:更优复杂度的数据结构/算法(O(n²)→O(n log n)等)
- 再工程化:缓存、批处理、并行化、减少I/O与重复计算
- 最后验证:回归测试 + 线上指标对比
示例回答我会先用Profiler或基准测试定位最耗时的步骤,再分析复杂度并考虑替换算法或数据结构。例如排序/去重场景用哈希(Hash)或堆结构替代双重循环。之后再通过缓存(Caching)、批处理(Batch Processing)或并行化(Parallelization)降低常数项,并用测试与线上指标验证优化是否真实有效。
435. 你如何实现一个 LRU 缓存(LRU Cache)?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: python, data-structures;标签: lru, hashmap, linked-list)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Telstra
- id: 69709b51120fcc15913a53ec | 官方: 是 | 付费: 否
答案:
思路- 核心需求:O(1) 的 get/put + 按最近最少使用淘汰(Least Recently Used Eviction)
- 经典组合:哈希表(定位)+ 双向链表(维护访问顺序)
- Python可用 OrderedDict 简化;其他语言手写链表+Map
示例代码(Python,OrderedDict)from collections import OrderedDict
class LRUCache:
类 LRUCache:
def __init__(self, capacity: int):
def __init__(self, capacity: int):
self.capacity = capacity
设置自身容量为传入的容量
self.cache = OrderedDict()
self.cache = OrderedDict()
def get(self, key: int) -> int:
def get(self, key: int) -> int:
if key not in self.cache:
if key not in self.cache:
return -1
return -1
self.cache.move_to_end(key) # mark as recently used
self.cache.move_to_end(key) # 标记为最近使用
return self.cache[key]
return self.cache[key]
def put(self, key: int, value: int) -> None:
def put(self, key: int, value: int) -> None:
if key in self.cache:
if key in self.cache:
self.cache.move_to_end(key)
self.cache.move_to_end(key)
self.cache[key] = value
self.cache[key] = value
if len(self.cache) > self.capacity:
if len(self.cache) > self.capacity:
self.cache.popitem(last=False) # evict least recently used
self.cache.popitem(last=False) # 淘汰最久未使用的条目
436. 给定一个无序数组(Unsorted Array),如何找到第 K 大的元素?
- 知识点: 算法与数据结构 / 编程语言基础 (主题: python, algorithms;标签: quickselect, kth-element)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Telstra
- id: 69709b55120fcc15913a5727 | 官方: 是 | 付费: 否
答案:
思路- 用 Quickselect(选择算法,Quickselect):平均 O(n),最坏 O(n²)
- 每次选 pivot,把数组按大于/等于/小于 pivot 分区
- 只递归到包含第K大元素的那一边,避免全排序
示例代码(Python,Quickselect)import random
def kth_largest(nums, k):
def kth_largest(nums, k):
k is 1-based: k=1 returns the largest
pivot = random.choice(nums)
pivot = random.choice(nums)
highs = [x for x in nums if x > pivot]
highs = [x for x in nums if x > pivot]
lows = [x for x in nums if x < pivot]
lows = [x for x in nums if x < pivot]
pivots = [x for x in nums if x == pivot]
pivots = [x for x in nums if x == pivot]
if k <= len(highs):
if k <= len(highs):
return kth_largest(highs, k)
return kth_largest(highs, k)
if k > len(highs) + len(pivots):
if k > len(highs) + len(pivots):
return kth_largest(lows, k - len(highs) - len(pivots))
return kth_largest(lows, k - len(highs) - len(pivots))
return pivot
return pivot
437. 什么是排序算法(Sorting Algorithm)?解释冒泡排序(Bubble Sort)和归并排序(Merge Sort)的区别。
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: Sorting, Bubble Sort, Merge Sort)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69772669a39c9c5c3a8a0644 | 官方: 是 | 付费: 否
答案:
答案排序算法(Sorting Algorithm)用于按某种顺序(升序/降序)重排元素。冒泡排序(Bubble Sort)通过反复比较相邻元素并交换来把最大/最小值“冒”到一端,平均与最坏时间复杂度 O(n^2),适合小数据或教学;归并排序(Merge Sort)采用分治(Divide and Conquer),把数组拆分到最小单元后再合并成有序数组,时间复杂度 O(n log n),更适合大规模数据,但需要额外 O(n) 辅助空间。
438. 什么是图(Graph)?解释常见的图遍历算法 DFS 和 BFS。
- 知识点: 算法与数据结构 (主题: data-structures, graph;标签: Graph, DFS, BFS)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69772669a39c9c5c3a8a0648 | 官方: 是 | 付费: 否
答案:
答案图(Graph)由顶点(节点,Vertex/Node)和边(Edge)组成,用于表示关系网络。DFS(深度优先搜索,Depth-First Search)优先沿一条路径走到底再回溯,常用递归(Recursion)或栈(Stack)实现,适合路径搜索、拓扑排序(Topological Sorting)、连通性分析;BFS(广度优先搜索,Breadth-First Search)按层扩展访问邻居,常用队列(Queue)实现,天然适合求无权图最短路径与层级遍历。两者都需要记录 visited 防止重复访问。
439. 解释动态规划(Dynamic Programming)的概念,并给出一个非斐波那契的例子。
- 知识点: 算法与数据结构 (主题: algorithms, dynamic-programming;标签: DP, Knapsack, Optimal Substructure)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 6977267ca39c9c5c3a8a0e5e | 官方: 是 | 付费: 否
答案:
答案动态规划(Dynamic Programming,DP)用于解决“最优子结构 + 重叠子问题”的问题:把大问题拆成子问题,保存子问题的解(记忆化或表格法)避免重复计算,从而显著降低复杂度。典型例子是 0/1 背包(0/1 Knapsack):在容量限制下选择物品使价值最大,用 dpi 表示前 i 个物品、容量 w 的最大价值,通过“选/不选”转移求解;另一个常见例子是最长公共子序列(Longest Common Subsequence,LCS)。
440. 如何准备笔试中的 Coding round?
- 知识点: 算法与数据结构 (主题: algorithms, data-structures, coding-interview;标签: Coding Round, Edge Cases, Complexity)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69773446a39c9c5c3a8dc2be | 官方: 是 | 付费: 否
答案:
答案Coding round(编程测试)通常限时且题量少,关键是“模板化解题流程”:先明确输入输出与约束,再选合适数据结构(Data Structure)与算法(Algorithm),写出可运行版本后补齐边界条件(空输入、重复值、极端大小等)。训练时优先覆盖数组/字符串、哈希(Hash Table)、双指针(Two Pointers)、栈队列、排序与基础递归/DP。提交前快速检查复杂度与变量初始化,避免低级错误。
441. 描述编程中的递归(Recursion)概念。
- 知识点: 算法与数据结构 (主题: algorithms, recursion;标签: wipro, freshers, recursion)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69781f33a39c9c5c3ab3c986 | 官方: 是 | 付费: 否
答案:
答案递归(Recursion)是函数在执行过程中调用自身的技术,通过把复杂问题拆分为规模更小但结构相同的子问题来求解。每次递归都应朝着“基本情况(base case)”推进,达到基本情况时停止递归并逐层返回结果。递归常用于树/图遍历、分治算法、组合枚举与数学计算等场景;实现时要注意基本情况与递归深度,避免无限递归与栈溢出。
442. 描述二叉树(Binary Tree)的概念及其遍历算法。
- 知识点: 算法与数据结构 (主题: data-structures, trees;标签: wipro, binary-tree, traversal)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69781f33a39c9c5c3ab3c98c | 官方: 是 | 付费: 否
答案:
答案二叉树(Binary Tree)是一种层级数据结构,每个节点最多有两个子节点(左、右),最顶层为根节点(Root)。遍历(Traversal)用于按规则访问所有节点,常见有三种:中序(In-order:左→根→右)、先序(Pre-order:根→左→右)、后序(Post-order:左→右→根)。这些遍历是实现搜索、插入、删除、表达式求值、排序(如 BST 的中序有序)等操作的基础。
443. 解释堆栈(Stack)和队列(Queue)数据结构之间的区别。
- 知识点: 算法与数据结构 (主题: data-structures;标签: wipro, stack, queue)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69781f33a39c9c5c3ab3c992 | 官方: 是 | 付费: 否
答案:
答案栈(Stack)与队列(Queue)都是线性数据结构(Linear Data Structure),但访问规则不同:栈遵循后进先出(LIFO),只在栈顶进行入栈/出栈,常用于函数调用栈、撤销操作等;队列遵循先进先出(FIFO),一端入队另一端出队,常用于任务调度、消息缓冲等。两者在使用场景上分别匹配“最近优先”和“先来先服务”的需求。
444. 解释循环链表(Circular Linked List)的概念。
- 知识点: 算法与数据结构 (主题: data-structures, linked-list;标签: wipro, circular-linked-list)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69781f33a39c9c5c3ab3c99b | 官方: 是 | 付费: 否
答案:
答案循环链表(Circular Linked List)是一种链表(Linked List)结构,其中最后一个节点的 next 指针不指向 null,而是指回头节点(head),从而形成闭环。由于天然可循环遍历,它适合需要从任意节点开始连续迭代、轮询调度或环形缓冲等场景。循环链表(Circular Linked List)可以基于单链表(Singly Linked List)或双向链表(Doubly Linked List)实现,关键在于维护尾节点到头节点的链接关系。
445. 描述二分查找(Binary Search)算法的概念。
- 知识点: 算法与数据结构 (主题: algorithms, search;标签: wipro, binary-search)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69781f33a39c9c5c3ab3c9a2 | 官方: 是 | 付费: 否
答案:
答案二分查找(Binary Search)是一种在有序数组/列表中查找目标值的高效算法:每次取中间元素与目标比较,若目标更小则在左半区继续查找,若更大则在右半区继续查找,直到找到或区间为空。由于每轮都将搜索范围缩小一半,其时间复杂度为 O(log n),远优于线性查找(Linear Search)的 O(n)。
446. 解释动态规划(Dynamic Programming)的概念。
- 知识点: 算法与数据结构 (主题: algorithms, dynamic-programming;标签: wipro, dp)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69781f33a39c9c5c3ab3c9a6 | 官方: 是 | 付费: 否
答案:
答案动态规划(Dynamic Programming,DP)通过把问题拆分为重叠子问题,并把子问题结果缓存(记忆化,Memoization)或按表格自底向上计算(制表,Tabulation)来避免重复计算,从而优化时间复杂度。它适用于“最优子结构 + 子问题重叠”的问题,例如斐波那契、背包问题(Knapsack Problem)、最短路径、序列匹配等。设计 DP 时要明确状态定义、状态转移方程与边界条件。
447. 描述图(Graph)数据结构的概念及其遍历算法。
- 知识点: 算法与数据结构 (主题: data-structures, graphs, algorithms;标签: wipro, graph, dfs, bfs)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69781f33a39c9c5c3ab3c9aa | 官方: 是 | 付费: 否
答案:
答案图(Graph)由顶点(Vertex)与边(Edge)组成,用于表示实体间的连接关系,可分为有向/无向、加权/无权等类型。图的遍历用于系统访问节点,常见算法是 DFS(Depth-First Search,深度优先搜索:沿路径尽可能深入再回溯)与 BFS(Breadth-First Search,广度优先搜索:按层逐步扩展)。它们广泛用于路径搜索、连通性分析、拓扑排序、环检测等实际问题。
448. 排序算法有哪些不同类型?比较它们的时间复杂度。
- 知识点: 算法与数据结构 (主题: algorithms, sorting;标签: wipro, sorting, time-complexity)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69781f38a39c9c5c3ab3cdac | 官方: 是 | 付费: 否
答案:
答案常见排序算法包括冒泡(Bubble Sort)、插入(Insertion Sort)、选择(Selection Sort)、归并(Merge Sort)、快速(Quick Sort)与堆排序(Heap Sort)。性能对比常用时间复杂度衡量:冒泡/插入/选择平均与最坏多为 O(n²),适合小规模或近乎有序数据;归并与堆排序稳定在 O(n log n),适合大数据量;快速排序平均 O(n log n) 且常用,但最坏可到 O(n²),通常通过随机化/三数取中等策略降低风险。
449. 什么是树遍历(Tree Traversal)?
- 知识点: 算法与数据结构 (主题: data-structures, trees, algorithms;标签: tree-traversal)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 697825c7a39c9c5c3ab5939b | 官方: 是 | 付费: 否
答案:
答案树的遍历(Tree Traversal)是按一定规则访问树中所有节点的过程。常见三种深度优先遍历(Depth-First Traversal):中序(In-order Traversal:左→根→右)、先序(Pre-order Traversal:根→左→右)、后序(Post-order Traversal:左→右→根)。此外还有广度优先遍历(Breadth-First Traversal,层序遍历 Level-order Traversal),按层从上到下访问。
450. 深度优先遍历(DFS)是如何工作的?
- 知识点: 算法与数据结构 (主题: algorithms, graphs;标签: dfs)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 697825c7a39c9c5c3ab5939e | 官方: 是 | 付费: 否
答案:
答案深度优先搜索(DFS,Depth-First Search)优先沿着一条路径尽可能深入访问节点,直到无法继续再回溯到最近的分叉点继续探索。实现上常用栈(Stack,显式栈)或递归(隐含调用栈)。DFS 常用于路径搜索、连通分量、拓扑排序、环检测等。
451. 什么是搜索操作(Search Operation)?(以 BST 为例)
- 知识点: 算法与数据结构 (主题: data-structures, trees;标签: bst, search)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 697825d1a39c9c5c3ab59e0f | 官方: 是 | 付费: 否
答案:
答案这里通常指二叉搜索树(BST,Binary Search Tree)的搜索:从根节点开始,把目标值与当前节点比较;若目标更小则进入左子树,若更大则进入右子树,直到找到目标或到达空节点。BST 的搜索在树较平衡时平均为 O(log n),最坏退化为 O(n)。
452. 写一个程序判断回文数(Palindrome)。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: c, algorithms;标签: palindrome, c)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 697825d1a39c9c5c3ab59e15 | 官方: 是 | 付费: 否
答案:
答案思路:保存原始数字 number,然后通过取余(modulo)与整除(integer division)逐位反转得到 reversed,最后比较 number 与 reversed 是否相等。相等则为回文数(Palindrome)。
include <stdio.h>
int main() {
int main() {
int n, number, reversed = 0, remainder;
int n, number, reversed = 0, remainder;
// Input the number to check if it's a palindrome
// 输入要检查是否为回文数的数字
printf("Enter an integer: ");
printf("Enter an integer: ");
scanf("%d", &n);
scanf("%d", &n);
// Save the original number to compare later
// 保存原始数字以便稍后比较
number = n;
number = n;
// Reverse the number
// 反转数字
while (n != 0) {
while (n != 0) {
remainder = n % 10; // Get the last digit of the number
remainder = n % 10; // 获取数字的最后一位
reversed = reversed * 10 + remainder; // Build the reversed number
reversed = reversed * 10 + remainder; // 构建反转后的数字
n /= 10; // Remove the last digit from the number
n /= 10; // 从数字中移除最后一位
}
// Compare the original number with the reversed number
// 将原始数字与反转后的数字进行比较
if (number == reversed)
if (number == reversed)
printf("%d is a palindrome.\n", number); // If both are equal, it's a palindrome
printf("%d is a palindrome.\n", number); // 如果两者相等,则为回文
else
else
printf("%d is not a palindrome.\n", number); // Otherwise, it's not a palindrome
printf("%d is not a palindrome.\n", number); // 否则,不是回文
return 0;
return 0;
}
453. 写一个程序判断一个数是否为质数(Prime Number)。
- 知识点: 算法与数据结构 / 编程语言基础 (主题: c, algorithms;标签: prime, c)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 697825d6a39c9c5c3ab5a2d8 | 官方: 是 | 付费: 否
答案:
答案思路:质数(Prime Number)只能被 1 和自身整除。对 num 从 2 试除到 i*i <= num(等价于到 sqrt(num)),若存在整除则不是质数(Prime Number),否则是质数(Prime Number)。
include <stdio.h>
int main() {
int main() {
int num, i, isPrime = 1;
int num, i, isPrime = 1;
// 输入数字(Input Number)
printf("Enter the number to check if it is prime: ");
printf("Enter the number to check if it is prime: ");
scanf("%d", &num);
scanf("%d", &num);
// 处理小于2的情况,因为质数(Prime Number)必须大于1
if (num <= 1) {
if (num <= 1) {
printf("Number is not prime\n");
printf("Number is not prime\n");
return 0;
return 0;
}
// 检查从2到sqrt(num)之间的数是否能整除num
for (i = 2; i * i <= num; i++) {
for (i = 2; i * i <= num; i++) {
if (num % i == 0) {
if (num % i == 0) {
isPrime = 0;
isPrime = 0;
break;
break;
}
}
// 输出结果(Output Result)
if (isPrime) {
if (isPrime) {
printf("Number is prime\n");
printf("Number is prime\n");
} else {
} else {
printf("Number is not prime\n");
printf("Number is not prime\n");
}
return 0;
return 0;
}
454. TikTok 的技术面(Technical Round)通常如何组织?题目来源与备考策略是什么?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms, coderpad, hackerrank;标签: tiktok, technical-round, leetcode)
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 697887f9a39c9c5c3ad6951b | 官方: 是 | 付费: 否
答案:
答案技术面(Technical Round)通常 2–3 轮,每轮约 45 分钟,通过 CoderPad 或 HackerRank 等进行。面试官(Interviewer)通常拥有较大出题自由度,题库不一定标准化,因此题目变化快、会不断替换以保持难度;很多候选人建议按 LeetCode 风格 DS&A(Data Structures & Algorithms)强化训练,并在面试中清晰讲解思路与复杂度(Complexity)。常见题型包括链表(Linked List)、缓存(Cache,如 LRU)、字符串处理(String Processing)等,重点不仅是写对,还要沟通过程与时间管理(Time Management)。
455. Reverse words in a given string
反转给定字符串中的单词
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ecd6 | 官方: 是 | 付费: 否
答案:
解题思路:Split by spaces, reverse the list of words, then join with single spaces. If you must preserve multiple spaces, scan the string and rebuild tokens. Time O(n), space O(n).
456. Given a distance dist, count the total number of ways to cover the distance with 1, 2, and 3 steps.
给定一个距离 dist,计算用 1、2 和 3 步覆盖该距离的总方法数。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ecd9 | 官方: 是 | 付费: 否
答案:
解题思路:DP(Dynamic Programming): ways[d]=ways[d-1]+ways[d-2]+ways[d-3] with base cases. Return ways[dist]. Time O(dist), space O(1) if rolling.
457. Implement an LRU cache.
实现一个 LRU 缓存。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ecde | 官方: 是 | 付费: 否
答案:
解题思路:Use HashMap + Doubly Linked List(双向链表). Map key→node; list keeps MRU(Most Recently Used)at head, LRU(Least Recently Used)at tail. get/put in O(1).
458. Given an array of integers and a value, determine if any three integers in the array sum up to the value given.
给定一个整数数组和一个值,判断数组中是否有三个整数之和等于该给定值。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ece1 | 官方: 是 | 付费: 否
答案:
解题思路:Sort array, then for each i run two pointers (l,r). O(n^2) time, O(1) extra; handle duplicates carefully.
459. Determine if two binary trees are identical.
判断两棵二叉树是否相同。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ece4 | 官方: 是 | 付费: 否
答案:
解题思路:DFS(Depth-First Search)recursively compare structure and values; or BFS(Breadth-First Search)with queue pairs. O(n) time, O(h) stack.
460. Implement an Iterator over a binary tree with integer values. Your Iterator will be initialized with the root node.
在具有整数值的二叉树上实现一个迭代器。你的迭代器将使用根节点进行初始化。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ece7 | 官方: 是 | 付费: 否
答案:
解题思路:In-order iterator(中序迭代器): push left spine onto stack. next(): pop, then push left spine of right child. hasNext(): stack not empty. Amortized O(1) per op.
461. Clone a directed graph.
克隆一个有向图。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ecea | 官方: 是 | 付费: 否
答案:
解题思路:BFS(Breadth-First Search)/DFS(Depth-First Search) with hashmap(哈希映射) old→new. For each node(节点), create copy(副本) and wire neighbors(邻居). O(V+E).
462. Find all palindrome substrings.
找出所有回文子串。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ecf1 | 官方: 是 | 付费: 否
答案:
解题思路:Expand around centers(中心) (2n-1 centers(中心)) to collect palindromes(回文): O(n^2) time(时间), O(1) extra(额外); or Manacher(马拉车算法) for O(n) if needed.
463. Write an algorithm to find the largest sum subarray.
编写一个算法来找出最大和子数组。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ecf4 | 官方: 是 | 付费: 否
答案:
解题思路:Kadane’s algorithm(卡丹算法): track current best ending here and global best. O(n) time(时间), O(1) space(空间).
464. Search in a rotated array.
在旋转数组中查找。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ecf7 | 官方: 是 | 付费: 否
答案:
解题思路:Modified binary search(二分搜索) using sorted half logic. O(log n) if no duplicates(重复); with duplicates(重复) may degrade to O(n).
465. Given a linked list, zip it from its two ends in place, using constant extra space.
给定一个链表,使用常数额外空间,从两端开始就地对其进行压缩。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ecfa | 官方: 是 | 付费: 否
答案:
解题思路:Find middle (slow/fast)(快慢指针), reverse second half, then merge alternating nodes(节点). O(n) time(时间), O(1) extra(额外).
466. Given an array of numbers nums of size n, find products where products[i] is product of all nums[j] where j != i.
给定一个大小为n的数字数组nums,找出乘积,其中products[i]是所有nums[j]的乘积,且j不等于i。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ecfd | 官方: 是 | 付费: 否
答案:
解题思路:Prefix(前缀) and suffix(后缀) products(乘积): first pass build prefix(前缀), second pass multiply by suffix(后缀) running product(乘积). O(n) time(时间), O(1) extra(额外) besides output.
467. Given the head pointers of two linked lists representing integers, add the linked lists and return the new linked list.
给定两个表示整数的链表的头指针,将链表相加并返回新的链表。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed00 | 官方: 是 | 付费: 否
答案:
解题思路:Simulate grade-school addition(加法) with carry(进位); iterate both lists(链表), create new list(链表). If digits(数字) are forward order, reverse first or use stacks(栈).
468. Given an unsorted set of numbers from 1 to N with exactly two missing numbers, find those two missing numbers.
给定一个从1到N的无序数字集合,且恰好缺少两个数字,找出这两个缺失数字。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed03 | 官方: 是 | 付费: 否
答案:
解题思路:Use XOR(异或) partition or math(数学): sum(和) and sumsq(平方和) to solve two equations(方程). XOR(异或) method: xorAll then split by rightmost set bit(位). O(n).
469. Design a workflow diagram for a problem.
为问题设计一个工作流图。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed06 | 官方: 是 | 付费: 否
答案:
解题思路:Clarify inputs/outputs(输入/输出), stakeholders(利益相关者), failure modes(故障模式). Draw steps, decisions, data stores(数据存储), and monitoring(监控). Highlight idempotency(幂等性) and retries(重试).
470. A chessboard problem and its variations.
棋盘问题及其变体。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed09 | 官方: 是 | 付费: 否
答案:
解题思路:Confirm the exact variant. Common techniques: coloring invariants(着色不变量), BFS(广度优先搜索)/DP(动态规划) for moves, backtracking(回溯) for N-Queens(N皇后), bitmask(位掩码) optimization.
471. Given magicNumber() returns random 1 or 0, generate a random number using magicNumber().
给定magicNumber()返回随机的1或0,使用magicNumber()生成一个随机数。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed10 | 官方: 是 | 付费: 否
答案:
解题思路:If unbiased 0/1, build bits to form uniform range(均匀范围); if biased, use Von Neumann trick(冯·诺依曼技巧) to create fair bit (01→0,10→1) then assemble.
472. Theory behind common software engineering/algo/data structures concepts and problems.
常见软件工程/算法/数据结构概念和问题背后的理论。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed15 | 官方: 是 | 付费: 否
答案:
解题思路:Provide a clear approach, handle edge cases, and state time/space complexity.
473. Typical data structures, parsing, flow control, corner case handling.
典型的数据结构、解析、流程控制和边界情况处理。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed18 | 官方: 是 | 付费: 否
答案:
解题思路:Provide a clear approach, handle edge cases, and state time/space complexity.
474. Linked List Random Node.
链表随机节点。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed1b | 官方: 是 | 付费: 否
答案:
解题思路:Reservoir sampling(蓄水池抽样): iterate nodes(节点), keep result with probability(概率) 1/i at i-th node(节点). O(n) time(时间), O(1) space(空间).
475. Questions related to integrating interval ranges.
与整合区间范围相关的问题。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed1e | 官方: 是 | 付费: 否
答案:
解题思路:Sort intervals(区间) by start, then merge overlapping by tracking current [s,e]. O(n log n) time(时间).
476. What DataStructure would you consider to represent a File Structure (zipped) / Print the file structure with indentation: A.zip B.txt C.zip D.txt E.zip.
你会考虑用什么数据结构来表示一个文件结构(压缩的) / 打印带缩进的文件结构:A.zip B.txt C.zip D.txt E.zip。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed21 | 官方: 是 | 付费: 否
答案:
解题思路:Use a tree(树) (nodes(节点) with children list(子列表)). Parse tokens(标记), push/pop stack(栈) when entering/leaving zip, then DFS(深度优先搜索) print with depth indentation(缩进).
477. Find the least common ancestor of two nodes in a tree.
找出树中两个节点的最近公共祖先。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed24 | 官方: 是 | 付费: 否
答案:
解题思路:Binary tree(二叉树): recurse(递归); return node if matches, else combine left/right(左右子树). BST(二叉搜索树): walk down using value comparisons(值比较). O(n) or O(h).
478. Level of experience with iOS development.
iOS开发经验水平。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed27 | 官方: 是 | 付费: 否
答案:
解题思路:Discuss Swift/Obj-C basics(基础知识), UIKit/SwiftUI, memory management(内存管理), concurrency(并发) (GCD/async-await), testing(测试), and App Store constraints(约束).
479. Implement a quadtree.
实现一个四叉树。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed2d | 官方: 是 | 付费: 否
答案:
解题思路:Recursive node(递归节点) with 4 children(子节点); subdivide when capacity exceeded(容量超出). Insert/search by region(区域). Useful for spatial indexing(空间索引). Complexity depends on balance(平衡).
480. Write a function that can return the number of times that __ appears in a number.
编写一个函数,返回____在数字中出现的次数。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed30 | 官方: 是 | 付费: 否
答案:
解题思路:Digit-count problem(数字计数问题): for digit d in [0..9], count occurrences from 0..n using positional math(位数运算) (higher/cur/lower). O(log n).
481. OS Concepts.
操作系统概念。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed33 | 官方: 是 | 付费: 否
答案:
解题思路:Be ready for processes vs threads(进程与线程), scheduling(调度), memory (paging(分页)), synchronization(同步), deadlocks(死锁), filesystems(文件系统), and virtual memory(虚拟内存).
482. Median for a stream.
数据流的中位数。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed36 | 官方: 是 | 付费: 否
答案:
解题思路:Two heaps(双堆): max-heap(最大堆) for lower half, min-heap(最小堆) for upper half. Rebalance sizes(平衡大小); median from tops. O(log n) per insert(每次插入).
483. Implement a list.
实现一个列表。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed39 | 官方: 是 | 付费: 否
答案:
解题思路:Clarify: dynamic array(动态数组) vs linked list(链表). For dynamic array: resizing strategy(扩容策略), amortized O(1) append(均摊追加), bounds checks(边界检查), iterators(迭代器).
484. Debug a hash table implementation.
调试哈希表的实现。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed3c | 官方: 是 | 付费: 否
答案:
解题思路:Check hashing(哈希), modulo(取模), resizing(扩容), load factor(负载因子), collision handling(冲突处理) (chaining(链地址)/probing(探测)), tombstones(墓碑), and equality semantics(相等语义); add tests for edge cases(边界情况).
485. Matrix multiplication.
矩阵乘法。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed3f | 官方: 是 | 付费: 否
答案:
解题思路:Triple loop(三重循环) O(n^3) for dense(稠密); optimize cache by loop ordering/blocking(循环排序/分块); for sparse use compressed formats(压缩格式) and multiply only nonzeros(非零元素).
486. Write code to add/subtract two linked lists that contain a digit each to represent huge numbers.
编写代码来对两个链表进行加/减操作,每个链表包含一个数字,用于表示大数。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: data-structures, algorithms;标签: Apple SWE, Algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979d9e1c8f1f94b6461ed42 | 官方: 是 | 付费: 否
答案:
解题思路:Handle sign/compare magnitudes(符号/比较大小); for addition use carry(进位); for subtraction use borrow(借位). If forward order(正向顺序), use stacks(栈) or reverse(反转). Ensure removing leading zeros(前导零).
487. You are given an array of integers; determine if there are any three integers whose sum equals the given value.
给定一个整数数组,判断是否存在三个整数之和等于给定值。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: algorithms, arrays;标签: 3Sum, Two Pointers, Apple SWE)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979dba7c8f1f94b64623de0 | 官方: 是 | 付费: 否
答案:
这是 3Sum 的变体:先排序;遍历 i,把问题转成在区间 [i+1..n-1] 用双指针(双指针)寻找两数之和为 target-nums[i]。根据当前和大小移动左右指针,命中即返回 true。时间复杂度 O(n^2),额外空间 O(1)。
488. Clone a directed graph by creating a deep copy.
通过深拷贝克隆一个有向图。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: graphs, algorithms;标签: Graph, DFS, BFS, Apple SWE)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979dba7c8f1f94b64623de6 | 官方: 是 | 付费: 否
答案:
用 DFS/BFS 遍历图,并用哈希表(哈希表)记录 old→new 映射。访问节点时若未克隆则先创建副本;遍历邻居并把“邻居副本”加入当前副本的邻接表。映射表可防止有环图(有环图)的无限递归(递归)。
489. Apple Coding Interview Questions (from screenshot: Screen Shot 2025-03-27 at 17.02.32.png)
苹果编码面试问题(来自截图:Screen Shot 2025-03-27 at 17.02.32.png)
- 知识点: 算法与数据结构 / 行为与软技能 (主题: algorithms;标签: Screenshot, Apple Coding)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979dba8c8f1f94b64623e10 | 官方: 是 | 付费: 否
答案:
该题目列表来自截图附件。当前未提供可解析的文本内容;拿到截图中的题目文字后,可在此条目中补齐完整题目与答案要点。
490. Apple Coding Interview Questions (from screenshot: Screen Shot 2025-03-27 at 17.02.48.png)
苹果编码面试问题(来自截图:Screen Shot 2025-03-27 at 17.02.48.png)
- 知识点: 算法与数据结构 / 行为与软技能 (主题: algorithms;标签: Screenshot, Apple Coding)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Apple
- id: 6979dba8c8f1f94b64623e14 | 官方: 是 | 付费: 否
答案:
该题目列表来自截图附件。当前未提供可解析的文本内容;拿到截图中的题目文字后,可在此条目中补齐完整题目与答案要点。
491. Format an array of words into lines of specified length.
将单词数组格式化为指定长度的行。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: algorithms, data-structures;标签: Atlassian Coding)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Atlassian
- id: 6979de50c8f1f94b6462c73d | 官方: 是 | 付费: 否
答案:
遍历单词并尽量填满每一行不超过 max_width(最大宽度);把多余空格均匀分配到单词间(可用平均分配+余数补齐)。最后一行通常左对齐、单词间单空格,剩余补空格。
492. Find the missing number from an array spanning from 0 to n.
从0到n的数组中找出缺失的数字。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: algorithms, data-structures;标签: Atlassian Coding)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Atlassian
- id: 6979de50c8f1f94b6462c740 | 官方: 是 | 付费: 否
答案:
两种常用法:①用 set(集合)/布尔数组标记后从 0..n 扫描缺失值;②用等差数列求和 expected=n(n+1)/2,再减去实际数组和得到缺失数。时间 O(n),数学法额外空间 O(1)。
493. Select a random number from a stream with equal probability.
以等概率从流中随机选择一个数字。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: algorithms, data-structures;标签: Atlassian Coding)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Atlassian
- id: 6979de50c8f1f94b6462c743 | 官方: 是 | 付费: 否
答案:
用水塘抽样(Reservoir Sampling):维护一个当前选中值;当读到第 i 个元素时,以 1/i 的概率替换当前选中值。可证明每个元素最终被选中的概率都相同。
494. Write a Python function to find the longest increasing subsequence in a list of integers.
编写一个Python函数,求出整数列表中的最长递增子序列。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: algorithms, data-structures;标签: Atlassian Coding)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Atlassian
- id: 6979de50c8f1f94b6462c746 | 官方: 是 | 付费: 否
答案:
DP(Dynamic Programming):dp[i] 表示以 i 结尾的 LIS(Longest Increasing Subsequence)长度,遍历 j<i,若 nums[j]<nums[i] 则 dp[i]=max(dp[i],dp[j]+1),时间 O(n^2)。可用“耐心排序(Patience Sorting)”+二分(Binary Search)维护 tails 达到 O(n log n)。
495. Given the employees and departments table, write a query to get the top 3 highest employee salaries by department.
给定员工表和部门表,编写一个查询,按部门获取薪资最高的前3名员工。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: algorithms, data-structures;标签: Atlassian Coding)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Atlassian
- id: 6979de50c8f1f94b6462c749 | 官方: 是 | 付费: 否
答案:
用窗口函数(Window Function):按 department 分区(Partition),对 salary 进行 RANK()/DENSE_RANK()(降序),筛选 rank<=3;再 join departments 得到部门名,最后按部门与薪资排序输出。
496. 算法题:扫雷(Minesweeper)实现 reveal(),返回点开后揭示的 tile 数量。
- 知识点: 算法与数据结构
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69896edb69b2be043c3eb2b4 | 官方: 是 | 付费: 否
答案:
思路:若点到 bomb 则结束;否则从起点做 BFS(Breadth-First Search)/DFS(Depth-First Search):当格子邻雷数为 0 时继续扩展到 8 邻域;邻雷数 > 0 则只揭示该格不扩展。用 visited 防重复。返回 visited 的数量(或累计揭示数量)。
497. 算法题:给定 4 个整数与 + - × ÷,按原顺序通过任意括号组合判断能否得到 24。
- 知识点: 算法与数据结构
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69896edb69b2be043c3eb2b8 | 官方: 是 | 付费: 否
答案:
可用递归(Recursion)枚举括号切分:对序列 [a,b,c,d],选择切分点把序列分成左右两段,递归计算左右段所有可能结果,再用四则运算组合。由于顺序固定,切分只在相邻位置发生。注意除法与非整除、浮点误差(Floating-point Error)(用分数或 epsilon)。
498. 算法题:找 k 个最近点(k-nearest points)。
- 知识点: 算法与数据结构
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 69896edb69b2be043c3eb2bc | 官方: 是 | 付费: 否
答案:
常用解法:维护大小为 k 的最大堆(Max Heap)(按距离平方排序),遍历点集:堆未满则入堆;满则若当前距离更小替换堆顶。复杂度 O(n log k)。也可用快速选择(Quickselect)做到平均 O(n)。
499. (提示)Amazon 也会考 LeetCode 风格的算法题,你需要准备哪些方面?
- 知识点: 算法与数据结构
- 类型: technical | 难度: medium | 子类型:
- 分类: fullstack
- id: 698970a769b2be043c408026 | 官方: 是 | 付费: 否
答案:
重点准备:数组/字符串、哈希表(Hash Table)、栈/队列、二分(Binary Search)、双指针(Two Pointers)、DFS(Depth-First Search)/BFS(Breadth-First Search)、递归(Recursion)与回溯(Backtracking)、堆/优先队列(Priority Queue)、简单 DP(Dynamic Programming)、时间/空间复杂度(Time/Space Complexity)分析,以及常见边界(空输入、重复、溢出)。前端岗位也常结合 DOM(Document Object Model)/事件/异步等场景,但底层 CS(Computer Science)思维同样重要。
500. 编写代码检查三棵二叉树(Binary Tree)是否完全相同。
- 知识点: 算法与数据结构 (主题: tree, algorithms;标签: google, real-question, prepfully)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872b86 | 官方: 是 | 付费: 是
答案:
题目来源Prepfully 报告,Google SWE(Software Engineer)Technical Phone Screen(技术电话面试)真题。
思路分析递归(Recursion)比较三棵树的结构和值。可以先写比较两棵树的函数,再扩展到三棵。
解题方法方法一:递归(Recursion)同时递归遍历三棵树,比较每个节点的值。如果三个节点都为 null 返回 true,如果任一为 null 而其他不为 null 返回 false。
- 时间复杂度:O(n),n 为最小树的节点数
- 空间复杂度:O(h),h 为树高(递归栈)
评分要点- 能否正确处理 null 节点(Node)的边界情况 - 递归逻辑是否清晰
- 能否讨论迭代方法(使用队列 BFS)
501. 找到二叉树(Binary Tree)中最长的路径(序列)。
- 知识点: 算法与数据结构 (主题: tree, algorithms;标签: google, real-question, prepfully)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872b8c | 官方: 是 | 付费: 是
答案:
题目来源Prepfully 报告,Google SWE Technical Phone Screen 真题。类似 LeetCode 298/549。
思路分析DFS(深度优先搜索,Depth-First Search)遍历树(Tree),维护当前递增序列(Increasing Sequence)长度。当子节点值等于父节点值+1时,序列长度加1。
解题方法DFS + 全局最大值从根开始 DFS,每个节点检查左右子节点是否能延续序列。用全局变量维护最长序列。
- 时间复杂度:O(n)
- 空间复杂度:O(h)
评分要点- 能否正确定义"序列"(连续递增(Consecutive Increasing) vs 任意路径(Arbitrary Path)) - DFS 递归结构是否清晰
- 是否主动与面试官澄清序列的定义
502. 给定整数数组,返回所有和为0的不重复三元组(Triplet) [a,b,c]。
- 知识点: 算法与数据结构 (主题: array, sorting, algorithms;标签: google, real-question, igotanoffer)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872b95 | 官方: 是 | 付费: 是
答案:
题目来源IGotAnOffer 报告,Google SWE Onsite 高频真题。对应 LeetCode 15 (Three Sum),Medium。
思路分析排序(Sorting) + 双指针(Two Pointers)。先排序数组,固定一个数,用双指针在剩余部分寻找两数之和。注意跳过重复元素。
解题方法排序 + 双指针排序后遍历,对每个 nums[i],设 left=i+1, right=n-1。三数和小于0则 left++,大于0则 right--。跳过重复值避免重复三元组。
- 时间复杂度:O(n²)
- 空间复杂度:O(1)(不计输出)
评分要点- 能否避免 O(n³) 暴力解(Brute Force) - 去重逻辑是否正确
- 代码边界条件处理
503. 实现一个 Snapshot Array 快照数组(Snapshot Array)。
- 知识点: 算法与数据结构 (主题: array, data-structures, binary-search;标签: google, real-question, igotanoffer)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872b98 | 官方: 是 | 付费: 是
答案:
题目来源IGotAnOffer 报告,Google SWE Onsite 真题。对应 LeetCode 1146,Medium。
思路分析需要支持 set(index, val)、snap()、get(index, snap_id)。关键是不能每次 snap 复制整个数组。
解题方法TreeMap / Binary Search每个 index 维护一个 (snap_id → value) 的有序映射。snap() 只增加计数器。get() 通过二分查找(Binary Search)找到 - 时间复杂度(Time Complexity):set O(logS), snap O(1), get O(logS)
- 空间复杂度:O(设置次数)
评分要点- 能否避免每次 snap 复制数组(空间优化(Space Optimization)) - 是否使用有序映射实现高效查找
- 能否分析各操作复杂度
504. 找到给定数组中最长的连续子序列(Consecutive Subsequence)。
- 知识点: 算法与数据结构 (主题: array, hash-table;标签: google, real-question, prepfully)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872b9b | 官方: 是 | 付费: 是
答案:
题目来源Prepfully 报告,Google SWE Onsite Coding Round。对应 LeetCode 128,Medium。
思路分析使用 HashSet 存所有数,对每个可能的序列起点(即 num-1 不在集合中的数),向后扩展计算长度。
解题方法HashSet将所有数加入 HashSet。遍历每个数,如果 num-1 不在集合中(说明是序列起点),则从 num 开始向后扩展 num+1, num+2... 更新最大长度。
- 时间复杂度:O(n)
- 空间复杂度:O(n)
评分要点- 能否识别序列起点的优化 - 能否实现 O(n) 而非 O(nlogn) 排序方案
505. Delete Nodes And Return Forest:删除二叉树中指定节点后返回剩余的森林。
- 知识点: 算法与数据结构 (主题: tree, algorithms;标签: google, real-question, cnblogs)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872ba1 | 官方: 是 | 付费: 是
答案:
题目来源cnblogs 2025 Google 面经。对应 LeetCode 1110,Medium。
思路分析后序遍历 + HashSet。先处理子树再处理当前节点,避免断链问题。
解题方法后序 DFS将待删除节点放入 HashSet。后序遍历:如果当前节点需要删除,将非空子节点加入结果列表,返回 null。如果根节点未被删除,加入结果。
- 时间复杂度:O(n)
- 空间复杂度:O(n)
评分要点- 为什么选择后序遍历 - 如何处理根节点的特殊情况
506. 找到给定金额所需的最少硬币数量。
- 知识点: 算法与数据结构 (主题: dynamic-programming, algorithms;标签: google, real-question, igotanoffer)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872bad | 官方: 是 | 付费: 是
答案:
题目来源IGotAnOffer 报告,Google SWE Onsite。对应 LeetCode 322 (Coin Change),Medium。
思路分析经典 DP 问题。dp[i] 表示凑齐金额 i 所需的最少硬币数。
解题方法自底向上 DP初始化 dp[0]=0,其余为 ∞。对每个金额 i,遍历所有硬币面值 coin,dp[i] = min(dp[i], dp[i-coin]+1)。
- 时间复杂度:O(amount × coins)
- 空间复杂度:O(amount)
评分要点- DP 状态转移方程是否正确 - 能否分析为什么贪心不可行
- 边界处理:amount=0, 无解返回 -1
507. 生成所有可能的合法括号组合。
- 知识点: 算法与数据结构 (主题: string, algorithms;标签: google, real-question, igotanoffer)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872bb0 | 官方: 是 | 付费: 是
答案:
题目来源IGotAnOffer 报告,Google SWE Onsite。对应 LeetCode 22,Medium。
思路分析回溯法(Backtracking)。维护左括号和右括号的剩余数量,只在合法时添加。
解题方法回溯递归函数接收当前字符串、剩余左括号数 open、剩余右括号数 close。可以添加左括号(open > 0),可以添加右括号(close > open)。当长度达到 2n 时加入结果。
- 时间复杂度:O(4^n / √n)(第 n 个 Catalan 数)
- 空间复杂度:O(n)(递归深度)
评分要点- 回溯条件(Backtracking Condition)是否正确 - 能否解释 Catalan 数
508. 实现一个二叉搜索树(Binary Search Tree, BST)的迭代器(Iterator)。
- 知识点: 算法与数据结构 (主题: tree, data-structures, stack;标签: google, real-question, prepfully)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872bb3 | 官方: 是 | 付费: 是
答案:
题目来源Prepfully 报告,Google SWE Onsite。对应 LeetCode 173,Medium。
思路分析中序遍历(Inorder Traversal)BST 得到有序序列。用栈(Stack)模拟中序遍历的迭代版本。
解题方法栈 + 受控递归(Controlled Recursion)初始化时将根节点到最左叶节点的路径压栈。next():弹出栈顶,如果有右子树则将右子树的最左路径压栈。hasNext():栈非空。
- next() 均摊 O(1),hasNext() O(1)
- 空间复杂度:O(h)
评分要点- 是否理解"受控递归"的思想 - 均摊复杂度的分析
509. 在给定数组中找到 K 个最接近 X 的整数。
- 知识点: 算法与数据结构 (主题: array, binary-search, sorting;标签: google, real-question, prepfully)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872bb6 | 官方: 是 | 付费: 是
答案:
题目来源Prepfully 报告,Google SWE Onsite。对应 LeetCode 658,Medium。
思路分析排序数组(Sorted Array)中二分查找(Binary Search)X 的位置,然后用双指针(Two Pointers)向两侧扩展取最近的 K 个。
解题方法二分查找 + 双指针二分找到 X 的插入位置,然后设左右指针,每次取距 X 更近的一侧扩展,直到取满 K 个。
- 时间复杂度:O(log n + K)
- 空间复杂度:O(1)(不计输出)
评分要点- 能否想到二分查找优化 - 双指针扩展逻辑是否正确
- 当距离相等时如何处理
510. 在 2D 矩阵(2D Matrix)中找到只包含 X 不包含 O 的最大正方形(Maximal Square)。
- 知识点: 算法与数据结构 (主题: array, dynamic-programming;标签: google, real-question, prepfully)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872bb9 | 官方: 是 | 付费: 是
答案:
题目来源Prepfully 报告,Google SWE Onsite Coding Round。类似 LeetCode 221 (Maximal Square)。
思路分析DP(Dynamic Programming)问题。dpi 表示以 (i,j) 为右下角的最大全 X 正方形边长。
解题方法动态规划(Dynamic Programming)如果 matrixi == 'X',dpi = min(dpi-1, dpi, dpi-1) + 1。否则 dpi = 0。维护全局最大值(global maximum)。
- 时间复杂度:O(m×n)
- 空间复杂度:O(m×n),可优化至 O(n)
评分要点- DP 状态转移方程(state transition equation) - 能否解释为什么取三者最小值
- 空间优化技巧
511. 什么是实现自动补全(autocomplete)功能的最佳数据结构(data structure)?用代码演示。
- 知识点: 算法与数据结构 (主题: tree, data-structures;标签: google, real-question, prepfully)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Google
- id: 69a6c9a51fac73b30e872bbc | 官方: 是 | 付费: 是
答案:
题目来源Prepfully 报告,Google SWE Onsite。开放式设计+编码混合题。
思路分析Trie(前缀树,prefix tree)是自动补全的最佳数据结构。支持 O(L) 前缀查找(prefix search)(L 为前缀长度)。
解题方法Trie 实现TrieNode 包含 children 映射(map)和 isEnd 标记(flag)。实现 insert(word)、search(prefix) 返回所有匹配词。可优化:在每个节点存储 top-K 热门词(top-K popular words)。
- insert: O(L), search prefix: O(L + 结果数)
- 空间复杂度:O(总字符数)
评分要点- 能否解释为什么 Trie 优于 HashMap(哈希映射) - 代码实现是否完整
- 能否讨论生产环境优化(压缩 Trie、频率排序)
512. 完成 HackerRank CodePair 在线编程测试(online coding test),要求在限定时间内解决算法题目,并分析时间复杂度(time complexity)和空间复杂度(space complexity)。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures, coding;标签: jetstar, real-question, glassdoor, swe, hackerrank)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- 公司: Jetstar Airways
- id: 69b2b81b58d557c90297ab6b | 官方: 是 | 付费: 是
答案:
题目来源Glassdoor / InterviewCoder 报告,Jetstar Airways 软件工程师面试流程中的技术评估环节。HackerRank CodePair 是 Jetstar 技术岗位常用的在线编程平台。
思路分析Jetstar 的 HackerRank CodePair 测试通常涵盖基础算法和数据结构题目,难度为中等偏下。作为航空业公司,Jetstar 更注重候选人的问题解决能力和代码质量,而非极端算法难度。
准备建议- 常见题型:数组操作(array manipulation)、字符串处理(string processing)、哈希表(hash table)、基础排序与搜索(sorting and searching)
- 时间复杂度:面试官会要求你分析每个解法的 Big O 复杂度
- 空间复杂度:同样需要说明额外空间使用情况
- 代码风格:保持代码清晰、有注释、变量命名规范
评分要点- 能否在限定时间内完成题目 - 代码是否正确处理边界条件
- 是否主动讨论时间和空间复杂度
- 代码可读性和组织结构
513. Find out smallest and largest number in a given Array?
在给定的数组中找出最小和最大的数字?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99468 | 官方: 否 | 付费: 否
答案:
https://www.scaler.com/topics/difference-between-array-and-arraylist/https://www.scaler.com/topics/difference-between-array-and-arraylist/https://www.scaler.com/topics/difference-between-array-and-arraylist/https://www.scaler.com/topics/difference-between-array-and-arraylist/https://www.scaler.com/topics/difference-between-array-and-arraylist/https://www.scaler.com/topics/difference-between-array-and-arraylist/https://www.scaler.com/topics/difference-between-array-and-arraylist/ 方法:
- For storing the largest and smallest numbers create two variables named smallest and largest.
- Assign Integer.MAX_VALUE to the variable smallest
- Assign Integer.MIN_VALUE to the variable largest
- In each traversal of for loop, we will compare the current element with the largest and smallest number and update the value accordingly.
- If a number is larger than the largest, then it can not be smaller than the smallest, therefore, we can skip if the first condition holds.
import java.util.*;
import java.util.*;
public class InterviewBit{
public class InterviewBit{
public static void main(String args[]) {
public static void main(String args[]) {
int[] inputArray = {10,20, 22, 30, 77};
int[] inputArray = {10,20, 22, 30, 77};
int largest = inputArray[0];
int largest = inputArray[0];
int smallest = inputArray[0];
int smallest = inputArray[0];
for( int number : inputArray ) {
for( int number : inputArray ) {
if(number > largest) {
if(number > largest) {
largest = number;
largest = number;
}
else if (smallest > number) {
else if (smallest > number) {
smallest = number;
smallest = number;
}
}
System.out.println("Largest and Smallest numbers are "
System.out.println("Largest and Smallest numbers are "
largest +" "+smallest);
- largest +" "+smallest);
}
}
Output :
输出:
- largest +" "+smallest);
Largest and Smallest numbers are 77 10
Largest and Smallest numbers are 77 10
Conclusion
结论
In this article, we have covered the most important and commonly asked interview questions based on arrays. To make the most of all the knowledge available, it is absolutely necessary to practice data structures and algorithms as much as possible. You should keep in mind certain properties of array data structures, for example, array index starts at 0, the elements of an array are stored in contiguous memory locations, etc.
在本文中,我们涵盖了基于数组的最重要且常被问及的面试问题。为了充分利用已有的知识,尽可能多地练习数据结构和算法是绝对必要的。你应该记住数组数据结构的某些特性,例如,数组索引从0开始,数组元素存储在连续的内存位置中,等等。
Additional Interview Resources: - Top Array Coding Problems for Interviews
更多面试资源:- 面试中常见的顶级数组编码问题
- Data Structure Interview Questions
- Algorithm Interview Questions
- DSA Tutorial
- InterviewBit Blog-Coding Problems
- DSA Courses
- Coding Interview Questions
- Technical Interview Questions
- Array vs ArrayList
514. Check for balanced parenthesis in an expression using constant space.
检查表达式中的括号是否使用常量空间平衡配对。
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b9946b | 官方: 否 | 付费: 否
答案:
- You will be given string str containing characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, your task is to determine whether the brackets are balanced or not.
These conditions should satisfy for balanced brackets:
Open brackets must be closed by the same type of brackets.开括号必须由相同类型的闭括号闭合。
Open brackets must be closed in the correct order.
开括号必须按正确的顺序闭合。
Approach: - To keep track of two brackets to be compared keep two variables i and j.
方法:- 为了追踪待比较的两个括号,使用两个变量 i 和 j。- Maintain a count variable and increment its value on encountering an opening bracket and decrements on encountering a closing bracket.
- Assign values of j and i as- j = i, i = i + 1 and counter++ when opening brackets are encountered.
When Closing brackets are encountered do count– i,e decrement its value and compare brackets at i and j,
If brackets at i and j match, then substitute ‘#’ in the string at ith and jth position. Increment i and decrement j until non ‘#’ value is encountered or j ≥ 0. If brackets at i and j do not match, return false. - If count != 0, return false.如果 i 和 j 处的括号匹配,则将字符串中第 i 和第 j 个位置替换为‘#’。递增 i 并递减 j,直到遇到非‘#’的值或 j ≥ 0。如果 i 和 j 处的括号不匹配,则返回 false。- 如果 count != 0,则返回 false。
import java.util.*;
import java.util.*;
class InterviewBit
class InterviewBit
{
static String str = "[[]]";
static int Count = 0;
static int Count = 0;
static int i = 0;
static int i = 0;
static int j = -1;
static int j = -1;
static int helperFunc(char compare)
static int helperFunc(char compare)
{
Count--;
Count--;
char temp = str.charAt(j);
char temp = str.charAt(j);
if (j > -1 && temp == compare)
if (j > -1 && temp == compare)
{
str = str.replace(str.charAt(i),'#');
str = str.replace(str.charAt(i),'#');
str = str.replace(str.charAt(j),'#');
str = str.replace(str.charAt(j),'#');
temp = str.charAt(j);
temp = str.charAt(j);
while (j >= 0 && temp == '#')
while (j >= 0 && temp == '#')
j--;
j--;
i++;
i++;
return 1;
return 1;
}
else
else
return 0;
return 0;
}
static boolean isValid()
static boolean isValid()
{
if (str.length() == 0)
if (str.length() == 0)
return true;
返回 true;
else {
否则 {
int result;
int result;
while (i < str.length())
while (i < str.length())
{
char temp = str.charAt(i);
char temp = str.charAt(i);
if(temp=='}')
if (temp=='}')
{
result = helperFunc('{');
result = helperFunc('{');
if (result == 0)
if (result == 0)
{
return false;
返回 false;
}
}
else if(temp == ')')
else if (temp == ')')
{
result = helperFunc('(');
result = helperFunc('(');
if (result == 0)
if (result == 0)
{
return false;
返回 false;
}
}
else if(temp == ']')
else if (temp == ']')
{
result = helperFunc('[');
result = helperFunc('[');
if (result == 0)
if (result == 0)
{
return false;
返回 false;
}
}
else
else
{
j = i;
j = i;
i++;
i++;
Count++;
Count++;
}
}
if (count != 0)
if (count != 0)
return false;
返回 false;
return true;
返回 true;
}
}
public static void main(String args[])
public static void main(String args[])
{
if (isValid())
if (isValid())
System.out.println("No");
System.out.println("No");
else
else
System.out.println("Yes");
System.out.println("Yes");
}}
515. Two sum of an array: In this question you will be given an array arr and a target. You have to return the indices of the two numbers such that they add up to target.
两数之和:在这个问题中,你会得到一个数组arr和一个目标值。你必须返回两个数字的索引,使它们相加等于目标值。
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b9946e | 官方: 否 | 付费: 否
答案:
In this question, you will be given an array arr and a target. You have to return the indices of the two numbers such that they add up to the target.
在这个问题中,你会得到一个数组arr和一个目标值。你必须返回两个数字的索引,使它们相加等于目标值。
Approach :
方法:
So the easiest and most efficient solution is using a HashMap. We have to iterate through all the elements of the array and if (target-num) is present in the array then return {lower index, higher index} else push the value at arr[i] and the index i in the hashmap.
所以最简单且最有效的解决方案是使用HashMap。我们必须遍历数组中的所有元素,如果(target-num)存在于数组中,则返回{较低索引,较高索引},否则将arr[i]处的值和索引i放入hashmap中。
public class InterviewBit {
public class InterviewBit {
public int[] twoSum(int[] arr, int target) {
public int[] twoSum(int[] arr, int target) {
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for(int i = 0; i <arr.length; i++){
for(int i = 0; i <arr.length; i++){
Integer diff = (Integer)(target - arr[i]);
Integer diff = (Integer)(target - arr[i]);
if(hash.containsKey(diff)){
if(hash.containsKey(diff)){
int toReturn[] = {hash.get(diff)+1, i+1};
int toReturn[] = {hash.get(diff)+1, i+1};
return toReturn;
return toReturn;
}
hash.put(arr[i], i);
hash.put(arr[i], i);
}
return null;
返回 null;
}
}
The time Complexity for this approach will be O(n).
这种方法的时间复杂度将是O(n)。
516. How do you rotate an array?
你如何旋转一个数组?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99471 | 官方: 否 | 付费: 否
答案:
You will be given an input number N and N numbers following it as the input. You are also given an integer K which represents how many times you have to rotate the array. Rotate the array K values to the right if K is positive and K values to the left if K is negative. If K=0, do not rotate the array.
你将会得到一个输入数字N,以及紧随其后的N个数字作为输入。你还会得到一个整数K,它代表你需要将数组旋转多少次。如果K为正数,则将数组向右旋转K个值;如果K为负数,则向左旋转K个值。如果K=0,则不旋转数组。
The figure shows how the rotating array will look if k=2.
图中显示了当k=2时旋转后的数组形态。
Approach:
方法:
If the value of K is positive then do K=K%N where N is the length of the input array for eg: if k =10 and N=3 then k will become 1 which means rotating the array 10 times is equivalent to rotating the array 1 time.Similarly, If the value of K is negative, K=K%N + N. 2. Reverse the first part of the array i.e. from 0 to N-K-1 and the second part from N-K to N-1 separately. 3. Reverse the entire array i.e. from 0 to N-1. K determines how the array will be rotated.
- 如果K的值为正数,则执行K=K%N,其中N是输入数组的长度,例如:如果k=10且N=3,则k将变为1,这意味着将数组旋转10次等同于旋转1次。类似地,如果K的值为负数,则K=K%N + N。 2. 先分别反转数组的第一部分,即从0到N-K-1,以及第二部分,即从N-K到N-1。 3. 再反转整个数组,即从0到N-1。K决定了数组将如何被旋转。
Code:
代码:
import java.io.*;
import java.io.*;
import java.util.*;
import java.util.*;
public class Main {
public class Main {
public static void display(int[] arr) {
public static void display(int[] arr) {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder();
for (int val : arr) {
for (int val : arr) {
sb.append(val + " ");
sb.append(val + " ");
}
System.out.println(sb);
System.out.println(sb);
}
public static void reverse(int[] arr, int li, int ri) {
public static void reverse(int[] arr, int li, int ri) {
while (li < ri) {
while (li < ri) {
int t = arr[li];
int t = arr[li];
arr[li] = arr[ri];
arr[li] = arr[ri];
arr[ri] = t;
arr[ri] = t;
li++;
li++;
ri--;
ri--;
}
}
public static void rotate(int[] arr, int k) {
public static void rotate(int[] arr, int k) {
k = k % arr.length;
k = k % arr.length;
if (k < 0) {
如果 (k < 0) {
k += arr.length;
k += arr.length;
}
reverse(arr, 0, arr.length - k - 1);
reverse(arr, 0, arr.length - k - 1);
reverse(arr, arr.length - k, arr.length - 1);
reverse(arr, arr.length - k, arr.length - 1);
reverse(arr, 0, arr.length - 1);
reverse(arr, 0, arr.length - 1);
}
public static void main(String[] args) throws Exception {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
整数[] arr = 新整数[n];
for (int i = 0; i < n; i++) {
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(br.readLine());
arr[i] = Integer.parseInt(br.readLine());
}
int k = Integer.parseInt(br.readLine());
int k = Integer.parseInt(br.readLine());
rotate(arr, k);
rotate(arr, k);
display(arr);
display(arr);
}
517. How do you sort an array of 0 and 1?
如何对一个包含0和1的数组进行排序?
- 知识点: 算法与数据结构 (主题: arrays, data-structures;标签: interviewbit, array, topic-specific, arrays, data-structures)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b3793e58d557c902b99474 | 官方: 否 | 付费: 否
答案:
You are given an array of 0s and 1s in random order and you have to sort this array i.e Segregate 0s on the left side and 1s on the right side of the array.
你得到一个由0和1组成的数组,顺序是随机的,你需要对这个数组进行排序,即将0分割到数组的左侧,将1分割到数组的右侧。
Approach: - Maintain two indexes and Initialize the first index as 0 and second index n-1.
方法: - 维护两个索引,并将第一个索引初始化为0,第二个索引初始化为n-1。
- Now follow the following algorithm until left class InterviewBit
{
void segregatearray(int arr[], int size)
void segregatearray(int arr[], int size)
{
int left = 0, right = size - 1;
int left = 0, right = size - 1;
while (left < right)
while (left < right)
{
while (arr[left] == 0 && left < right)
while (arr[left] == 0 && left < right)
left++;
left++;
while (arr[right] == 1 && left < right)
while (arr[right] == 1 && left < right)
right--;
right--;
if (left < right)
if (left < right)
{
arr[left] = 0;
arr[left] = 0;
arr[right] = 1;
arr[right] = 1;
left++;
left++;
right--;
right--;
}
}
}
public static void main(String[] args)
public static void main(String[] args)
{
Segregate seg = new Segregate();
Segregate seg = new Segregate();
int arr[] = new int[]{0, 1, 0, 1, 1, 1};
int arr[] = new int[]{0, 1, 0, 1, 1, 1};
int i, arr_size = arr.length;
int i, arr_size = arr.length;
seg.segregatearray(arr, arr_size);
seg.segregatearray(arr, arr_size);
System.out.print("Array after segregation is ");
System.out.print("分离后的数组是 ");
for (i = 0; i < 6; i++)
for (i = 0; i < 6; i++)
System.out.print(arr[i] + " ");
System.out.print(arr[i] + " ");
}
}
Time Complexity : O(n)
时间复杂度:O(n)
518. 设计一个算法,在未排序的数组中找到第 K 大的元素(K-th Largest Element),要求平均时间复杂度(Average Time Complexity)O(n)。
- 知识点: 算法与数据结构 (主题: algorithms;标签: canva, generated)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: design
- 公司: 可画
- id: 69b379cd58d557c902b9ffaf | 官方: 是 | 付费: 是
答案:
思路分析使用快速选择(QuickSelect)算法,基于快排分区思想。每次分区后只需处理一半数据。
参考答案选择 pivot,分区后判断 pivot 位置与 K 的关系,递归处理对应一侧。平均 O(n),最坏 O(n²),可通过随机化 pivot 优化。
评分要点- 理解 QuickSelect vs 完整排序(Full Sorting)的效率差异
- 正确实现分区逻辑
- 分析平均和最坏时间复杂度
- 了解随机化优化策略
常见追问- 如何保证最坏情况也是 O(n)?(Median of Medians) - 堆方法的时间复杂度对比?
519. 实现一个 Trie(前缀树)(Prefix Tree),支持 insert、search 和 startsWith 操作。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: canva, generated)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: design
- 公司: 可画
- id: 69b379cd58d557c902b9fffa | 官方: 是 | 付费: 是
答案:
思路分析每个节点包含子节点映射(Child Node Mapping)和是否为单词结尾的标志(End-of-Word Flag)。insert/search/startsWith 都沿着字符路径遍历。
参考答案TrieNode: children={}, isEnd=False。Insert: 逐字符创建节点路径。Search: 逐字符查找,检查 isEnd。StartsWith: 逐字符查找,不检查 isEnd。
评分要点- 正确的节点结构设计(Node Structure Design)
- 三个操作的正确实现
- 时间复杂度分析 O(m),m 为字符串长度
常见追问- 如何实现自动补全功能(Auto-complete Functionality)? - Trie 在Canva Editor搜索功能中的应用?
520. 给定一个有向图(Directed Graph),检测其中是否存在环(Cycle)。请给出两种不同的解法。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: canva, generated)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: design
- 公司: 可画
- id: 69b379cd58d557c902b9fffd | 官方: 是 | 付费: 是
答案:
思路分析方法1: DFS(深度优先搜索,Depth-First Search)+ 三色标记(Three-Color Marking)(白/灰/黑)。方法2: 拓扑排序(Topological Sorting)(Kahn's BFS),若无法完成则有环。
参考答案DFS: 维护 visiting(灰色)集合,遇到灰色节点则有环。拓扑排序: 入度(In-degree)为0的节点入队,处理完后若还有未访问节点则有环。
评分要点- 两种方法的正确实现
- 时间空间复杂度分析
- 理解两种方法的适用场景
常见追问- 如何输出环的具体路径? - 在Canva Editor的依赖管理中如何应用?
521. 实现一个最小栈(Min Stack),支持 push、pop、top 和 getMin 操作,所有操作均为 O(1)。
- 知识点: 算法与数据结构 (主题: algorithms, data-structures;标签: canva, generated)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: design
- 公司: 可画
- id: 69b379ce58d557c902ba0040 | 官方: 是 | 付费: 是
答案:
思路分析使用辅助栈(Auxiliary Stack)同步记录每个状态下的最小值。或在主栈中存储差值。
参考答案双栈法:主栈存数据,辅助栈存当前最小值。Push 时比较并压入辅助栈;Pop 时同步弹出。
评分要点- O(1) 时间和空间效率
- 正确处理重复最小值
- 边界情况处理
常见追问- 如何只用一个栈实现? - 如何扩展支持 getMax?
522. 给定一个矩阵(Matrix),找出从左上角到右下角的最小路径和(Minimum Path Sum)。只能向下或向右移动。
- 知识点: 算法与数据结构 (主题: algorithms, dynamic-programming;标签: canva, generated)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: design
- 公司: 可画
- id: 69b379ce58d557c902ba0043 | 官方: 是 | 付费: 是
答案:
思路分析经典动态规划(Dynamic Programming)。dpi = gridi + min(dpi-1, dpi)。
参考答案初始化第一行和第一列为累加和,然后逐行逐列填充 dp 表。可原地修改节省空间。
评分要点- 正确的状态转移方程(State Transition Equation)
- 边界条件处理
- 空间优化(一维 dp 或原地修改)
常见追问- 如何输出具体路径? - 如果可以上下左右四个方向移动呢?
523. 设计并实现一个支持 O(1) 插入、删除和随机获取的数据结构(Data Structure)。
- 知识点: 算法与数据结构 / 系统设计/架构 / UI/UX 设计 (主题: algorithms, data-structures, system-design;标签: canva, generated)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: design
- 公司: 可画
- id: 69b379ce58d557c902ba0089 | 官方: 是 | 付费: 是
答案:
思路分析结合 ArrayList 和 HashMap。ArrayList 存数据实现 O(1) 随机访问(Random Access),HashMap 存值到索引的映射实现 O(1) 查找删除(Lookup and Deletion)。
参考答案Insert(插入): 添加到数组(Array)末尾,记录索引(Index)。Delete(删除): 将待删元素与末尾交换,更新映射(Mapping),删除末尾。GetRandom(随机获取): 随机索引访问数组(Array)。
评分要点- 正确的数据结构(Data Structure)选择
- 删除操作的交换技巧
- 所有操作 O(1) 的正确性
常见追问- 如何支持重复元素(Duplicate Elements)? - 在Canva Editor的实际应用场景?
524. What is dynamic programming? How is it different from greedy algorithms?
什么是动态规划?它与贪心算法有何不同?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a4d58d557c902ba5168 | 官方: 否 | 付费: 否
答案:
Dynamic Programming (DP) is an algorithmic technique used to solve problems by breaking them into smaller overlapping subproblems and storing their results to avoid recomputation.
动态规划(DP)是一种算法技术,通过将问题分解为更小的重叠子问题并存储其结果以避免重复计算来解决复杂问题。
DP is applicable when two properties exist:
当满足两个性质时,DP适用:
Optimal substructure (optimal solution can be built from optimal sub-solutions) 2. Overlapping subproblems
- 最优子结构(最优解可由最优子解构建) 2. 重叠子问题
There are two common approaches: - Top-down (memoization): Recursive solution with caching.
有两种常见方法:- 自顶向下(记忆化):带缓存的递归解法。
Bottom-up (tabulation): Iterative solution building from smallest cases.
Classic DP problems: - 0/1 Knapsack经典DP问题:- 0/1背包问题
- Longest Common Subsequence (LCS)
- Matrix Chain Multiplication
Fibonacci with memoization
Greedy algorithms, in contrast, make the locally optimal choice at each step without reconsidering previous decisions. They do not store subproblem results.相比之下,贪心算法在每一步选择局部最优解而不重新考虑之前的决策。它们不存储子问题的结果。
Greedy works only when the greedy choice property holds, meaning a locally optimal choice leads to a globally optimal solution.
贪心算法仅在满足贪心选择性质时有效,即局部最优选择能导致全局最优解。
Examples: - Fractional Knapsack -> Greedy works.
示例:- 分数背包 -> 贪心算法有效。
- 0/1 Knapsack -> Requires DP.
Dijkstra’s algorithm -> Greedy (for non-negative weights).
Key differences:关键区别:
| Aspect 方面 | Dynamic Programming 动态规划 | Greedy 贪心 |
|---|---|---|
| Stores subproblems 存储子问题 | Yes 是 | No 否 |
| Revisits decisions 重新审视决策 | Yes 是 | No 否 |
| Guarantees global optimum 保证全局最优 | Yes (if applicable) 是(如适用) | Only when property holds 仅当性质成立时 |
| Complexity 复杂度 | Often higher 通常较高 | Usually lower 通常较低 |
DP typically has higher time and space complexity but guarantees correctness for complex optimization problems.
动态规划通常具有更高的时间和空间复杂度,但能在复杂优化问题中保证正确性。
In interviews, common traps can be: - Confusing recursion with DP (recursion alone is not DP).
在面试中,常见陷阱可能是:- 混淆递归与动态规划(仅递归不是动态规划)。
- Not identifying overlapping subproblems.
- Applying greedy where DP is required.
525. Explain time complexity and space complexity. What is Big-O notation?
解释时间复杂度和空间复杂度。什么是大O表示法?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba516b | 官方: 否 | 付费: 否
答案:
Time complexity measures how an algorithm’s running time grows as the input size increases. It does not measure actual time in seconds, it measures growth rate relative to input size nnn.
时间复杂度衡量算法运行时间随输入规模增长的情况。它不测量实际秒数,而是测量相对于输入大小 nnn 的增长速率。
Space complexity measures how much memory an algorithm uses as input size increases. This includes: - Input space
空间复杂度衡量算法随输入规模增长使用的内存量。这包括:- 输入空间
Auxiliary space (extra memory used by the algorithm)
The most common way to express complexity is using Big-O notation . Big-O describes the upper bound (worst-case growth rate) of an algorithm.表达复杂度的最常见方式是使用大O表示法。大O描述算法的上界(最坏情况增长速率)。
For example: - Binary Search runs in O(log n) because the search space is halved each step.
例如:- 二分搜索运行时间为 O(log n),因为每一步搜索空间减半。
- Merge Sort runs in O(n log n) due to dividing and merging.
Bubble Sort runs in O(n²) because of nested comparisons.
Common complexities:常见复杂度:
| Complexity 复杂度 | Meaning 含义 | Example 示例 |
|---|---|---|
| O(1) | Constant time 常数时间 | Access array element 访问数组元素 |
| O(log n) | Logarithmic 对数 | Binary search 二分搜索 |
| O(n) | Linear 线性 | Linear search 线性搜索 |
| O(n log n) | Linearithmic 线性对数 | Merge sort 归并排序 |
| O(n²) | Quadratic 二次 | Bubble sort 冒泡排序 |
| O(2ⁿ) | Exponential 指数 | Subset generation 子集生成 |
Big-O is not the only notation: - Big-Ω (Omega): Best-case lower bound.
大O不是唯一表示法:- 大-Ω(Omega):最佳情况的下界。
Big-Θ (Theta): Tight bound (exact asymptotic growth).
For example, linear search: - Best case: O(1)例如,线性搜索:- 最佳情况:O(1)
- Worst case: O(n)
Average case: Θ(n)
Another important concept is amortized analysis . Some operations may occasionally be expensive, but over many operations, the average cost is small. For instance, dynamic arrays (like vectors) occasionally resize (O(n)), but insertion is amortized O(1) because resizing happens infrequently.另一个重要概念是均摊分析。某些操作可能偶尔昂贵,但在大量操作中,平均成本较小。例如,动态数组(如向量)偶尔调整大小(O(n)),但插入的均摊复杂度为 O(1),因为调整大小并不频繁。
526. What is hashing? Explain hash tables and collision resolution techniques.
什么是哈希?解释哈希表和冲突解决技术。
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba516e | 官方: 否 | 付费: 否
答案:
Hashing is a technique that maps a key to a fixed-size array index using a hash function. The goal is to achieve O(1) average time complexity for search, insert, and delete.
哈希是一种通过哈希函数将键映射到固定大小数组索引的技术。目标是实现搜索、插入和删除的平均时间复杂度为O(1)。
A hash table consists of: - An array (buckets)
哈希表由以下部分组成:- 一个数组(桶)
- A hash function
A collision resolution strategy
Collisions occur when two keys produce the same hash index.当两个键产生相同的哈希索引时,就会发生冲突。
There are two major collision resolution techniques:
有两种主要的冲突解决技术:
- Chaining: Each bucket contains a linked list (or dynamic structure). Multiple keys can exist in the same bucket.
- Open Addressing: All keys are stored within the array itself. If a collision occurs, probing techniques are used:
- Linear Probing
- Quadratic Probing
- Double Hashing
Important concepts:
重要概念:
- Load Factor (α) = Number of elements / Table sizeHigher load factor increases collisions.
- Rehashing: Resizing the table when load factor exceeds a threshold.
| Technique 技术 | Storage 存储 | Advantage 优势 | Limitation 局限性 |
|---|---|---|---|
| Chaining 链式法 | Linked lists 链表 | Simple 简单 | Extra memory 额外内存 |
| Open Addressing 开放寻址 | Array only 仅数组 | Cache friendly 缓存友好 | Clustering 聚集 |
Hash tables are used in: - Dictionaries
哈希表用于:- 字典
- Caches
- Symbol tables
Database indexing
Here are some follow-up questions that can be asked: - What makes a good hash function?以下是可能提出的后续问题:- 什么构成一个好的哈希函数?
- What is clustering?
- Why does performance degrade at high load factors?
527. What is a Binary Search Tree (BST)? What is the difference between BST, AVL tree, and B-tree?
什么是二叉搜索树(BST)?BST、AVL树和B树之间有什么区别?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4d58d557c902ba5171 | 官方: 否 | 付费: 否
答案:
A Binary Search Tree (BST) is a binary tree where, for every node: - Left subtree contains values smaller than the node.
二叉搜索树(BST)是一种二叉树,其中对于每个节点:- 左子树包含小于该节点的值。
Right subtree contains values greater than the node.
Average time complexity for search, insert, and delete is O(log n), but in the worst case (when skewed), it becomes O(n).搜索、插入和删除的平均时间复杂度为O(log n),但在最坏情况下(当树倾斜时),会变成O(n)。
An AVL tree is a self-balancing BST. For every node, the height difference between left and right subtrees (balance factor) is at most 1. If imbalance occurs, rotations (LL, RR, LR, RL) are performed. AVL guarantees O(log n) time complexity even in the worst case.
AVL树是一种自平衡的BST。对于每个节点,左右子树之间的高度差(平衡因子)最多为1。如果发生不平衡,则执行旋转(LL、RR、LR、RL)。AVL保证即使在最坏情况下,时间复杂度也为O(log n)。
A B-tree is a balanced multi-way tree optimized for disk storage. Unlike BSTs, a B-tree node can contain multiple keys and children. It minimizes disk I/O operations and is widely used in databases and file systems.
B树是一种针对磁盘存储优化的平衡多路树。与BST不同,B树节点可以包含多个键和子节点。它最小化磁盘I/O操作,并广泛应用于数据库和文件系统中。
| Feature 特性 | BST | AVL | B-tree B树 |
|---|---|---|---|
| Balancing 平衡 | No 否 | Yes 是 | Yes 是 |
| Worst Case 最坏情况 | O(n) | O(log n) | O(log n) |
| Node Children 节点子节点数 | 2 | 2 | Many 多个 |
| Use Case 使用场景 | In-memory 内存 | In-memory balanced 内存平衡 | Databases, file systems 数据库、文件系统 |
Databases prefer B+ trees (a variation of B-tree) because they are optimized for range queries and disk access.
数据库偏好使用 B+ 树(B 树的一种变体),因为它们针对范围查询和磁盘访问进行了优化。
In interviews, you can be asked questions like: - When does a BST degrade?
面试中可能会被问到这样的问题:- 二叉搜索树何时会退化?
- Why are rotations needed in AVL?
- Why don’t databases use simple BSTs?
528. What is a linked list? Compare singly linked list, doubly linked list, and circular linked list.
什么是链表?比较单向链表、双向链表和循环链表。
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba5174 | 官方: 否 | 付费: 否
答案:
A linked list is a linear data structure where elements (nodes) are stored non-contiguously in memory. Each node contains data and one or more pointers that reference the next (and possibly previous) node.
链表是一种线性数据结构,其中元素(节点)在内存中非连续存储。每个节点包含数据和一个或多个指针,这些指针引用下一个(可能还有前一个)节点。
In a singly linked list , each node contains a pointer to the next node. Traversal is one-directional. Insertion at the head is O(1), but searching is O(n).
在单向链表中,每个节点包含一个指向下一个节点的指针。遍历是单向的。在头部插入的时间复杂度为 O(1),但搜索为 O(n)。
In a doubly linked list , each node contains pointers to both the next and previous nodes. This allows bidirectional traversal and makes deletion easier if a node pointer is given.
在双向链表中,每个节点包含指向下一个节点和前一个节点的指针。这允许双向遍历,并且在给定节点指针时使删除操作更容易。
In a circular linked list , the last node points back to the first node. This structure is useful in round-robin scheduling and cyclic processes.
在循环链表中,最后一个节点指回第一个节点。这种结构在轮询调度和循环过程中非常有用。
| Type 类型 | Traversal 遍历 | Extra Memory 额外内存 | Common Use 常见用途 |
|---|---|---|---|
| Singly 单向 | One direction 单向 | Low 低 | Simple dynamic lists 简单的动态列表 |
| Doubly 双向 | Two directions 双向 | Higher 更高 | Browser history 浏览器历史记录 |
| Circular 循环 | Cyclic 循环 | Depends 取决于 | Scheduling systems 调度系统 |
Compared to arrays: - Linked lists allow dynamic memory allocation.
与数组相比:- 链表允许动态内存分配。
- No random access (O(n) for indexing).
- Poor cache locality compared to arrays.
Better for frequent insertions/deletions.
A common follow-up question during interviews could be why linked lists are slower than arrays despite both having O(n) traversal, the answer here will be adjacent to cache locality and contiguous memory.面试中一个常见的后续问题可能是为什么链表比数组慢,尽管两者遍历时时间复杂度都是 O(n),这里的答案将涉及缓存局部性和连续内存。
529. What is the difference between stack and queue? Explain their real-world applications.
栈和队列有什么区别?解释它们的现实应用。
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba5177 | 官方: 否 | 付费: 否
答案:
A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. The last element inserted is the first one removed.
栈是一种遵循 LIFO(后进先出)原则的线性数据结构。最后插入的元素最先被移除。
A queue is a linear data structure that follows the FIFO (First In, First Out) principle. The first element inserted is the first one removed.
队列是一种遵循 FIFO(先进先出)原则的线性数据结构。最先插入的元素最先被移除。
Operations:
操作:
| Structure 结构 | Insert Operation 插入操作 | Remove Operation 移除操作 |
|---|---|---|
| Stack 栈 | Push Push(压入) | Pop Pop(弹出) |
| Queue 队列 | Enqueue Enqueue(入队) | Dequeue Dequeue(出队) |
A stack is heavily used in: - Function call management (call stack)
栈广泛用于:- 函数调用管理(调用栈)
- Undo/redo functionality
- Expression evaluation (infix to postfix)
Backtracking algorithms (DFS)
A queue is commonly used in: - Breadth-First Search (BFS)队列常用于:- 广度优先搜索(BFS)
- CPU scheduling
- Print spooling
Message queues in distributed systems
Variants include: - Circular Queue: Prevents wasted space in array implementation.变体包括:- 循环队列:防止数组实现中的空间浪费。
- Priority Queue: Elements are removed based on priority, not order.
Deque (Double Ended Queue): Insertion and deletion from both ends.
Time complexity for both insertion and deletion is typically O(1).插入和删除的时间复杂度通常都是 O(1)。
In interviews, these topics are also covered along the lines: - Implementation using arrays vs linked lists
在面试中,这些主题也会围绕以下内容进行讨论:- 使用数组与链表的实现对比
- When recursion implicitly uses a stack
- Difference between stack overflow and heap overflow
530. Explain different types of joins in SQL with examples.
用示例解释SQL中不同类型的连接(JOIN)。
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba517a | 官方: 否 | 付费: 否
答案:
A JOIN in SQL is used to combine rows from two or more tables based on a related column. It is fundamental in relational databases because normalized data is often split across multiple tables.
SQL中的连接(JOIN)用于基于相关列将两个或多个表中的行合并。这在关系数据库中至关重要,因为规范化数据通常分布在多个表中。
The most commonly used join is the INNER JOIN . It returns only the rows that have matching values in both tables.
最常用的连接是内连接(INNER JOIN)。它只返回两个表中具有匹配值的行。
SELECT e.name, d.department_name
SELECT e.name, d.department_name
FROM Employees e
FROM Employees e
INNER JOIN Departments d
INNER JOIN Departments d
ON e.department_id = d.id;
ON e.department_id = d.id;
Only employees with a matching department_id will appear in the result.
只有具有匹配department_id的员工会出现在结果中。
A LEFT JOIN (LEFT OUTER JOIN) returns all rows from the left table and the matching rows from the right table. If no match exists, NULL values are returned for the right table columns.
左连接(LEFT OUTER JOIN)返回左表中的所有行以及右表中匹配的行。如果没有匹配项,则右表列返回NULL值。
A RIGHT JOIN is the opposite, all rows from the right table are returned, with NULLs for unmatched rows on the left.
右连接(RIGHT JOIN)相反,返回右表中的所有行,对于左表中不匹配的行则填充NULL。
A FULL OUTER JOIN returns all rows from both tables. If there is no match on either side, NULL values are filled in.
全外连接(FULL OUTER JOIN)返回两个表中的所有行。如果任一侧没有匹配项,则填充NULL值。
A CROSS JOIN returns the Cartesian product of both tables, every row of the first table combined with every row of the second table. It does not require a condition and is rarely used unless intentional.
交叉连接(CROSS JOIN)返回两个表的笛卡尔积,即第一表中的每一行与第二表中的每一行组合。它不需要条件,除非有意使用,否则很少使用。
A SELF JOIN joins a table with itself. It is commonly used in hierarchical data like employee-manager relationships.
自连接将表与自身连接。它常用于层级数据,例如员工与经理的关系。
SELECT e.name, m.name AS manager
SELECT e.name, m.name AS manager
FROM Employees e
FROM Employees e
LEFT JOIN Employees m
LEFT JOIN Employees m
ON e.manager_id = m.id;
ON e.manager_id = m.id;
Other variations include: - NATURAL JOIN: Automatically joins tables based on columns with the same name (not commonly recommended in production due to lack of explicitness).
其他变体包括:- 自然连接(NATURAL JOIN):基于同名列自动连接表(由于缺乏明确性,在生产中通常不推荐使用)。
USING clause: Simplifies join syntax when both tables share the same column name.
Join Type
连接类型Returns
返回结果INNER JOIN
内连接(INNER JOIN)Matching rows only
仅匹配的行LEFT JOIN
左连接(LEFT JOIN)All left rows + matches
所有左表行 + 匹配项RIGHT JOIN
右连接(RIGHT JOIN)All right rows + matches
所有右表行 + 匹配项FULL OUTER JOIN
全外连接(FULL OUTER JOIN)All rows from both tables
两个表中的所有行CROSS JOIN
交叉连接(CROSS JOIN)Cartesian product
笛卡尔积
From a performance perspective: - Joins rely heavily on indexing.
从性能角度来看:- 连接严重依赖索引。
- Large joins without indexes can cause full table scans.
INNER JOIN is usually faster than OUTER JOIN because fewer rows are processed.
In interviews, candidates are often tested on: - Difference between LEFT JOIN and INNER JOIN在面试中,候选人常被测试:- 左连接与内连接之间的区别
- How NULLs behave in joins
- Join order and indexing impact
531. What is the difference between SQL and NoSQL databases? When to use which?
SQL 和 NoSQL 数据库有什么区别?何时使用哪种?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba517d | 官方: 否 | 付费: 否
答案:
SQL databases are relational databases that store data in structured tables with predefined schemas. They follow ACID properties and are designed for strong consistency and complex queries involving joins.
SQL 数据库是关系型数据库,将数据存储在具有预定义模式的规范化表中。它们遵循 ACID 属性,专为强一致性和涉及连接的复杂查询而设计。
Common examples include MySQL and PostgreSQL.
常见示例包括 MySQL 和 PostgreSQL。
NoSQL databases are non-relational and designed for scalability, flexibility, and distributed architectures. They often follow the BASE model (Basically Available, Soft state, Eventually consistent).
NoSQL 数据库是非关系型的,专为可扩展性、灵活性和分布式架构而设计。它们通常遵循 BASE 模型(基本可用、软状态、最终一致性)。
Examples include MongoDB (document-based), Redis (key-value), Apache Cassandra (column-family), and Neo4j (graph-based).
示例包括 MongoDB(基于文档)、Redis(键值)、Apache Cassandra(列族)和 Neo4j(基于图)。
| Aspect 方面 | SQL | NoSQL |
|---|---|---|
| Schema 模式 | Fixed 固定 | Flexible 灵活 |
| Scaling 扩展 | Vertical 垂直 | Horizontal 水平 |
| Consistency 一致性 | Strong 强 | Often eventual 通常最终 |
| Best For 最适合 | Transactions, complex queries 事务、复杂查询 | Large-scale distributed data 大规模分布式数据 |
SQL is preferred in financial systems and applications requiring strict consistency. NoSQL is preferred for high-throughput systems, real-time applications, and unstructured data.
SQL 在金融系统和需要严格一致性的应用中更受青睐。NoSQL 更适合高吞吐量系统、实时应用和非结构化数据。
532. What are the ACID properties in a database? Why are they important?
什么是数据库中的ACID属性?为什么它们很重要?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba5180 | 官方: 否 | 付费: 否
答案:
ACID is a set of properties that guarantee reliable and consistent database transactions. It ensures that even in cases of crashes, power failures, or concurrent access, the database remains correct.
ACID是一组保证数据库事务可靠且一致的属性。它确保即使在崩溃、电源故障或并发访问的情况下,数据库仍保持正确。
Atomicity means a transaction either completes fully or does not happen at all. If any part fails, the entire transaction is rolled back.
原子性意味着事务要么完全完成,要么根本不发生。如果任何部分失败,整个事务将被回滚。
Consistency ensures that a transaction moves the database from one valid state to another, maintaining all defined constraints and rules.
一致性确保事务将数据库从一个有效状态移动到另一个有效状态,维护所有已定义的约束和规则。
Isolation ensures that concurrent transactions do not interfere with each other. Depending on the isolation level (Read Uncommitted, Read Committed, Repeatable Read, Serializable), different types of anomalies like dirty reads or phantom reads are prevented.
隔离性确保并发事务不相互干扰。根据隔离级别(读未提交、读已提交、可重复读、可序列化),可防止脏读或幻读等不同类型的异常。
Durability guarantees that once a transaction is committed, it will persist even if the system crashes. This is typically implemented using Write-Ahead Logging (WAL) and recovery logs.
持久性保证一旦事务提交,即使系统崩溃,它也会持久存在。这通常通过预写日志(WAL)和恢复日志来实现。
| Property 属性 | Meaning 含义 | Purpose 目的 |
|---|---|---|
| Atomicity 原子性 | All-or-nothing execution 全有或全无执行 | Prevents partial updates 防止部分更新 |
| Consistency 一致性 | Valid state transitions 有效状态转换 | Maintains integrity 维护完整性 |
| Isolation 隔离性 | No interference 无干扰 | Prevents anomalies 防止异常 |
| Durability 持久性 | Permanent after commit 提交后永久 | Ensures persistence 确保持久性 |
A common example would be: if money is debited from one account but the system crashes before crediting another, atomicity ensures the transaction is rolled back.
一个常见示例是:如果从某个账户扣款但系统在向另一个账户入账前崩溃,原子性确保事务被回滚。
In interviews, candidates often confuse consistency with isolation, so clarity here is important.
在面试中,候选人常混淆一致性和隔离性,因此这里清晰理解很重要。
533. What is virtual memory? Explain paging and segmentation.
什么是虚拟内存?解释分页和分段。
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba5183 | 官方: 否 | 付费: 否
答案:
Virtual memory is a memory management technique that allows a system to use disk storage as an extension of physical RAM. It gives each process the illusion of having a large, continuous memory space, even if physical memory is limited. This improves multiprogramming and provides process isolation.
虚拟内存是一种内存管理技术,允许系统使用磁盘存储作为物理RAM的扩展。它给每个进程一种拥有大连续内存空间的错觉,即使物理内存有限。这提高了多道程序设计并提供进程隔离。
Paging divides logical memory into fixed-size blocks called pages and physical memory into frames of the same size. A page table maps logical pages to physical frames. When a required page is not present in RAM, a page fault occurs, and the operating system loads the page from disk. Paging eliminates external fragmentation but can cause internal fragmentation due to fixed block sizes.
分页将逻辑内存划分为固定大小的块,称为页,并将物理内存划分为相同大小的帧。页表将逻辑页映射到物理帧。当所需页不在RAM中时,发生缺页故障,操作系统从磁盘加载该页。分页消除了外部碎片,但由于固定块大小,可能导致内部碎片。
To improve performance, systems use a Translation Lookaside Buffer (TLB), which caches page table entries to speed up address translation.
为提高性能,系统使用转换后备缓冲区(TLB),它缓存页表项以加速地址转换。
Segmentation, in contrast, divides memory into variable-sized logical segments such as code, stack, and data. Each segment has a base address and limit. Segmentation aligns with how programmers view memory, but it can lead to external fragmentation.
相比之下,分段将内存划分为可变大小的逻辑段,如代码、栈和数据。每段有基地址和限制。分段与程序员对内存的看法一致,但可能导致外部碎片。
| Aspect 方面 | Paging 分页 | Segmentation 分段 |
|---|---|---|
| Block Size 块大小 | Fixed 固定 | Variable 可变 |
| Fragmentation 碎片 | Internal 内部 | External 外部 |
| View 观点 | Physical memory-oriented 面向物理内存 | Logical memory-oriented 面向逻辑内存 |
Modern systems often combine paging and segmentation to balance efficiency and logical organization.
现代系统常结合分页和分段,以在效率和逻辑组织间取得平衡。
In interviews, the follow-up questions usually include TLB, thrashing, page replacement algorithms (LRU, FIFO), and differences between internal and external fragmentation.
面试中,后续问题通常包括TLB、抖动、页面置换算法(LRU、FIFO)以及内部碎片和外部碎片的区别。
534. Explain the different CPU scheduling algorithms. Compare preemptive vs non-preemptive.
解释不同的CPU调度算法。比较抢占式与非抢占式。
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a4e58d557c902ba5186 | 官方: 否 | 付费: 否
答案:
CPU scheduling determines which process in the ready queue gets access to the CPU. The main goals are maximizing CPU utilization, minimizing waiting time, reducing turnaround time, and improving response time.
CPU调度决定就绪队列中哪个进程获得CPU的访问权。主要目标是最大化CPU利用率、最小化等待时间、减少周转时间以及改善响应时间。
First Come First Serve (FCFS) is a non-preemptive algorithm where processes execute in order of arrival. It is simple but suffers from the convoy effect, where short jobs wait behind long ones.
先来先服务(FCFS)是一种非抢占式算法,进程按到达顺序执行。它简单,但存在护航效应问题,即短作业在长作业后面等待。
Shortest Job First (SJF) selects the process with the smallest CPU burst time. It minimizes average waiting time and is theoretically optimal. However, it may cause starvation for long processes. Its preemptive version is called Shortest Remaining Time First (SRTF).
最短作业优先(SJF)选择具有最小CPU突发时间的进程。它最小化平均等待时间,理论上是最优的。然而,它可能导致长进程的饥饿。其抢占式版本称为最短剩余时间优先(SRTF)。
Round Robin (RR) assigns a fixed time quantum to each process. After the quantum expires, the process is moved to the end of the queue. It is widely used in time-sharing systems. If the quantum is too small, context switching overhead increases; if too large, it behaves like FCFS.
轮转调度(RR)为每个进程分配一个固定的时间片。时间片到期后,进程被移到队列末尾。它广泛应用于分时系统。如果时间片过小,上下文切换开销会增加;如果过大,则行为类似于FCFS。
Priority Scheduling executes processes based on priority levels. It can be preemptive or non-preemptive. Starvation can occur, which is typically solved using aging (gradually increasing the priority of waiting processes).
优先级调度基于优先级级别执行进程。它可以是抢占式或非抢占式。可能会发生饥饿,通常通过老化解决(逐步提高等待进程的优先级)。
Multi-Level Feedback Queue (MLFQ) uses multiple queues with different priority levels. Processes can move between queues based on their behavior, favoring short and interactive tasks. Modern operating systems commonly use variations of this approach.
多级反馈队列(MLFQ)使用多个具有不同优先级级别的队列。进程可以根据其行为在队列之间移动,这有利于短任务和交互式任务。现代操作系统通常使用这种方法的各种变体。
The fundamental difference between preemptive and non-preemptive scheduling is:
抢占式和非抢占式调度之间的根本区别是:
| Aspect 方面 | Preemptive 抢占式 | Non-Preemptive 非抢占式 |
|---|---|---|
| CPU Control CPU控制 | Can interrupt running process 可以中断运行中的进程 | Runs until completion or blocking 运行直到完成或阻塞 |
| Responsiveness 响应性 | High 高 | Lower 较低 |
| Overhead 开销 | Higher 较高 | Lower 较低 |
Preemptive scheduling is better for interactive systems, while non-preemptive scheduling is simpler and suitable for batch systems.
抢占式调度更适合交互式系统,而非抢占式调度更简单,适用于批处理系统。
In interviews, you can be asked why SJF is optimal, what starvation is, and why Round Robin is preferred in interactive environments.
面试中,你可能被问到为什么SJF是最优的、什么是饥饿,以及为什么交互环境中优先选择轮转调度。
535. What is the difference between process and thread? Explain with examples.
进程和线程之间有什么区别?请用示例解释。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: behavioral | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba5189 | 官方: 否 | 付费: 否
答案:
A process is an independent program in execution that has its own memory space, system resources, and execution context. The operating system isolates processes from one another, which means if one process crashes, it does not directly affect others. Each process maintains a Process Control Block (PCB), its own address space, and allocated resources like file handles and network connections.
进程是执行中的独立程序,具有自己的内存空间、系统资源和执行上下文。操作系统将进程彼此隔离,这意味着如果一个进程崩溃,它不会直接影响其他进程。每个进程维护一个进程控制块(PCB)、自己的地址空间以及分配的资源,如文件句柄和网络连接。
A thread, on the other hand, is the smallest unit of execution within a process. Multiple threads can exist inside a single process, and they share the same memory space (heap and global variables). However, each thread has its own stack, program counter, and registers.
而线程是进程内最小的执行单元。一个进程中可以存在多个线程,它们共享相同的内存空间(堆和全局变量)。然而,每个线程有自己的栈、程序计数器和寄存器。
The key difference lies in memory isolation and overhead:
关键区别在于内存隔离和开销:
| Aspect 方面 | Process 进程 | Thread 线程 |
|---|---|---|
| Memory 内存 | Separate address space 独立地址空间 | Shared address space 共享地址空间 |
| Context Switching 上下文切换 | Expensive 昂贵 | Faster 更快 |
| Communication 通信 | IPC mechanisms IPC 机制 | Shared variables 共享变量 |
| Fault Isolation 故障隔离 | Strong 强 | Weak 弱 |
Because processes do not share memory, communication between them requires Inter-Process Communication (IPC) like pipes or sockets. Threads communicate directly via shared memory, which makes them faster but also prone to race conditions if synchronization is not handled properly.
由于进程不共享内存,它们之间的通信需要借助进程间通信(IPC)机制,如管道或套接字。线程直接通过共享内存进行通信,这使它们更快,但若未妥善处理同步,也容易引发竞态条件。
There are also user-level threads (managed by libraries) and kernel-level threads (managed by the OS scheduler). Kernel-level threads allow true parallel execution on multi-core systems.
还有用户级线程(由库管理)和内核级线程(由操作系统调度器管理)。内核级线程允许在多核系统上实现真正的并行执行。
For example, in Google Chrome, each browser tab runs as a separate process for isolation, while multiple threads inside a tab handle rendering, networking, and scripting.
例如,在 Google Chrome 中,每个浏览器标签页作为独立进程运行以实现隔离,而标签页内的多个线程处理渲染、网络和脚本执行。
In interviews, the deeper expectation is that you understand the trade-off between isolation and performance, and how multithreading introduces synchronization challenges.
在面试中,更深层的期望是你理解隔离与性能之间的权衡,以及多线程如何引入同步方面的挑战。
536. What is the difference between BFS and DFS? When to use which?
BFS 和 DFS 有什么区别?何时使用哪一种?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba518c | 官方: 否 | 付费: 否
答案:
Breadth-First Search (BFS) and Depth-First Search (DFS) are graph traversal algorithms used to explore nodes and edges.
广度优先搜索(BFS)和深度优先搜索(DFS)是用于探索节点和边的图遍历算法。
Both run in O(V + E) time when using an adjacency list representation, where: - V = number of vertices
当使用邻接表表示时,两者的时间复杂度均为 O(V + E),其中:- V = 顶点数
E = number of edges
BFS explores the graph level by level. It uses a queue to process nodes in order of discovery.BFS 逐层探索图。它使用队列按发现顺序处理节点。
DFS explores as deep as possible before backtracking. It uses a stack (explicitly or via recursion).
DFS 在回溯前尽可能深入探索。它使用栈(显式或通过递归实现)。
Key differences:
关键区别:
| Feature 特性 | BFS | DFS |
|---|---|---|
| Data Structure 数据结构 | Queue 队列 | Stack / Recursion 栈 / 递归 |
| Traversal Pattern 遍历模式 | Level-order 层序 | Depth-first 深度优先 |
| Shortest Path (Unweighted) 最短路径(无权图) | Yes 是 | No 否 |
| Memory Usage 内存使用 | Can be high 可能较高 | Usually lower 通常较低 |
BFS is preferred when: - Finding shortest path in an unweighted graph
BFS 首选于以下场景:- 在无权图中查找最短路径
- Solving level-order traversal problems
Checking bipartite graphs
DFS is preferred when: - Detecting cyclesDFS 首选于以下场景:- 检测环
- Topological sorting
- Finding connected components
Solving maze/backtracking problems
Graph representation also matters: - Adjacency List: Space efficient for sparse graphs (O(V + E)).图的表示方式也很重要:- 邻接表:对稀疏图空间效率高(O(V + E))。
- Adjacency Matrix: Faster edge lookup but uses O(V²) space.
537. How does the internet work end-to-end when you type a URL in a browser?
当你在浏览器中输入 URL 时,互联网是如何端到端工作的?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51cc | 官方: 否 | 付费: 否
答案:
When you type a URL into a browser and press Enter, multiple systems coordinate to fetch and display the webpage. The process happens in layers.
当你在浏览器中输入一个URL并按回车时,多个系统协同工作以获取并显示网页。这一过程分层进行。
First, the browser checks: - Browser cache
首先,浏览器检查:- 浏览器缓存
- OS cache
Router cache
If the IP address is not cached, a DNS lookup begins. The browser queries a recursive DNS resolver, which may perform iterative queries to: - Root DNS servers如果IP地址未被缓存,则开始DNS查找。浏览器查询递归DNS解析器,该解析器可能会执行迭代查询以:- 根DNS服务器
- Top-level domain (TLD) servers
Authoritative DNS servers
Once the IP address is resolved, the browser establishes a connection to the server.一旦IP地址被解析,浏览器便与服务器建立连接。
If the site uses HTTP: - A TCP 3-way handshake occurs (SYN -> SYN-ACK -> ACK).
如果站点使用HTTP:- 发生TCP三次握手(SYN -> SYN-ACK -> ACK)。
If the site uses HTTPS: - TCP handshake first
如果站点使用HTTPS:- 先进行TCP握手
Then a TLS handshake to establish encryption
After the secure connection is established: - The browser sends an HTTP request (GET /index.html)安全连接建立后:- 浏览器发送HTTP请求(GET /index.html)
- The request may pass through load balancers and CDNs
The server processes the request (possibly querying databases or services)
The server sends back an HTTP response: - Status codes like 200 (OK), 301 (Redirect), 404 (Not Found), 500 (Server Error)服务器返回HTTP响应:- 状态码如200(成功)、301(重定向)、404(未找到)、500(服务器错误)
The browser then: - Parses HTML -> builds DOM
浏览器随后:- 解析HTML -> 构建DOM- Parses CSS -> builds CSSOM
- Combines into render tree
Performs layout and paint
Modern systems may involve: - CDN caching for static assets现代系统可能涉及:- 静态资源的CDN缓存
- Load balancers distributing traffic
- Reverse proxies
Microservices internally
This question tests whether you understand networking, DNS, TCP, TLS, HTTP, and browser rendering as one connected system.这个问题测试你是否理解网络、DNS、TCP、TLS、HTTP以及浏览器渲染作为一个关联系统的运作。
538. What is the difference between HTTP and HTTPS? How does TLS/SSL work?
HTTP和HTTPS有什么区别?TLS/SSL是如何工作的?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51cf | 官方: 否 | 付费: 否
答案:
HTTP (HyperText Transfer Protocol) is a stateless application-layer protocol used for transferring data between client and server. It runs on port 80 and sends data in plaintext.
HTTP(超文本传输协议)是一种无状态的应用层协议,用于在客户端和服务器之间传输数据。它运行在80端口,并以明文发送数据。
HTTPS is HTTP over TLS (Transport Layer Security). It runs on port 443 and encrypts communication between client and server.
HTTPS是HTTP over TLS(传输层安全性)。它运行在443端口,并对客户端与服务器之间的通信进行加密。
The key difference is encryption and authentication.
关键区别在于加密和认证。
TLS works using asymmetric and symmetric cryptography.
TLS使用非对称和对称密码学来工作。
During the TLS handshake:
在TLS握手期间:
Client sends "Client Hello" (supported cipher suites). 2. Server replies with "Server Hello" and its digital certificate. 3. The certificate is verified by a Certificate Authority (CA). 4. Client and server agree on a session key. 5. Symmetric encryption begins for the session.
- 客户端发送“Client Hello”(支持的密码套件)。 2. 服务器回复“Server Hello”及其数字证书。 3. 证书由证书颁发机构(CA)进行验证。 4. 客户端和服务器协商会话密钥。 5. 会话开始使用对称加密。
Public-key cryptography is used only during key exchange because it is computationally expensive. After that, symmetric encryption is used for performance.
公钥密码学仅在密钥交换期间使用,因为其计算成本高昂。之后,为提升性能而使用对称加密。
| Aspect 方面 | HTTP | HTTPS |
|---|---|---|
| Encryption 加密 | No 无 | Yes (TLS) 有(TLS) |
| Port 端口 | 80 | 443 |
| Security 安全性 | Vulnerable to MITM 易受中间人攻击 | Encrypted & authenticated 加密且经过认证 |
HTTPS is mandatory for: - Login systems
以下场景必须使用HTTPS: - 登录系统
- Payment gateways
- Authentication tokens
Sensitive APIs
Modern improvements: - HTTP/2 -> multiplexing, header compression现代改进: - HTTP/2 -> 多路复用、头部压缩
- HTTP/3 -> uses QUIC (built over UDP) for reduced latency
539. What is the difference between TCP and UDP? When would you choose one over the other?
TCP和UDP有什么区别?在什么情况下你会选择其中一个而不是另一个?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51d2 | 官方: 否 | 付费: 否
答案:
TCP and UDP are transport-layer protocols used for data transmission.
TCP和UDP是用于数据传输的传输层协议。
TCP (Transmission Control Protocol) is connection-oriented and reliable. Before sending data, it establishes a connection using a 3-way handshake. It guarantees: - Ordered delivery
TCP(传输控制协议)是面向连接且可靠的。在发送数据之前,它通过三次握手建立连接。它保证: - 有序送达
- Error checking
- Retransmission of lost packets
- Flow control
Congestion control
UDP (User Datagram Protocol) is connectionless and does not guarantee delivery, order, or duplication protection.UDP(用户数据报协议)是无连接的,不保证送达、顺序或重复保护。
| Feature 特性 | TCP | UDP |
|---|---|---|
| Connection 连接 | Yes 有 | No 无 |
| Reliability 可靠性 | Guaranteed 有保证 | No guarantee 无保证 |
| Ordering 排序 | Maintained 保持 | Not maintained 不保持 |
| Speed 速度 | Slower 较慢 | Faster 较快 |
| Overhead 开销 | High 高 | Low 低 |
TCP is used for: - HTTP/HTTPS
TCP用于: - HTTP/HTTPS
- FTP
Email protocols
UDP is used for: - DNS queriesUDP用于: - DNS查询
- Online gaming
- Video streaming
VoIP
DNS uses UDP because: - Queries are smallDNS使用UDP是因为: - 查询内容小
- Speed matters more than reliability
- Retries can happen at application level
540. Explain the concept of API. What is the difference between REST and SOAP?
解释API的概念。REST和SOAP之间有什么区别?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51d5 | 官方: 否 | 付费: 否
答案:
An API (Application Programming Interface) is a defined way for software components to communicate with each other. It specifies how requests are made and responses are structured.
API(应用程序编程接口)是软件组件之间进行通信的一种定义方式。它规定了请求如何发出以及响应如何结构化。
In web systems, APIs typically use HTTP.
在Web系统中,API通常使用HTTP。
REST (Representational State Transfer) is an architectural style for building APIs. It is: - Stateless
REST(表述性状态转移)是一种用于构建API的架构风格,其特点包括:- 无状态
- Resource-based
- Uses standard HTTP methods (GET, POST, PUT, DELETE)
Typically returns JSON
SOAP (Simple Object Access Protocol) is a protocol that: - Uses XML-based message envelopesSOAP(简单对象访问协议)是一种协议,其特点为:- 使用基于XML的消息封套
- Follows strict standards
- Supports WS-Security
Uses WSDL for contract definition
Aspect
方面REST SOAP Type
类型Architectural style
架构风格Protocol
协议Format
格式JSON (commonly)
JSON(常用)XML State
状态Stateless
无状态Can be stateful
可以有状态Flexibility
灵活性High
高Strict
严格
REST is widely used for: - Web applications
REST广泛应用于:- Web应用程序
- Mobile backends
Public APIs
SOAP is still used in: - Enterprise systemsSOAP仍用于:- 企业系统
- Banking systems
Environments requiring strict contracts and security compliance
Interview follow-ups include: - What makes an API idempotent?面试追问包括:- 什么使API具有幂等性?
- What are HTTP status codes?
- What is rate limiting?
541. What is the difference between compiler and interpreter? Give examples.
编译器和解释器有什么区别?请举例说明。
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51d8 | 官方: 否 | 付费: 否
答案:
A compiler translates the entire source code into machine code before execution. The generated executable runs directly on hardware.
编译器在执行前将整个源代码翻译成机器代码。生成的执行文件直接在硬件上运行。
An interpreter executes code line by line at runtime without generating a separate executable.
解释器在运行时逐行执行代码,不会生成单独的执行文件。
Examples: - Compiled languages: C, C++, Go
示例:- 编译型语言:C、C++、Go
Interpreted languages: Python, Ruby (historically JavaScript)
Feature
特性Compiler
编译器Interpreter
解释器Translation
翻译Entire program first
先处理整个程序Line-by-line
逐行处理Speed
速度Faster execution
执行更快Slower execution
执行更慢Error Detection
错误检测Before execution
执行前During execution
执行中Output
输出Executable file
执行文件No separate file
无单独文件
Modern systems often use hybrid models.
现代系统常采用混合模型。
Java compiles source code into bytecode, which runs on the JVM (Java Virtual Machine). The JVM uses JIT (Just-In-Time) compilation to convert bytecode into machine code at runtime.
Java将源代码编译为字节码,该字节码在JVM(Java虚拟机)上运行。JVM使用JIT(即时编译)在运行时将字节码转换为机器代码。
Similarly, .NET uses CLR with JIT compilation.
类似地,.NET使用带有JIT编译的CLR。
Transpilers convert one high-level language to another, such as TypeScript to JavaScript.
转译器将一种高级语言转换为另一种,例如将TypeScript转换为JavaScript。
Trade-offs: - Compilers -> better runtime performance
权衡:- 编译器 -> 更好的运行时性能
- Interpreters -> better portability and debugging flexibility
542. What is recursion? Explain with examples and discuss its limitations.
什么是递归?举例说明并讨论其局限性。
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51db | 官方: 否 | 付费: 否
答案:
Recursion is a programming technique where a function calls itself to solve a smaller version of the same problem. Every recursive solution must have:
递归是一种编程技术,函数调用自身来解决同一问题的更小版本。每个递归解决方案都必须具备:
A base case - the stopping condition 2. A recursive case - where the function calls itself with a smaller input
- 基本情况 - 停止条件 2. 递归情况 - 函数以更小输入调用自身的地方
For example, factorial:fact(n) = n * fact(n-1) fact(0) = 1
例如,阶乘:fact(n) = n * fact(n-1) fact(0) = 1
Each recursive call is placed on the call stack . The stack stores: - Function parameters
每次递归调用都被放入调用栈中。栈存储:- 函数参数
- Local variables
Return address
When the base case is reached, the stack starts unwinding.当达到基本情况时,栈开始展开。
Common recursive use cases: - Tree traversal (DFS)
常见的递归使用场景:- 树遍历(DFS)
- Merge sort and quicksort
- Fibonacci sequence
Backtracking problems
However, recursion has limitations.然而,递归也有局限性。
First, deep recursion can cause stack overflow because each function call consumes stack memory. Languages have recursion depth limits (for example, Python’s default recursion limit).
首先,深度递归可能导致栈溢出,因为每次函数调用都会消耗栈内存。语言有递归深度限制(例如,Python 的默认递归限制)。
Second, recursion can be inefficient if the problem contains overlapping subproblems. A classic example is naive Fibonacci, which runs in O(2ⁿ) time. This can be improved using memoization , which stores previously computed results.
其次,如果问题包含重叠子问题,递归可能效率低下。一个经典例子是朴素斐波那契,其运行时间为 O(2ⁿ)。这可以通过记忆化来改进,记忆化会存储先前计算的结果。
Third, recursion may be slower than iteration due to function call overhead.
第三,由于函数调用开销,递归可能比迭代慢。
Some languages support tail recursion optimization (TCO) , where the compiler converts certain recursive calls into iterative loops, reducing stack usage. However, not all languages guarantee TCO.
某些语言支持尾递归优化(TCO),编译器会将特定递归调用转换为迭代循环,从而减少栈使用。然而,并非所有语言都保证 TCO。
In interviews, recursion is often preferred for clarity (especially in tree and graph problems), but iteration may be better when: - Stack depth is large
在面试中,递归通常更受青睐,因为它清晰(尤其是在树和图问题中),但在以下情况下迭代可能更优:- 栈深度较大
- Performance is critical
The logic is straightforward
The key is knowing when recursion simplifies thinking, and when it becomes a liability.关键在于知道何时递归能简化思考,何时它会成为负担。
543. What are design patterns? Explain Singleton, Factory, and Observer with use cases.
什么是设计模式?用使用场景解释单例、工厂和观察者模式。
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51de | 官方: 否 | 付费: 否
答案:
Design patterns are reusable solutions to common software design problems. They are not code snippets, but proven architectural templates.
设计模式是针对常见软件设计问题的可复用解决方案。它们不是代码片段,而是经过验证的架构模板。
They are generally categorized into: - Creational patterns
它们通常分为:- 创建型模式
- Structural patterns
- Behavioral patterns
Singleton (Creational Pattern): Ensures that a class has only one instance and provides a global access point to it.
For example: - Logger例如:- 日志记录器
- Database connection pool
Configuration manager
However, Singleton can introduce hidden global state and tight coupling. It makes unit testing difficult because dependencies become implicit. In modern systems, dependency injection is often preferred over Singleton.然而,单例模式可能引入隐藏的全局状态和紧密耦合。它使单元测试变得困难,因为依赖关系变得隐式。在现代系统中,依赖注入通常优于单例模式。
- Factory (Creational Pattern): Encapsulates object creation logic and delegates it to subclasses or dedicated factory classes.
Instead of directly calling a constructor, the client requests an object from a factory.
客户端不是直接调用构造函数,而是从工厂请求一个对象。
For example: - Payment gateway selection (CreditCard, UPI, PayPal)
例如:- 支付网关选择(信用卡、UPI、PayPal)
- UI component rendering
Database driver selection
Factory improves flexibility and reduces tight coupling to concrete implementations.工厂提高了灵活性,并减少了对具体实现的紧密耦合。
- Observer (Behavioral Pattern): Defines a one-to-many dependency between objects. When one object changes state, all observers are notified automatically.
For example:
例如:
- Event listeners in UI frameworks
- Publish-subscribe systems
- Real-time notification systems
| Pattern 模式 | Category 类别 | Use Case 使用场景 |
|---|---|---|
| Singleton 单例 | Creational 创建型 | One shared instance 一个共享实例 |
| Factory 工厂 | Creational 创建型 | Object creation control 对象创建控制 |
| Observer 观察者 | Behavioral 行为型 | Event-driven updates 事件驱动更新 |
In interviews, candidates are often asked: - When not to use Singleton
在面试中,候选人常被问到:- 何时不使用单例模式
- Difference between Factory and Abstract Factory
- How Observer differs from Pub-Sub
544. What is version control? Explain Git branching strategies.
什么是版本控制?解释 Git 分支策略。
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51e1 | 官方: 否 | 付费: 否
答案:
Version control is a system that tracks changes to source code over time. It enables collaboration, history tracking, rollback, and parallel development.
版本控制是一种随时间跟踪源代码变更的系统。它支持协作、历史追踪、回滚和并行开发。
Git is a distributed version control system , meaning every developer has a full copy of the repository, including history.
Git 是一种分布式版本控制系统,意味着每个开发者都有仓库的完整副本,包括历史记录。
Branching is a core Git feature. It allows teams to work on features independently without affecting the main codebase.
分支是 Git 的核心特性。它允许团队独立开发功能,而不影响主代码库。
Common branching strategies:
常见分支策略:
Git Flow - main (production)
Git Flow - 主线(生产环境)
- develop (integration branch)
- feature branches
- release branches
hotfix branches
Best for structured releases and larger teams, but can be heavy.最适合结构化发布和大型团队,但可能显得繁琐。
GitHub Flow - main branch
GitHub Flow - 主分支
- Short-lived feature branches
Pull Request (PR)-based workflow
Simple and effective for continuous deployment environments.简单且有效,适用于持续部署环境。
Trunk-Based Development - Single main branch (trunk)
主干开发 - 单一主分支(主干)
- Very short-lived branches
Frequent merges
Encourages small, incremental changes and reduces merge conflicts.鼓励小而渐进的变更,减少合并冲突。
Merge vs Rebase: - Merge creates a new merge commit.
合并与变基:- 合并会创建新的合并提交。
Rebase rewrites commit history for a cleaner timeline.
Conflict resolution is a natural part of branching and requires understanding how changes overlap.冲突解决是分支操作的自然部分,需要理解变更如何重叠。
Branching strategy impacts: - Team velocity
分支策略影响:- 团队速度
- Release frequency
- Deployment complexity
545. What is the difference between monolithic and microservices architecture?
单体架构和微服务架构之间有什么区别?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: system-design
- 分类: fullstack
- id: 69b37a4e58d557c902ba51e4 | 官方: 否 | 付费: 否
答案:
A monolithic architecture is a single, unified application where all components (UI, business logic, database access) are part of one deployable unit.
单体架构是一个统一的应用,所有组件(用户界面、业务逻辑、数据库访问)都属于一个可部署单元。
A microservices architecture breaks an application into independent services that communicate over APIs.
微服务架构将应用拆分为通过API通信的独立服务。
Monolith characteristics: - Single codebase
单体架构特点:- 单一代码库
- Single deployment unit
- Easier initial development
Simpler testing and debugging
Microservices characteristics: - Independently deployable services微服务特点:- 可独立部署的服务
- Technology flexibility
- Horizontal scalability
Decentralized data management
Feature
特性Monolith
单体架构Microservices
微服务架构Deployment
部署Single unit
单一单元Multiple services
多个服务Scaling
扩展Entire app
整个应用Individual services
单独服务Complexity
复杂度Lower initially
初始较低Higher operational complexity
操作复杂度较高Team Structure
团队结构Small teams
小团队Multiple autonomous teams
多个自治团队
Microservices introduce challenges like: - Network latency
微服务带来的挑战包括:- 网络延迟
- Distributed transactions
- Data consistency
Observability and monitoring
Inter-service communication may use: - REST服务间通信可以使用:- REST
- gRPC
Message queues (Kafka, RabbitMQ)
Monolith is often the better choice for: - Startups单体架构通常是以下场景的更好选择:- 初创公司
- Small teams
Early-stage products
Microservices can be opted when: - System complexity grows微服务可以在以下情况选择:- 系统复杂性增长
- Independent scaling is needed
- Teams are large and autonomous
546. What is CI/CD? Explain the pipeline stages.
什么是CI/CD?解释流水线各阶段。
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51e7 | 官方: 否 | 付费: 否
答案:
CI/CD stands for Continuous Integration and Continuous Delivery (or Continuous Deployment).
CI/CD代表持续集成和持续交付(或持续部署)。
Continuous Integration (CI) means that every code change is automatically built and tested. Developers integrate code frequently into a shared repository.
持续集成(CI)意味着每次代码变更都会自动构建和测试。开发人员频繁地将代码集成到共享仓库中。
Continuous Delivery ensures that code is always in a deployable state and can be released to production at any time.
持续交付确保代码始终处于可部署状态,并可在任何时间发布到生产环境。
Continuous Deployment goes one step further, every successful build is automatically deployed to production.
持续部署更进一步,每个成功的构建都会自动部署到生产环境。
A typical CI/CD pipeline:
典型的CI/CD流水线:
Code commit 2. Build stage 3. Unit tests 4. Integration tests 5. Artifact creation 6. Deployment to staging 7. Acceptance testing 8. Production deployment
- 代码提交 2. 构建阶段 3. 单元测试 4. 集成测试 5. 工件创建 6. 部署到预发布环境 7. 验收测试 8. 生产部署
Common tools: - Jenkins
常见工具:- Jenkins
- GitHub Actions
GitLab CI
Key concepts: - Artifact management关键概念:- 工件管理
- Automated testing
- Rollback strategies
- Blue-green deployment
Canary releases
CI/CD improves: - Deployment frequencyCI/CD改进:- 部署频率
- Code quality
- Faster feedback cycles
- Reduced manual errors
547. What is the CAP theorem? Explain with real-world database examples.
什么是CAP定理?用真实世界的数据库示例解释。
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51ea | 官方: 否 | 付费: 否
答案:
The CAP theorem states that in a distributed system, you can guarantee only two out of the following three properties simultaneously: - Consistency (C) - Every read receives the most recent write (all nodes see the same data at the same time).
CAP定理指出,在分布式系统中,你只能同时保证以下三个属性中的两个:- 一致性(C)- 每次读取都收到最新的写入(所有节点在同一时间看到相同的数据)。
- Availability (A) - Every request receives a response, even if it’s not the most recent data.
Partition Tolerance (P) - The system continues operating despite network partitions (communication failures between nodes).
In a distributed system, multiple nodes communicate over a network to replicate and synchronize data.If a network failure occurs (a partition), some nodes cannot exchange updates. At that point, the system must choose: either reject requests to keep data consistent (Consistency) or continue serving requests with possibly stale data (Availability).在分布式系统中,多个节点通过网络通信来复制和同步数据。如果发生网络故障(分区),某些节点无法交换更新。此时,系统必须做出选择:要么拒绝请求以保持数据一致性(Consistency),要么继续处理可能包含过时数据的请求(Availability)。
There are three possible combinations:
存在三种可能的组合:
- CP (Consistency + Partition Tolerance): The system prioritizes consistency over availability. If a partition occurs, some requests may be rejected to maintain correctness.
Example: MongoDB (in certain configurations). During a network partition, it may refuse writes to maintain consistency.
示例:MongoDB(在某些配置下)。在网络分区期间,它可能拒绝写入以维持一致性。
- AP (Availability + Partition Tolerance): The system prioritizes availability. It continues serving requests even if some nodes are out of sync.
Example: Apache Cassandra. It allows writes during partitions and resolves inconsistencies later.
示例:Apache Cassandra。它允许在分区期间进行写入,并在稍后解决不一致问题。
This leads to eventual consistency, where data may be temporarily inconsistent but converges over time.
这导致了最终一致性,即数据可能暂时不一致,但会随着时间的推移而收敛。
- CA (Consistency + Availability): Possible only when there is no partition. Traditional single-node relational databases behave like CA systems because there is no distributed network to fail.
| System Type 系统类型 | Guarantees 保证 |
|---|---|
| Single-node RDBMS 单节点关系型数据库 | CA |
| MongoDB (config-dependent) MongoDB(配置相关) | CP |
| Cassandra | AP |
An important extension is the PACELC theorem : - If there is a Partition (P), choose between Availability (A) and Consistency (C).
一个重要的扩展是PACELC定理:- 如果有分区(P),则在可用性(A)和一致性(C)之间进行选择。
Else (E), choose between Latency (L) and Consistency (C).
This explains why some systems choose lower latency even when there is no failure.这解释了为什么有些系统即使在没有故障的情况下也选择较低的延迟。
548. How would you design a URL shortener? Walk through the system design.
你会如何设计一个URL缩短器?请逐步讲解系统设计。
- 知识点: 算法与数据结构 / 行为与软技能 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: behavioral | 难度: medium | 子类型: system-design
- 分类: fullstack
- id: 69b37a4e58d557c902ba51ed | 官方: 否 | 付费: 否
答案:
Here is a step-by-step explanation on how you can design a URL shortener:Client → API Layer → Application Server → Database ↓ Cache
以下是设计URL缩短器的分步说明:客户端 → API层 → 应用服务器 → 数据库 ↓ 缓存
The system consists of: - API servers (handle requests)
系统由以下部分组成:- API服务器(处理请求)
- Database (store mappings)
Cache (speed up reads)
Step 3: Generating Short URLs步骤3:生成短URL
We need a unique key.
我们需要一个唯一键。
Common approaches:
常见方法:
Base62 Encoding - Convert an auto-increment ID into base62 (a-z, A-Z, 0-9).
Base62 编码 - 将自增 ID 转换为 base62(a-z, A-Z, 0-9)。
- Produces short, readable URLs.
Deterministic and collision-free if ID is unique.
Hashing (MD5/SHA) + Truncation - Hash original URL哈希(MD5/SHA)+ 截断 - 对原始 URL 进行哈希处理
- Take first few characters
Must handle collisions carefully
Base62 with unique ID is simpler and more predictable.带唯一 ID 的 Base62 编码更简单且更可预测。
Step 4: Database Choice
第 4 步:数据库选择
SQL: - Strong consistency
SQL: - 强一致性
Simple schema (id, original_url, created_at)
NoSQL: - Better horizontal scalingNoSQL: - 更好的水平扩展
Easier sharding
For very high scale, NoSQL systems like Apache Cassandra may be preferred.对于非常高的规模,可能更倾向于使用 Apache Cassandra 等 NoSQL 系统。
Step 5: Read Optimization
第 5 步:读取优化
URL shorteners are read-heavy systems.
URL 缩短器是读密集型系统。
Use caching layer: - Redis or Memcached
使用缓存层: - Redis 或 Memcached
- Store frequently accessed mappings
Reduce database load
Step 6: Redirection Type第 6 步:重定向类型
Use HTTP status codes: - 301 (Permanent Redirect) -> cached by browsers
使用 HTTP 状态码: - 301(永久重定向)-> 会被浏览器缓存
302 (Temporary Redirect) -> not permanently cached
If analytics tracking is important, 302 may be preferable.如果数据分析追踪很重要,302 可能更可取。
Step 7: Scaling Strategy
第 7 步:扩展策略
To scale: - Horizontal scaling of API servers behind load balancer
实现扩展: - 在负载均衡器后水平扩展 API 服务器
- Database sharding (by key range or hash)
- Read replicas
- Rate limiting to prevent abuse
TTL support for expiring links
Step 8: Handling Collisions步骤8:处理冲突
If using hashing: - Check for existing key
如果使用哈希:- 检查现有键
Regenerate if collision occurs
If using incremental ID: - Collision risk is minimal if ID is unique如果使用增量ID:- 如果ID唯一,冲突风险极小
Step 9: Additional Considerations - Custom aliases
步骤9:其他考虑事项 - 自定义别名- Analytics storage
- Spam detection
- CDN for global latency reduction
Monitoring and observability
Step 1: Requirements步骤1:需求
Functional requirements: - Shorten a long URL
功能需求:- 缩短长URL
- Redirect short URL to original
Track analytics (click count, timestamp)
Non-functional requirements: - High availability非功能需求:- 高可用性
- Low latency (redirection must be fast)
- Scalable to millions of URLs
Handle high read traffic
Step 2: High-Level Architecture步骤2:高层架构
Typical flow:
典型流程:
549. How can you add value to the company?
你如何为公司增加价值?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51f0 | 官方: 否 | 付费: 否
答案:
I recently completed a team project at my previous job, and I devised strategies for improving teamwork and communication among team members. Back in my previous job, I designed strategies for improving teamwork and communication among team members. I can provide your organisation with both my previous experiences and my desire for innovation.
我最近在上一份工作中完成了一个团队项目,并设计了改善团队成员间团队合作和沟通的策略。回到我上一份工作时,我设计了改善团队成员间团队合作和沟通的策略。我可以为您所在的组织提供我之前的经验和我的创新意愿。
550. Describe a project you have worked on?
描述一个你参与过的项目?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51f3 | 官方: 否 | 付费: 否
答案:
I have worked on several projects over the years, but I have to say that my favourite one was the one I did for the IIT Bombay. It was a project that involved a lot of data analysis and data visualization. I was responsible for creating a dashboard that showed the students’ performance in their classes. The dashboard was designed to help the students understand how they were doing and what they needed to do to improve their grades. It was an interesting project because it involved a lot of data analysis and visualization. The project was a huge success, and it helped me learn a lot about data analysis and visualization.
多年来我参与过多个项目,但我最喜欢的还是为印度理工学院孟买分校做的那一个。这是一个涉及大量数据分析和数据可视化的项目。我负责创建一个仪表板,展示学生在课堂上的表现。该仪表板旨在帮助学生了解自己的学习状况以及如何提高成绩。这是一个有趣的项目,因为它涉及大量的数据分析和可视化。这个项目取得了巨大成功,帮助我学到了很多关于数据分析和可视化的知识。
551. Why did you choose computer science?
你为什么选择计算机科学?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51f6 | 官方: 否 | 付费: 否
答案:
Computer science is a very broad field that encompasses a wide range of topics, including computer programming, data analysis, and computer hardware and software design. There are many reasons that someone might choose to study computer science, including the desire to learn a new skill or the hope of finding a job in a field that requires technical knowledge. However, there are also some general benefits to choosing this field. For one, computer science is an excellent way to develop problem-solving skills. This can be useful when you’re faced with a tough problem or when you’re looking for a new job. Additionally, computer science can help you to develop your critical thinking and problem-solving skills. This can be useful if you’re faced with a difficult situation or if you’re looking for a new job. Computer science also has the potential to give you access to a wide range of opportunities, including internships and scholarships. However, it’s important to remember that there are many different types of computer science, so it’s important to choose the right one for you.
计算机科学是一个非常广泛的领域,涵盖广泛的主题,包括计算机编程、数据分析以及计算机硬件和软件设计。人们选择学习计算机科学的原因有很多,包括学习新技能的愿望或希望在需要技术知识的领域找到工作的期望。然而,选择这个领域也有一些普遍的好处。首先,计算机科学是培养解决问题能力的绝佳途径。当你面临难题或寻找新工作时,这可能非常有用。此外,计算机科学可以帮助你发展批判性思维和解决问题的能力。当你遇到困难情况或寻找新工作时,这可能会派上用场。计算机科学还可能为你带来广泛的机会,包括实习和奖学金。然而,重要的是要记住计算机科学有多种类型,因此选择适合自己的那一种很重要。
552. What is your biggest achievement?
你最大的成就是什么?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51f9 | 官方: 否 | 付费: 否
答案:
My greatest professional accomplishment was completing my Bachelor's degree in four years with a 3.9 GPA. My family's financial situation did not impact my Economics degree. As a result, I prioritized my time and built good habits to achieve it. I believe this experience will give me an advantage in my profession.
我最大的职业成就是在四年内完成学士学位,GPA达到3.9。我家庭的经济状况没有影响我的经济学学位。为此,我合理安排时间并养成了良好的习惯来实现这一目标。我相信这段经历将在我的职业生涯中给我带来优势。
553. Why are you interested in this job (related to CS)?
你为什么对这个职位(与计算机科学相关)感兴趣?
- 知识点: 算法与数据结构 (主题: cs-fundamentals;标签: interviewbit, computer-science, topic-specific, cs-fundamentals)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a4e58d557c902ba51fc | 官方: 否 | 付费: 否
答案:
My primary objective is to land a job with a long-term career opportunity where I can also learn Python using. Python is one of the duties listed in the job description, so I am certain that it will play a significant role. It also promises to be a highly skilled and cooperative department, which would help my career advancement. The company's reputation for supporting the development of its workforce may also play a role. It seems like a good match after all.
我的主要目标是找到一份有长期职业发展机会的工作,同时我也能在工作中学习使用Python。Python是职位描述中列出的职责之一,所以我相信它将在工作中扮演重要角色。此外,这个部门看起来技能高超且协作良好,这将有助于我的职业发展。公司以支持员工发展而闻名,这也可能是一个因素。总的来说,这似乎是一个很好的匹配。
554. Write a program to remove duplicates from a sorted array in place?
编写一个程序,原地从排序数组中移除重复元素?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba5ff5 | 官方: 否 | 付费: 否
答案:
- Input: {1, 1, 1, 2, 3, 3, 6, 6, 7}
- Output: {1, 2, 3, 6, 7}
- Explanation: The given input has only 1,2,3,6, and 7 as unique elements, hence the output only lists them out.
include <bits/stdc++.h>
using namespace std;
using namespace std;
class Solution{
class Solution{
public:
public:
//function that takes an array and its size as arguments
//接受一个数组及其大小作为参数的函数
int removeDuplicates(int a[],int n){
int removeDuplicates(int a[],int n){
int index=0;
int index=0;
for(int i=1;i<n;i++) {
for(int i=1;i<n;i++) {
if(a[i]!=a[index]) { //change index
if(a[i]!=a[index]) { //改变索引
index++; //swap next line
index++; //交换下一行
a[index]=a[i];
a[index]=a[i];
}
}
return index+1;
return index+1;
}
};
int main()
int main()
{
int T;
int T;
//taking the number of test cases from user
//从用户处获取测试用例的数量
cin>>T;
cin>>T;
//running the loop for all test cases
//为所有测试用例运行循环
while(T--)
while(T--)
{
int N;
int N;
//taking size input from user
//从用户处获取大小输入
cin>>N;
cin>>N;
int a[N];
int a[N];
//taking array input from user
//从用户处获取数组输入
for(int i=0;i<N;i++)
for(int i=0;i<N;i++)
{
cin>>a[i];
cin>>a[i];
}
Solution ob;
Solution ob;
//calling the removeDuplicates in the Solution class
//在Solution类中调用removeDuplicates函数
int n = ob.removeDuplicates(a,N);
int n = ob.removeDuplicates(a,N);
//printing the array after removing duplicates
//在移除重复元素后打印数组
for(int i=0;i<n;i++)
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<a[i]<<" ";
cout<<endl;
cout<<endl;
}
}
- Time Complexity: O(n)
- Space Complexity: O(1)
555. Write a function for zigzag traversal in a binary tree
编写一个函数用于二叉树的锯齿形遍历
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba5ff8 | 官方: 否 | 付费: 否
答案:
- Input:
- Output: [1, 3, 2, 4, 5, 6, 8, 7]
- Explanation: Zigzag Traversal first iterates the given level of the tree from left to right and then the next level as the right to the level.
// Tree Node
// 树节点
struct Node {
struct Node {
int data;
int data;
Node* left;
Node* left;
Node* right;
Node* right;
};
//Function to store the zigzag order traversal of a tree in a list.
//用于将树的锯齿形遍历顺序存储到列表中的函数。
vectorzigZagTraversal(Node* root)
vectorzigZagTraversal(Node* root)
{
//creating two stacks for level traversals in both order
//创建两个栈,用于按两种顺序进行层序遍历
stack<Node*> st1;
stack<Node*> st1;
stack<Node*> st2;
stack<Node*> st2;
//vector to store the zigzag traversal
//向量,用于存储锯齿形遍历结果
vectorresult;
vectorresult;
//Initialize the first stack with the root element
//用根元素初始化第一个栈
st1.push(root);
st1.push(root);
//Iterate until either of the stack is not empty
//迭代,直到任一栈不为空
while(!st1.empty() || !st2.empty()){
while(!st1.empty() || !st2.empty()){
//iterate until the first stack is not empty
//迭代,直到第一个栈不为空
while(!st1.empty()){
while(!st1.empty()){
Node* temp=st1.top();
Node* temp=st1.top();
st1.pop();
st1.pop();
result.push_back(temp->data);
结果数组追加(临时节点->数据);
if(temp->left)
如果(临时节点->左子节点)
st2.push(temp->left);
st2.push(temp->left);
if(temp->right)
如果(临时节点->右子节点)
st2.push(temp->right);
栈2压入(临时节点->右子节点);
}
//Iterate until the second stack is not empty
//当第二个栈不为空时进行迭代
while(!st2.empty()){
当(栈2不为空){
Node* temp=st2.top();
节点* 临时节点 = 栈2的栈顶元素;
st2.pop();
栈2弹出;
result.push_back(temp->data);
结果数组追加(临时节点->数据);
if(temp->right)
如果(临时节点->右子节点)
st1.push(temp->right);
栈1压入(临时节点->右子节点);
if(temp->left)
如果(临时节点->左子节点)
st1.push(temp->left);
栈1压入(临时节点->左子节点);
}
}
return result;
return result;
}
- Time Complexity: O(n)
- Space Complexity: O(n)
556. Write a function to sort a linked list of 0s, 1s and 2s
编写一个函数,对包含0、1和2的链表进行排序
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba5ffb | 官方: 否 | 付费: 否
答案:
- Input: 0->1->0->2->1->0->2->1
- Output: 0->0->0->1->1->1->2->2
- Explanation: All 0’s will come first then 1s and then 2s. This can be done in O(n) time by counting the occurrences of all three and rearranging them in the linked list.
//structure of the linked list
//链表的结构
struct Node {
struct Node {
int data;
int data;
Node *left;
节点* 左子节点;
Node *right;
节点* 右子节点;
}
//function take the head of the linked list as a parameter
//函数将链表的头节点作为参数
void sortList(Node *head)
void sortList(Node *head)
{
//if linked list is empty then return back
//如果链表为空则返回
if(head==NULL)
if(head==NULL)
return;
return;
else
else
{
Node *temp=head;
Node *temp=head;
Node *temp1=head;
Node *temp1=head;
//to store count of 0s, 1s, and 2s
//用于存储0、1和2的数量
int count0=0,count1=0,count2=0;
int count0=0,count1=0,count2=0;
//calculating the count of 0s, 1s, and 2s
//计算0、1和2的数量
while(temp!=NULL)
while(temp!=NULL)
{
if(temp->data==0)
if(temp->data==0)
count0++;
count0++;
else if(temp->data==1)
else if(temp->data==1)
count1++;
count1++;
else
else
count2++;
count2++;
temp=temp->next;
temp=temp->next;
}
//iterating over count of 0s and filling the linked list
//迭代0的数量并填充链表
while(count0!=0)
while(count0!=0)
{
temp1->data=0;
temp1->data=0;
temp1=temp1->next;
temp1=temp1->next;
count0--;
count0--;
}
//iterating over count of 1s and filling the linked list
//遍历1的数量并填充链表
while(count1!=0)
while(count1!=0)
{
temp1->data=1;
temp1->data=1;
temp1=temp1->next;
temp1=temp1->next;
count1--;
count1--;
}
//iterating over count of 2s and filling the linked list
//遍历2的数量并填充链表
while(count2!=0)
while(count2!=0)
{
temp1->data=2;
temp1->data=2;
temp1=temp1->next;
temp1=temp1->next;
count2--;
count2--;
}
}
}
- Time Complexity: O(n)
- Space Complexity: O(1)
557. Write a function to detect cycle in an undirected graph
编写一个函数来检测无向图中的环
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba5ffe | 官方: 否 | 付费: 否
答案:
- Input: n = 4, e = 4 , 0 1, 1 2, 2 3, 3 1
- Output: Yes
- Explanation: The graph is represented as follows in adjacency list representation:0->11->22->33->1
From the above representation, we can see that there exists a cycle: 1→2→3→1
从上述表示中,我们可以看到存在一个环:1→2→3→1
//function to run dfs for a given node in the graph
//对图中给定节点执行深度优先搜索的函数
int dfs(int v,vectoradj[],vector &visited,vector &rec,int i,int parent){
int dfs(int v,vectoradj[],vector &visited,vector &rec,int i,int parent){
int ans=0;
int ans=0;
visited[i]=1;
visited[i]=1;
rec[i]=1;
rec[i]=1;
for(auto x : adj[i]){
for(auto x : adj[i]){
if(x!=parent) {
if(x!=parent) {
if(rec[x])
if(rec[x])
return 1;
return 1;
ans=dfs(v,adj,visited,rec,x,i);
ans=dfs(v,adj,visited,rec,x,i);
if(ans)
if(ans)
return 1;
return 1;
}
}
rec[i]=0;
rec[i]=0;
return 0;
return 0;
}
// Function to detect cycle in an undirected graph.
// 检测无向图中是否存在环的函数。
// it takes adjacency list representation as an argument
// 它以邻接列表表示作为参数
bool isCycle(int v, vectoradj[]) {
bool isCycle(int v, vectoradj[]) {
vectorvisited(v,0),rec(v,0);
vectorvisited(v,0),rec(v,0);
int ans=0;
int ans=0;
for(int i=0;i<v;i++){
for(int i=0;i<v;i++){
if(visited[i]==0)
if(visited[i]==0)
ans=dfs(v,adj,visited,rec,i,-1);
ans=dfs(v,adj,visited,rec,i,-1);
if(ans)
if(ans)
return 1;
return 1;
}
return 0;
return 0;
}
- Time Complexity: O(V+E)
- Space Complexity: O(V)
558. Write a function to convert an infix expression to postfix expression
编写一个函数,将中缀表达式转换为后缀表达式
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba6001 | 官方: 否 | 付费: 否
答案:
- Input: a+b*(c^d)
- Output: abcd^*+
int prec(char c)
int prec(char c)
{
if (c == '^')
if (c == '^')
return 3;
return 3;
else if (c == '/' || c == '*')
else if (c == '/' || c == '*')
return 2;
return 2;
else if (c == '+' || c == '-')
else if (c == '+' || c == '-')
return 1;
return 1;
else
else
return -1;
return -1;
}
public:
public:
// Function to convert an infix expression to a postfix expression.
// 用于将中缀表达式转换为后缀表达式的函数。
string infixToPostfix(string s) {
string infixToPostfix(string s) {
stackst; // For stack operations, we are using C++ built in stack
stackst; // 对于栈操作,我们使用 C++ 内置的栈
string result;
string result;
for (int i = 0; i < s.length(); i++) {
for (int i = 0; i < s.length(); i++) {
char c = s[i];
char c = s[i];
// If the scanned character is
// 如果扫描到的字符是
// an operand, add it to the output string.
// 操作数,则将其添加到输出字符串中。
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
| | (c >= '0' && c <= '9')) |
result += c;
result += c;
// If the scanned character is an
// 如果扫描到的字符是
// '(', push it to the stack.
// '(',则将其压入栈中。
else if (c == '(')
else if (c == '(')
st.push('(');
st.push('(');
// If the scanned character is an ')',
// 如果扫描到的字符是 ')',
// pop and to output string from the stack
// 则从栈中弹出元素并添加到输出字符串,
// until an '(' is encountered.
// 直到遇到 '(' 为止。
else if (c == ')') {
else if (c == ')') {
while (st.top() != '(') {
while (st.top() != '(') {
result += st.top();
result += st.top();
st.pop();
st.pop();
}
st.pop();
st.pop();
}
// If an operator is scanned
// 如果扫描到一个运算符
else {
否则 {
while (!st.empty()
while (!st.empty()
&& prec(s[i]) <= prec(st.top())) {
&& prec(s[i]) <= prec(st.top())) {
if (c == '^' && st.top() == '^')
if (c == '^' && st.top() == '^')
break;
break;
else {
否则 {
result += st.top();
result += st.top();
st.pop();
st.pop();
}
}
st.push(c);
st.push(c);
}
}
// Pop all the remaining elements from the stack
// 从栈中弹出所有剩余元素
while (!st.empty()) {
while (!st.empty()) {
result += st.top();
result += st.top();
st.pop();
st.pop();
}
return result;
return result;
}
- Time Complexity: O(n)
- Space Complexity: O(n)
559. Write a function to find the maximum for each and every contiguous subarray of size k.
编写一个函数,找出每个大小为k的连续子数组中的最大值。
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba6004 | 官方: 否 | 付费: 否
答案:
- Input: N = 9, K = 3 arr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}
- Output: {3, 3, 4, 5, 5, 5, 6}
- Explanation: In the first subarray of size 3: {1,2,3}, the value 3 is maximum, similarly for all such subarrays for size 3.
//function to find maximum in each subarray using sliding window approach
//使用滑动窗口方法找出每个子数组中的最大值的函数
vectormax_of_subarrays(vector arr, int n, int k){
vectormax_of_subarrays(vector arr, int n, int k){
int i=0,j=0;
int i=0,j=0;
dequedq;
dequedq;
dq.push_front(i++);
dq.push_front(i++);
while(i<k)
while(i<k)
{
while(!dq.empty()&&arr[dq.back()]<=arr[i])
while(!dq.empty()&&arr[dq.back()]<=arr[i])
dq.pop_back();
dq.pop_back();
dq.push_back(i++);
dq.push_back(i++);
}
vectorans;
vectorans;
while(i<n)
while(i<n)
{
ans.push_back(arr[dq.front()]);
ans.push_back(arr[dq.front()]);
while(!dq.empty()&&j>=dq.front())
while(!dq.empty()&&j>=dq.front())
{
dq.pop_front();
dq.pop_front();
}
j++;
j++;
while(!dq.empty()&&arr[dq.back()]<=arr[i])
while(!dq.empty()&&arr[dq.back()]<=arr[i])
dq.pop_back();
dq.pop_back();
dq.push_back(i++);
dq.push_back(i++);
}
ans.push_back(arr[dq.front()]);
ans.push_back(arr[dq.front()]);
return ans;
return ans;
}
- Time Complexity: O(n)
- Space Complexity: O(k)
560. Write a function to merge two sorted binary search tree
编写一个函数来合并两个已排序的二叉搜索树
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba6007 | 官方: 否 | 付费: 否
答案:
Input:
输入:
First BST
第一个BST
7
/ \
5 9
Second BST
第二个BST
4
/ \
3 12
Output: 3 4 5 6 7 9 12
输出:3 4 5 6 7 9 12
//Function to return a list of integers denoting the node
//函数返回一个整数列表,表示节点
//values of both the BST in a sorted order.
//两个BST按排序顺序排列的节点值。
void inorder(Node*root,vector&v){
void inorder(Node*root,vector&v){
if(root==NULL)
if(root==NULL)
return;
return;
inorder(root->left,v);
inorder(root->left,v);
v.push_back(root->data);
v.push_back(root->data);
inorder(root->right,v);
inorder(root->right,v);
}
vectormerge(vector v1,vector v2){
vectormerge(vector v1,vector v2){
vectorv;
vectorv;
int n1=v1.size(),n2=v2.size(),i=0,j=0;
int n1=v1.size(),n2=v2.size(),i=0,j=0;
while(i<n1&&j<n2){
while(i<n1&&j<n2){
if(v1[i]>v2[j]){
if(v1[i]>v2[j]){
v.push_back(v2[j]);
v.push_back(v2[j]);
j++;
j++;
}
else{
否则{
v.push_back(v1[i]);
v.push_back(v1[i]);
i++;
i++;
}
}
while(i<n1){
while(i<n1){
v.push_back(v1[i]);
v.push_back(v1[i]);
i++;
i++;
}
while(j<n2){
while(j<n2){
v.push_back(v2[j]);
v.push_back(v2[j]);
j++;
j++;
}
return v;
返回 v;
}
vectormerge(Node root1, Node root2)
vectormerge(Node root1, Node root2)
{
vectorv1,v2;
vectorv1,v2;
inorder(root1,v1);
中序遍历(root1,v1);
inorder(root2,v2);
中序遍历(root2,v2);
return merge(v1,v2);
返回merge(v1,v2);
}
- Time Complexity: O(m+n)
- Space Complexity: O(height of the first tree + height of the second tree)
561. Write a function to print all unique rows of the given matrix.
编写一个函数来打印给定矩阵的所有唯一行。
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba600a | 官方: 否 | 付费: 否
答案:
Input:
输入:
{{1, 1, 1, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 0, 1},
{1, 1, 1, 0, 0}}
Output:
输出:
{{1, 1, 1, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 1, 0}}
vector<vector
vector<vector> uniqueRow(int MMAX,int row,int col)
{
set<vector> st;
set<vector> st;
vector<vector> v;
vector<vector> v;
for(int i=0; i<row; i++) {
for(int i=0; i<row; i++) {
vectorv1;
vectorv1;
for(int j=0; j<col; j++) {
for(int j=0; j<col; j++) {
v1.push_back(Mi);
v1.push_back(Mi);
}
if(st.count(v1) == 0) {
if(st.count(v1) == 0) {
v.push_back(v1);
v.push_back(v1);
st.insert(v1);
st.insert(v1);
}
}
return v;
返回 v;
}
- Time Complexity: O( ROW x COL )
- Space Complexity: O( ROW )
562. Write a function to find number of subarrays with product less than K
编写一个函数,用于查找乘积小于 K 的子数组数量
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba600d | 官方: 否 | 付费: 否
答案:
- Input: arr = [1, 6, 2, 3, 2, 1], k = 12
- Output: 11
int numSubarrayProductLessThanK(vector
int numSubarrayProductLessThanK(vector& nums, int k) {
int ans=0;
int ans=0;
int pdt=1;
int pdt=1;
int left=0,right=0;
int left=0,right=0;
while(right<=nums.size()-1){
while(right<=nums.size()-1){
pdt*=nums[right];
pdt*=nums[right];
while(pdt>=k and left<nums.size()){
while(pdt>=k and left<nums.size()){
pdt/=nums[left];
pdt/=nums[left];
left++;
left++;
}
if(right-left>=0)
if(right-left>=0)
ans+=right-left+1;//since on adding a new element new subarrays formed is r-i+1;
ans+=right-left+1;//因为每添加一个新元素,新形成的子数组数量为 r-i+1;
right++;
right++;
}
return ans;
return ans;
}
- Time Complexity: O(n)
- Space Complexity: O(1)
563. Find the subsequence of length 3 with the highest product from a sequence of non-negative integers, with the elements in increasing order.
从非负整数序列中找出长度为 3 且乘积最大的递增子序列。
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a6058d557c902ba6010 | 官方: 否 | 付费: 否
答案:
- Input: n = 8 arr[ ] = {6, 7, 10, 1, 2, 3, 11, 12}
- Output: {10, 11, 12}
The three increasing elements of the given arrays are 10, 11, and 12, which form a three-size subsequence with the highest product.
给定数组的三个递增元素为 10、11 和 12,它们构成了乘积最大的三元素子序列。
vectormaxProductSubsequence(int *a , int n)
vectormaxProductSubsequence(int *a , int n)
{
sets;
sets;
long long largestOnLeft[n];
long long largestOnLeft[n];
for(int i=0;i<n;i++)
for(int i=0;i<n;i++)
{
s.insert(a[i]);
s.insert(a[i]);
auto it=s.lower_bound(a[i]);
auto it=s.lower_bound(a[i]);
if(it==s.begin())
if(it==s.begin())
{
largestOnLeft[i]=-1;
largestOnLeft[i]=-1;
continue;
continue;
}
it--;
it--;
largestOnLeft[i]=*it;
largestOnLeft[i]=*it;
}
int m=0;
int m=0;
long long p=INT_MIN;
long long p=INT_MIN;
vectorresult(3);
vectorresult(3);
result[0]=-1;
result[0]=-1;
for(int i=n-1;i>=0;i--)
for(int i=n-1;i>=0;i--)
{
if(a[i]>=m){
if(a[i]>=m){
m=a[i];}
m=a[i];}
else
else
{
if(largestOnLeft[i] !=-1)
if(largestOnLeft[i] !=-1)
{
if(largestOnLeft[i]a[i]m >p)
if(largestOnLeft[i]a[i]m >p)
{
p=largestOnLeft[i]a[i]m;
p=largestOnLeft[i]a[i]m;
result[0]=largestOnLeft[i];
result[0]=largestOnLeft[i];
result[1]=a[i];
result[1]=a[i];
result[2]=m;
result[2]=m;
}
}
}
}
return v;
返回 v;
}
- Time Complexity: O(nlog(n))
- Space Complexity: O(n)
564. Write a function to implement Quicksort on Doubly Linked List
编写一个函数在双向链表上实现快速排序
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba6013 | 官方: 否 | 付费: 否
答案:
- Input: 810176
- Output: 167810
class Solution{
class Solution{
public:
public:
Node partition(Node l, Node *h){
Node partition(Node l, Node *h){
//Your code goes here
//你的代码写在这里
Node*temp = h;
Node*temp = h;
Node*tt = l;
Node*tt = l;
Node*first = l;
Node*first = l;
while(tt != h){
while(tt != h){
if(tt->data <= temp->data){
if(tt->data <= temp->data){
swap(first->data, tt->data);
swap(first->data, tt->data);
first = first->next;
first = first->next;
}
tt = tt -> next;
tt = tt -> next;
}
swap(first-> data, h->data);
swap(first-> data, h->data);
return first;
return first;
}
};
void _quickSort(struct Node l, struct Node h)
void _quickSort(struct Node l, struct Node h)
{
if (h != NULL && l != h && l != h->next)
if (h != NULL && l != h && l != h->next)
{
Solution ob;
Solution ob;
struct Node *p = ob.partition(l, h);
struct Node *p = ob.partition(l, h);
_quickSort(l, p->prev);
_quickSort(l, p->prev);
_quickSort(p->next, h);
_quickSort(p->next, h);
}
}
void quickSort(struct Node *head)
void quickSort(struct Node *head)
{
struct Node *h = lastNode(head);
struct Node *h = lastNode(head);
_quickSort(head, h);
_quickSort(head, h);
}
- Time Complexity: O(n^2) in the worst case when the list is already sorted. O(nlog(n)) in the best and average case.
- Space Complexity: O(n)
565. Write a function to connect nodes at the same level of a binary tree
编写一个函数来连接二叉树中同一层级的节点
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba6016 | 官方: 否 | 付费: 否
答案:
Input: 100
输入: 100
/ \
13 15
/ \ \
14 1 20
Output: 100-> NULL
输出:100-> NULL
/ \
13 -> 15 -> NULL
13 -> 15 -> NULL
/ \ \
14 -> 1 -> 20 -> NULL
14 -> 1 -> 20 -> NULL
class Solution
类解决方案
{
public:
public:
//Function to connect nodes at the same level.
//用于连接同一层级节点的函数。
void connect(Node *p)
void connect(Node *p)
{
map<int,vector> m;
map<int,vector> m;
queueq;
queueq;
queuel;
queuel;
q.push(p);
q.push(p);
l.push(0);
l.push(0);
while(!q.empty())
while(!q.empty())
{
Node *temp=q.front();
Node *temp=q.front();
int level=l.front();
int level=l.front();
q.pop();
q.pop();
l.pop();
l.pop();
m[level].push_back(temp);
m[level].push_back(temp);
if(temp->left!=NULL)
if(temp->left!=NULL)
{
q.push(temp->left);
q.push(temp->left);
l.push(level+1);
l.push(level+1);
}
if(temp->right!=NULL)
if(temp->right!=NULL)
{
q.push(temp->right);
q.push(temp->right);
l.push(level+1);
l.push(level+1);
}
}
for(map<int,vector> ::iterator it=m.begin();it!=m.end();it++)
for(map<int,vector> ::iterator it=m.begin();it!=m.end();it++)
{
vectortemp1=it->second;
vectortemp1=it->second;
for(int i=0;i<temp1.size()-1;i++)
for(int i=0;i<temp1.size()-1;i++)
{
temp1[i]->nextRight=temp1[i+1];
temp1[i]->nextRight=temp1[i+1];
}
temp1[temp1.size()-1]->nextRight=NULL;
temp1[temp1.size()-1]->nextRight=NULL;
}
}
};
- Time Complexity: O(n)
- Space Complexity: O(n)
566. Write a function to find number of structurally unique binary trees are possible
编写一个函数来查找可能的结构独特二叉搜索树的数量
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba6019 | 官方: 否 | 付费: 否
答案:
Input: N = 3
输入:N = 3
Output: 5 for N = 3, there are 5 possible BSTs:
输出:5,对于N = 3,有5种可能的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
class Solution
类解决方案
{
public:
public:
//function to calculate binomial coefficient C(n,k)
//计算二项式系数C(n,k)的函数
long long int binomialCoefficient(long long int n, long long int k)
long long int binomialCoefficient(long long int n, long long int k)
{
long long int res = 1;
long long int res = 1;
if (k > n - k)
if (k > n - k)
k = n - k;
k = n - k;
for (long long int i = 0; i < k; ++i)
for (long long int i = 0; i < k; ++i)
{
res *= (n - i);
res *= (n - i);
res /= (i + 1);
res /= (i + 1);
}
return res;
返回 res;
}
//function to calculate Nth Catalan Number
//函数用于计算第N个卡特兰数
long long int catalanNumber(long long in n)
long long int catalanNumber(long long in n)
{
// Calculate value of 2nCn
//计算2nCn的值
long long int C = binomialCoefficient(2*n, n);
long long int C = binomialCoefficient(2*n, n);
// return 2nCn/(n+1)
//返回2nCn/(n+1)
return C/(n+1);
return C/(n+1);
}
//Function to return the total number of possible unique BST.
//函数用于返回可能的唯一二叉搜索树的总数
long long int numOfUniqueBinarySearchTrees(int n)
long long int numOfUniqueBinarySearchTrees(int n)
{
// find nth catalan number
//查找第n个卡特兰数
long long int countOfUniqueBinarySearchTrees = catalanNumber(n);
long long int countOfUniqueBinarySearchTrees = catalanNumber(n);
// return nth catalan number
// 返回第n个卡特兰数
return countOfUniqueBinarySearchTrees;
返回唯一二叉搜索树的计数;
}
};
- Time Complexity: O(n)
- Space Complexity: O(1)
567. Implement LRU(Least Recently Used) Cache
实现LRU(最近最少使用)缓存
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba601c | 官方: 否 | 付费: 否
答案:
class LRUCache
class LRUCache
{
private:
private:
class node_t {
class node_t {
public:
public:
int key;
int key;
int value;
int value;
node_t * next;
node_t * next;
node_t * prev;
node_t * prev;
};
int cap;
int cap;
node_t head;
node_t head;
unordered_map<int, node_t*> tbl;
unordered_map<int, node_t*> tbl;
void remove_node(node_t * node) {
void remove_node(node_t * node) {
node->next->prev = node->prev;
node->next->prev = node->prev;
node->prev->next = node->next;
node->prev->next = node->next;
}
void add_node(node_t * node) {
void add_node(node_t * node) {
node->next = head.next;
node->next = head.next;
node->prev = &head;
node->prev = &head;
head.next = node;
head.next = node;
node->next->prev = node;
node->next->prev = node;
}
public:
public:
//Constructor for initializing the cache capacity with the given value.
//用于用给定值初始化缓存容量的构造函数。
LRUCache(int cap): cap(cap)
LRUCache(int cap): cap(cap)
{
// code here
//此处为代码
head.prev = &head;
head.prev = &head;
head.next = &head;
head.next = &head;
}
//Function to return value corresponding to the key.
//用于返回与键对应的值的函数。
int get(int key)
int get(int key)
{
// your code here
//此处为你的代码
unordered_map<int, node_t*>::iterator it = tbl.find(key);
unordered_map<int, node_t*>::iterator it = tbl.find(key);
if(it==tbl.end())
if(it==tbl.end())
return -1;
return -1;
remove_node(it->second);
remove_node(it->second);
add_node(it->second);
add_node(it->second);
return it->second->value;
返回 it->second->value;
}
//Function for storing key-value pair.
//存储键值对的函数。
void set(int key, int value)
void set(int key, int value)
{
// your code here
//此处为你的代码
unordered_map<int, node_t*>::iterator it = tbl.find(key);
unordered_map<int, node_t*>::iterator it = tbl.find(key);
if(it!=tbl.end())
if(it!=tbl.end())
{
remove_node(it->second);
remove_node(it->second);
add_node(it->second);
add_node(it->second);
it->second->value = value;
it->second->value = value;
}
else {
否则 {
node_t * node = new node_t;
node_t * node = new node_t;
node->key = key;
node->key = key;
node->value = value;
node->value = value;
add_node(node);
add_node(node);
tbl[key] = node;
tbl[key] = node;
if(tbl.size()>cap) {
if(tbl.size()>cap) {
auto * old_node = head.prev;
auto * old_node = head.prev;
tbl.erase(old_node->key);
tbl.erase(old_node->key);
remove_node(old_node);
remove_node(old_node);
delete old_node;
delete old_node;
}
}
}
};
- Time Complexity: O(1) to get an element
- Space Complexity: O(n)
568. Write a function to determine whether duplicate elements in a given array are within a given distance of each other.
编写一个函数,用于确定给定数组中重复元素之间的间隔是否在给定距离内。
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba601f | 官方: 否 | 付费: 否
答案:
- Input: arr[] = {1, 2, 3, 4, 2, 1, 2} range=3
- Output: True
class Solution {
class Solution {
public:
public:
bool checkDuplicatesWithinRange(vector
bool checkDuplicatesWithinRange(vectorarr, int range)
{
// Creating an empty hashset
// 创建一个空的哈希集合
unordered_setmyset;
unordered_setmyset;
// Traversing the input array
// 遍历输入数组
for (int i = 0; i < arr.size(); i++)
for (int i = 0; i < arr.size(); i++)
{
// If already present in hashset, then we found a duplicate within range distance
// 如果哈希集合中已存在,则说明在给定距离内发现了重复元素
if (myset.find(arr[i]) != myset.end())
if (myset.find(arr[i]) != myset.end())
return true;
返回 true;
// Add this item to hashset
// 将此元素添加到哈希集合
myset.insert(arr[i]);
myset.insert(arr[i]);
// Remove the range+1 distant item from the hashset
// 从哈希集合中移除距离为 range+1 的过期元素
if (i >= range)
if (i >= range)
myset.erase(arr[i-range]);
myset.erase(arr[i-range]);
}
return false;
返回 false;
}
};
- Time Complexity: O(n)
- Space Complexity: O(n)
569. Write a recursive function to calculate the height of a binary tree in Java.
编写一个递归函数,用 Java 计算二叉树的高度。
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba6022 | 官方: 否 | 付费: 否
答案:
- Consider that every node of a tree represents a class called Node as given below:
public class Node{
public class Node{
int data;
int data;
Node left;
Node left;
Node right;
Node right;
}
- Then the height of the binary tree can be found as follows:
int heightOfBinaryTree(Node node)
int heightOfBinaryTree(Node node)
{
if (node == null)
if (node == null)
return 0; // If node is null then height is 0 for that node.
return 0; // 如果节点为 null,则该节点的高度为 0。
else
else
{
// compute the height of each subtree
// 计算每个子树的高度
int leftHeight = heightOfBinaryTree(node.left);
int leftHeight = heightOfBinaryTree(node.left);
int rightHeight = heightOfBinaryTree(node.right);
int rightHeight = heightOfBinaryTree(node.right);
//use the larger among the left and right height and plus 1 (for the root)
// 使用左子树和右子树中较大的高度,并加 1(用于根节点)
return Math.max(leftHeight, rightHeight) + 1;
return Math.max(leftHeight, rightHeight) + 1;
}
}
570. Write Java code to count number of nodes in a binary tree
编写 Java 代码来计算二叉树中的节点数
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: coding
- 分类: fullstack
- id: 69b37a6058d557c902ba6025 | 官方: 否 | 付费: 否
答案:
int countNodes(Node root)
int countNodes(Node root)
{
int count = 1; //Root itself should be counted
int count = 1; //根节点本身应被计数
if (root ==null)
if (root ==null)
return 0;
return 0;
else
else
{
count += countNodes(root.left);
count += countNodes(root.left);
count += countNodes(root.right);
count += countNodes(root.right);
return count;
return count;
}
}
571. Print Left view of any binary trees.
打印任意二叉树的左视图。
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a6058d557c902ba6028 | 官方: 否 | 付费: 否
答案:
- The main idea to solve this problem is to traverse the tree in pre order manner and pass the level information along with it. If the level is visited for the first time, then we store the information of the current node and the current level in the hashmap. Basically, we are getting the left view by noting the first node of every level.
- At the end of traversal, we can get the solution by just traversing the map.
- Consider the following tree as example for finding the left view:
- Left view of a binary tree in Java:
import java.util.HashMap;
import java.util.HashMap;
//to store a Binary Tree node
//存储二叉树节点
class Node
class Node
{
int data;
int data;
Node left = null, right = null;
Node left = null, right = null;
Node(int data) {
Node(int data) {
this.data = data;
this.data = data;
}
}
public class InterviewBit
public class InterviewBit
{
// traverse nodes in pre-order way
//以前序遍历方式遍历节点
public static void leftViewUtil(Node root, int level, HashMap<Integer, Integer> map)
public static void leftViewUtil(Node root, int level, HashMap<Integer, Integer> map)
{
if (root == null) {
if (root == null) {
return;
return;
}
// if you are visiting the level for the first time
//如果你第一次访问该层级
// insert the current node and level info to the map
//将当前节点和层级信息插入映射中
if (!map.containsKey(level)) {
if (!map.containsKey(level)) {
map.put(level, root.data);
map.put(level, root.data);
}
leftViewUtil(root.left, level + 1, map);
leftViewUtil(root.left, level + 1, map);
leftViewUtil(root.right, level + 1, map);
leftViewUtil(root.right, level + 1, map);
}
// to print left view of binary tree
//打印二叉树的左视图
public static void leftView(Node root)
public static void leftView(Node root)
{
// create an empty HashMap to store first node of each level
// 创建一个空的HashMap来存储每一层的第一个节点
HashMap<Integer, Integer> map = new HashMap<>();
HashMap<Integer, Integer> map = new HashMap<>();
// traverse the tree and find out the first nodes of each level
// 遍历树并找出每一层的第一个节点
leftViewUtil(root, 1, map);
leftViewUtil(root, 1, map);
// iterate through the HashMap and print the left view
// 遍历HashMap并打印左视图
for (int i = 0; i <map.size(); i++) {
for (int i = 0; i <map.size(); i++) {
System.out.print(map.get(i) + " ");
System.out.print(map.get(i) + " ");
}
}
public static void main(String[] args)
public static void main(String[] args)
{
Node root = new Node(4);
Node root = new Node(4);
root.left = new Node(2);
root.left = new Node(2);
root.right = new Node(6);
root.right = new Node(6);
root.left.left = new Node(1);
root.left.left = new Node(1);
root.left.left = new Node(3);
root.left.left = new Node(3);
root.right.left = new Node(5);
root.right.left = new Node(5);
root.right.right = new Node(7);
root.right.right = new Node(7);
root.right.left.left = new Node(9);
root.right.left.left = new Node(9);
leftView(root);
leftView(root);
}
}
572. Given an m x n 2D grid map of '1’s which represents land and '0’s that represents water return the number of islands (surrounded by water and formed by connecting adjacent lands in 2 directions - vertically or horizontally).
给定一个 m x n 的二维网格,其中 '1' 表示陆地,'0' 表示水,返回岛屿的数量(岛屿被水包围,并由垂直或水平两个方向相邻的陆地连接形成)。
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a6058d557c902ba602b | 官方: 否 | 付费: 否
答案:
Assume that the boundary cases - which are all four edges of the grid are surrounded by water.
假设边界情况——即网格的所有四条边都被水包围。
Constraints are:
约束条件为:
m == grid.lengthn == grid[i].length1
m == grid.length,n == grid[i].length,1
Example:
示例:
Input: grid = [[“1” , “1” , “1” , “0” , “0”],[“1” , “1” , “0” , “0” , “0”],[“0” , “0” , “1” , “0” , “1”],[“0” , “0” , “0” , “1” , “1”]]
输入:grid = [[“1” , “1” , “1” , “0” , “0”],[“1” , “1” , “0” , “0” , “0”],[“0” , “0” , “1” , “0” , “1”],[“0” , “0” , “0” , “1” , “1”]]
Output: 3
输出:3
class InterviewBit {
class InterviewBit {
public int numberOfIslands(char[][] grid) {
public int numberOfIslands(char[][] grid) {
if(grid==null || grid.length==0||grid[0].length==0)
if(grid==null || grid.length==0||grid[0].length==0)
return 0;
return 0;
int m = grid.length;
int m = grid.length;
int n = grid[0].length;
int n = grid[0].length;
int count=0;
int count=0;
for(int i=0; i<m; i++){
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
for(int j=0; j<n; j++){
if(gridi=='1'){
if(gridi=='1'){
count++;
count++;
mergeIslands(grid, i, j);
mergeIslands(grid, i, j);
}
}
}
return count;
return count;
}
public void mergeIslands(char[][] grid, int i, int j){
public void mergeIslands(char[][] grid, int i, int j){
int m=grid.length;
int m=grid.length;
int n=grid[0].length;
int n=grid[0].length;
if(i<0||i>=m||j<0||j>=n||gridi!='1')
if(i<0||i>=m||j<0||j>=n||gridi!='1')
return;
return;
gridi='X';
gridi='X';
mergeIslands(grid, i-1, j);
mergeIslands(grid, i-1, j);
mergeIslands(grid, i+1, j);
mergeIslands(grid, i+1, j);
mergeIslands(grid, i, j-1);
mergeIslands(grid, i, j-1);
mergeIslands(grid, i, j+1);
mergeIslands(grid, i, j+1);
}
}
573. What is topological sorting in a graph?
什么是图中的拓扑排序?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a6058d557c902ba602e | 官方: 否 | 付费: 否
答案:
- Topological sorting is a linear ordering of vertices such that for every directed edge ij, vertex i comes before j in the ordering.
- Topological sorting is only possible for Directed Acyclic Graph (DAG).
Applications:
jobs scheduling from the given dependencies among jobs.根据给定作业间的依赖关系进行作业调度
ordering of formula cell evaluation in spreadsheets
电子表格中公式单元格求值的排序
ordering of compilation tasks to be performed in make files,
在make文件中执行的编译任务的排序
data serialization
数据序列化
resolving symbol dependencies in linkers.
链接器中解析符号依赖- Topological Sort Code in Java:
// V - total vertices
// V - 总顶点数
// visited - boolean array to keep track of visited nodes
// visited - 布尔数组,用于跟踪已访问的节点
// graph - adjacency list.
// 图 - 邻接表。
// Main Topological Sort Function.
// 主要拓扑排序函数。
void topologicalSort()
void topologicalSort()
{
Stackstack = new Stack ();
Stackstack = new Stack ();
// Mark all the vertices as not visited
// 将所有顶点标记为未访问
boolean visited[] = new boolean[V];
boolean visited[] = new boolean[V];
for (int j = 0; j < V; j++){
for (int j = 0; j < V; j++){
visited[j] = false;
visited[j] = false;
}
// Call the util function starting from all vertices one by one
// 从每个顶点逐一调用工具函数
for (int i = 0; i < V; i++)
for (int i = 0; i < V; i++)
if (visited[i] == false)
if (visited[i] == false)
topologicalSortUtil(i, visited, stack);
topologicalSortUtil(i, visited, stack);
// Print contents of stack -> result of topological sort
// 打印栈的内容 -> 拓扑排序结果
while (stack.empty() == false)
while (stack.empty() == false)
System.out.print(stack.pop() + " ");
System.out.print(stack.pop() + " ");
}
// A helper function used by topologicalSort
// 由拓扑排序使用的辅助函数
void topologicalSortUtil(int v, boolean visited[],
void topologicalSortUtil(int v, boolean visited[],
Stackstack)
Stackstack)
{
// Mark the current node as visited.
// 将当前节点标记为已访问。
visited[v] = true;
visited[v] = true;
Integer i;
Integer i;
// Recur for all the vertices adjacent to the current vertex
// 递归处理当前顶点的所有相邻顶点
Iteratorit = graph.get(v).iterator();
Iteratorit = graph.get(v).iterator();
while (it.hasNext()) {
while (it.hasNext()) {
i = it.next();
i = it.next();
if (!visited[i])
if (!visited[i])
topologicalSortUtil(i, visited, stack);
topologicalSortUtil(i, visited, stack);
}
// Push current vertex to stack that saves result
// 将当前顶点推入保存结果的栈中
stack.push(new Integer(v));
stack.push(new Integer(v));
}
Conclusion
结论
In this post, we covered the most important and frequently asked Data Structures interview questions. We've also included some pointers and tricks to help you prepare for the interview. When preparing for the product-based companies interview, keep in mind that the Data Structures interview is a critical component of the process. It is critical that you are well prepared for the interview because it will determine whether or not you are hired. As a result, it is critical to begin planning as soon as possible.
在本文中,我们涵盖了最重要且经常被问到的数据结构面试问题。我们还包含了一些提示和技巧,以帮助您为面试做准备。在为基于产品的公司面试做准备时,请记住,数据结构面试是该过程中的关键组成部分。充分准备面试至关重要,因为它将决定您是否被录用。因此,尽早开始规划至关重要。
Additional Interview Resources
其他面试资源
- Programming: DSA - https://www.interviewbit.com/courses/programming/
- Data Structure MCQ - https://www.interviewbit.com/data-structure-mcq/
- Best Books for Data Structures and Algorithms - https://www.interviewbit.com/blog/data-structures-and-algorithms-books/
- Best Data Structures and Algorithms Course - https://www.interviewbit.com/blog/best-courses-for-data-structures-and-algorithms/
- Free Java DSA Certification Course - https://www.scaler.com/topics/course/dsa-beginners-java/
- Algorithm Interview Questions - https://www.interviewbit.com/algorithm-interview-questions/
- Master Data Structures and Algorithms With the Scaler Academy Program - https://www.scaler.com/courses/data-structures-and-algorithms/
- Difference Between Array and Linked List - https://www.scaler.com/topics/difference-between-array-and-linked-list/
574. What Python features reduce code complexity in DSA solutions?
哪些 Python 特性降低了 DSA 解决方案中的代码复杂度?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a6058d557c902ba6031 | 官方: 否 | 付费: 否
答案:
Python provides dynamic typing, which reduces boilerplate code. Built-in data structures like lists, sets, and dictionaries simplify logic. List comprehensions help write compact loops. Functions and modules help organize code neatly. These features allow shorter and cleaner DSA solutions.
Python 提供了动态类型,减少了样板代码。像列表、集合和字典这样的内置数据结构简化了逻辑。列表推导式有助于编写紧凑的循环。函数和模块有助于整齐地组织代码。这些特性允许更短、更简洁的 DSA 解决方案。
575. What role do Python built-ins play in DSA problem-solving interviews?
在DSA问题解决面试中,Python内置函数扮演什么角色?
- 知识点: 算法与数据结构 (主题: data-structures, algorithms;标签: interviewbit, data-structure, topic-specific, data-structures, algorithms)
- 类型: technical | 难度: medium | 子类型: concept
- 分类: fullstack
- id: 69b37a6058d557c902ba6034 | 官方: 否 | 付费: 否
答案:
Built-ins like sort, min, max, and sum simplify solutions. They reduce code length and improve readability. However, candidates must know their time complexity. Interviewers expect proper justification for using them.
像sort、min、max和sum这样的内置函数简化了解决方案。它们减少了代码长度并提高了可读性。然而,候选人必须知道它们的时间复杂度。面试官期望对使用它们给出合理的理由。
评论